Dorn4449 commited on
Commit
41923d2
·
verified ·
1 Parent(s): e739962

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -0
app.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ultralytics import YOLO
2
+ import cv2
3
+ import gradio as gr
4
+ import torch
5
+
6
+ # Load YOLOv8 model
7
+ model = YOLO('yolov8n.pt')
8
+
9
+ # Set the stream URL
10
+ stream_url = "https://edge01.london.nginx.hdontap.com/hosb5/ng_showcase-coke_bottle-street_fixed.stream/chunklist_w464099566.m3u8"
11
+
12
+ # Low-resolution for inference
13
+ LOW_RES = (320, 180)
14
+
15
+ def detect_and_draw(frame):
16
+ # Resize frame to low resolution for faster inference
17
+ low_res_frame = cv2.resize(frame, LOW_RES)
18
+
19
+ # Perform YOLOv8 inference
20
+ results = model(low_res_frame)
21
+
22
+ # Scale bounding boxes
23
+ scale_x = frame.shape[1] / LOW_RES[0]
24
+ scale_y = frame.shape[0] / LOW_RES[1]
25
+
26
+ # Draw bounding boxes on high-res frame
27
+ for detection in results[0].boxes.data:
28
+ x1, y1, x2, y2, conf, cls = detection
29
+ x1, y1, x2, y2 = int(x1*scale_x), int(y1*scale_y), int(x2*scale_x), int(y2*scale_y)
30
+ label = f"{results[0].names[int(cls)]} {conf:.2f}"
31
+ cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
32
+ cv2.putText(frame, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
33
+
34
+ return frame
35
+
36
+ def process_stream():
37
+ cap = cv2.VideoCapture(stream_url)
38
+ frame_count = 0
39
+ while cap.isOpened():
40
+ ret, frame = cap.read()
41
+ if not ret:
42
+ break
43
+
44
+ frame_count += 3
45
+ if frame_count % 30 == 0: # Process every 30th frame
46
+ result = detect_and_draw(frame)
47
+ result_rgb = cv2.cvtColor(result, cv2.COLOR_BGR2RGB)
48
+ yield result_rgb
49
+
50
+ cap.release()
51
+
52
+ # Gradio interface for live video stream
53
+ iface = gr.Interface(
54
+ fn=process_stream,
55
+ inputs=None,
56
+ outputs="image",
57
+ live=True,
58
+ title="YOLOv8 Real-Time Object Detection",
59
+ description="Live stream processed with YOLOv8 for real-time object detection."
60
+ )
61
+
62
+ if __name__ == "__main__":
63
+ if torch.cuda.is_available():
64
+ model.to('cuda')
65
+ iface.queue()
66
+ iface.launch()