|
| 1 | +import cv2 |
| 2 | +import numpy as np |
| 3 | +import streamlit as st |
| 4 | +from dotenv import load_dotenv |
| 5 | +from ultralytics import YOLO |
| 6 | + |
| 7 | +load_dotenv() |
| 8 | + |
| 9 | +with st.sidebar: |
| 10 | + model_name = st.selectbox( |
| 11 | + label="Select a model", |
| 12 | + options=[ |
| 13 | + "yolov8n.pt", |
| 14 | + "yolov9c.pt", |
| 15 | + "yolov10n.pt", |
| 16 | + # https://docs.ultralytics.com/models/yolov8/#supported-tasks-and-modes |
| 17 | + ], |
| 18 | + key="model_name", |
| 19 | + index=0, |
| 20 | + ) |
| 21 | + |
| 22 | + |
| 23 | +st.title("Object detection") |
| 24 | + |
| 25 | +st.info("Upload an image and AI will detect objects in the image.") |
| 26 | + |
| 27 | +uploaded_file = st.file_uploader( |
| 28 | + "Upload an image", |
| 29 | + type=( |
| 30 | + "jpg", |
| 31 | + "jpeg", |
| 32 | + "png", |
| 33 | + "gif", |
| 34 | + "bmp", |
| 35 | + "tiff", |
| 36 | + ), |
| 37 | +) |
| 38 | +if uploaded_file is not None: |
| 39 | + button = st.button("Detect objects") |
| 40 | + |
| 41 | +row1_left, row1_right = st.columns(2) |
| 42 | +with row1_left: |
| 43 | + if uploaded_file: |
| 44 | + st.image( |
| 45 | + uploaded_file, |
| 46 | + use_column_width=True, |
| 47 | + caption="Input image", |
| 48 | + ) |
| 49 | + |
| 50 | +with row1_right: |
| 51 | + if uploaded_file and button: |
| 52 | + with st.spinner("Thinking..."): |
| 53 | + model = YOLO(model_name) |
| 54 | + bytes_data = uploaded_file.getvalue() |
| 55 | + cv2_img = cv2.imdecode(np.frombuffer(bytes_data, np.uint8), cv2.IMREAD_COLOR) |
| 56 | + results = model(cv2_img, conf=0.5, classes=[0]) |
| 57 | + output_img = results[0].plot(labels=True, conf=True) |
| 58 | + output_img = cv2.cvtColor(output_img, cv2.COLOR_BGR2RGB) |
| 59 | + categories = results[0].boxes.cls |
| 60 | + person_num = len(categories) |
| 61 | + |
| 62 | + # Output |
| 63 | + st.image( |
| 64 | + output_img, |
| 65 | + use_column_width=True, |
| 66 | + caption="Output image", |
| 67 | + ) |
| 68 | + st.text(f"Number of people: {person_num}") |
0 commit comments