Update app.py
Browse files
app.py
CHANGED
|
@@ -6,7 +6,7 @@ import numpy as np
|
|
| 6 |
# Load the YOLOv5 model
|
| 7 |
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True)
|
| 8 |
|
| 9 |
-
# Function to run inference on an image
|
| 10 |
def run_inference(image):
|
| 11 |
# Convert the image from PIL format to a format compatible with OpenCV
|
| 12 |
image = np.array(image)
|
|
@@ -14,19 +14,28 @@ def run_inference(image):
|
|
| 14 |
# Run YOLOv5 inference
|
| 15 |
results = model(image)
|
| 16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
# Convert the annotated image from BGR to RGB for display
|
| 18 |
annotated_image = results.render()[0]
|
| 19 |
annotated_image = cv2.cvtColor(annotated_image, cv2.COLOR_BGR2RGB)
|
| 20 |
|
| 21 |
-
return annotated_image
|
| 22 |
|
| 23 |
# Create the Gradio interface
|
| 24 |
interface = gr.Interface(
|
| 25 |
fn=run_inference,
|
| 26 |
inputs=gr.Image(type="pil"),
|
| 27 |
-
outputs=
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
| 30 |
)
|
| 31 |
|
| 32 |
# Launch the app
|
|
|
|
| 6 |
# Load the YOLOv5 model
|
| 7 |
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True)
|
| 8 |
|
| 9 |
+
# Function to run inference on an image and count objects
|
| 10 |
def run_inference(image):
|
| 11 |
# Convert the image from PIL format to a format compatible with OpenCV
|
| 12 |
image = np.array(image)
|
|
|
|
| 14 |
# Run YOLOv5 inference
|
| 15 |
results = model(image)
|
| 16 |
|
| 17 |
+
# Extract detection results
|
| 18 |
+
detections = results.pandas().xyxy[0]
|
| 19 |
+
|
| 20 |
+
# Count objects by category
|
| 21 |
+
object_counts = detections['name'].value_counts().to_dict()
|
| 22 |
+
|
| 23 |
# Convert the annotated image from BGR to RGB for display
|
| 24 |
annotated_image = results.render()[0]
|
| 25 |
annotated_image = cv2.cvtColor(annotated_image, cv2.COLOR_BGR2RGB)
|
| 26 |
|
| 27 |
+
return annotated_image, object_counts
|
| 28 |
|
| 29 |
# Create the Gradio interface
|
| 30 |
interface = gr.Interface(
|
| 31 |
fn=run_inference,
|
| 32 |
inputs=gr.Image(type="pil"),
|
| 33 |
+
outputs=[
|
| 34 |
+
gr.Image(type="pil"),
|
| 35 |
+
gr.JSON(label="Object Counts") # Add JSON output for object counts
|
| 36 |
+
],
|
| 37 |
+
title="YOLOv5 Object Detection with Counts",
|
| 38 |
+
description="Upload an image to run YOLOv5 object detection, see the annotated results, and view the count of detected objects by category."
|
| 39 |
)
|
| 40 |
|
| 41 |
# Launch the app
|