Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
import cv2
|
| 4 |
+
import numpy as np
|
| 5 |
+
from PIL import Image
|
| 6 |
+
|
| 7 |
+
# Load the YOLOv5 model
|
| 8 |
+
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True)
|
| 9 |
+
|
| 10 |
+
# Function to perform object detection
|
| 11 |
+
def detect_objects(image):
|
| 12 |
+
# Convert the image to a numpy array
|
| 13 |
+
img_array = np.array(image)
|
| 14 |
+
|
| 15 |
+
# Perform object detection
|
| 16 |
+
results = model(img_array)
|
| 17 |
+
|
| 18 |
+
# Draw bounding boxes and labels
|
| 19 |
+
for index, row in results.pandas().xyxy[0].iterrows():
|
| 20 |
+
x1, y1, x2, y2 = int(row['xmin']), int(row['ymin']), int(row['xmax']), int(row['ymax'])
|
| 21 |
+
label = row['name']
|
| 22 |
+
cv2.rectangle(img_array, (x1, y1), (x2, y2), (0, 255, 0), 2)
|
| 23 |
+
cv2.putText(img_array, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (36, 255, 12), 2)
|
| 24 |
+
|
| 25 |
+
# Convert the numpy array back to an image
|
| 26 |
+
output_image = Image.fromarray(img_array)
|
| 27 |
+
return output_image
|
| 28 |
+
|
| 29 |
+
# Set up the Gradio interface
|
| 30 |
+
interface = gr.Interface(
|
| 31 |
+
fn=detect_objects,
|
| 32 |
+
inputs=gr.Image(source='webcam', tool='editor', type="pil"),
|
| 33 |
+
outputs=gr.Image(type="pil"),
|
| 34 |
+
live=True,
|
| 35 |
+
title="Real-time Object Detection with YOLOv5"
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
# Launch the interface
|
| 39 |
+
interface.launch()
|