JishnuSetia commited on
Commit
9083db7
·
verified ·
1 Parent(s): 60a165a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -0
app.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import cv2
4
+ import numpy as np
5
+
6
+ # Load YOLOv5 model
7
+ def load_model():
8
+ return torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True)
9
+
10
+ model = load_model()
11
+
12
+ # YOLOv5 object detection function
13
+ def yolo_object_detection(frame):
14
+ # Convert Gradio's RGB frame to BGR for OpenCV processing
15
+ img_bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
16
+
17
+ # Perform YOLOv5 inference
18
+ results = model(img_bgr)
19
+ detections = results.pandas().xyxy[0]
20
+
21
+ # Draw bounding boxes and labels
22
+ for _, row in detections.iterrows():
23
+ x1, y1, x2, y2 = int(row['xmin']), int(row['ymin']), int(row['xmax']), int(row['ymax'])
24
+ label = f"{row['name']} {row['confidence']:.2f}"
25
+ cv2.rectangle(img_bgr, (x1, y1), (x2, y2), (255, 0, 0), 2)
26
+ cv2.putText(img_bgr, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (36, 255, 12), 2)
27
+
28
+ # Convert back to RGB for Gradio display
29
+ img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
30
+ return img_rgb
31
+
32
+ # Gradio interface for real-time object detection
33
+ with gr.Blocks() as demo:
34
+ with gr.Row():
35
+ with gr.Column():
36
+ # Video input from webcam
37
+ input_img = gr.Image(sources=["webcam"], type="numpy", label="Webcam Input")
38
+ with gr.Column():
39
+ # Output with detected objects
40
+ output_img = gr.Image(streaming=True, label="YOLOv5 Object Detection Output")
41
+
42
+ # Stream YOLOv5 object detection
43
+ input_img.stream(yolo_object_detection, inputs=[input_img], outputs=[output_img],
44
+ time_limit=30, stream_every=0.1, concurrency_limit=30)
45
+
46
+ # Launch the app
47
+ demo.launch()