File size: 1,267 Bytes
107566b
 
5f09a7f
107566b
 
 
5f09a7f
107566b
94c1933
107566b
 
 
 
 
5f09a7f
107566b
94c1933
 
 
 
 
 
5f09a7f
 
 
107566b
94c1933
107566b
 
 
 
 
94c1933
 
 
 
 
 
107566b
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import gradio as gr
import cv2
import torch
import numpy as np

# Load the YOLOv5 model
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True)

# Function to run inference on an image and count objects
def run_inference(image):
    # Convert the image from PIL format to a format compatible with OpenCV
    image = np.array(image)

    # Run YOLOv5 inference
    results = model(image)

    # Extract detection results
    detections = results.pandas().xyxy[0]

    # Count objects by category
    object_counts = detections['name'].value_counts().to_dict()

    # Convert the annotated image from BGR to RGB for display
    annotated_image = results.render()[0]
    annotated_image = cv2.cvtColor(annotated_image, cv2.COLOR_BGR2RGB)

    return annotated_image, object_counts

# Create the Gradio interface
interface = gr.Interface(
    fn=run_inference,
    inputs=gr.Image(type="pil"),
    outputs=[
        gr.Image(type="pil"),
        gr.JSON(label="Object Counts")  # Add JSON output for object counts
    ],
    title="YOLOv5 Object Detection with Counts",
    description="Upload an image to run YOLOv5 object detection, see the annotated results, and view the count of detected objects by category."
)

# Launch the app
interface.launch()