Spaces:
Sleeping
Sleeping
Create CrowdDetection.py
Browse files- CrowdDetection.py +65 -0
CrowdDetection.py
ADDED
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import torch
|
3 |
+
import cv2
|
4 |
+
from ultralytics import YOLO
|
5 |
+
|
6 |
+
# Crowd Detection Class
|
7 |
+
class CrowdDetection:
|
8 |
+
def __init__(self, yolo_model_path="yolov8n.pt", crowd_threshold=10):
|
9 |
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
10 |
+
self.model = YOLO(yolo_model_path).to(self.device) # Move to GPU
|
11 |
+
self.model.nms = 0.5 # Set NMS threshold
|
12 |
+
self.crowd_threshold = crowd_threshold
|
13 |
+
|
14 |
+
def detect_crowd(self, video_path):
|
15 |
+
cap = cv2.VideoCapture(video_path)
|
16 |
+
output_path = "output_crowd.mp4"
|
17 |
+
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
|
18 |
+
out = cv2.VideoWriter(output_path, fourcc, int(cap.get(cv2.CAP_PROP_FPS)),
|
19 |
+
(int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))))
|
20 |
+
|
21 |
+
while cap.isOpened():
|
22 |
+
ret, frame = cap.read()
|
23 |
+
if not ret:
|
24 |
+
break
|
25 |
+
|
26 |
+
results = self.model(frame)
|
27 |
+
person_count = 0
|
28 |
+
|
29 |
+
for result in results:
|
30 |
+
boxes = result.boxes.xyxy.cpu().numpy()
|
31 |
+
classes = result.boxes.cls.cpu().numpy()
|
32 |
+
|
33 |
+
for box, cls in zip(boxes, classes):
|
34 |
+
if int(cls) == 0: # YOLO class ID 0 = "person"
|
35 |
+
person_count += 1
|
36 |
+
x1, y1, x2, y2 = map(int, box)
|
37 |
+
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
|
38 |
+
cv2.putText(frame, "Person", (x1, y1 - 10),
|
39 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
|
40 |
+
|
41 |
+
alert_text = "Crowd Alert!" if person_count > self.crowd_threshold else f"People: {person_count}"
|
42 |
+
cv2.putText(frame, alert_text, (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1,
|
43 |
+
(0, 0, 255) if person_count > self.crowd_threshold else (0, 255, 0), 2)
|
44 |
+
|
45 |
+
out.write(frame)
|
46 |
+
|
47 |
+
cap.release()
|
48 |
+
out.release()
|
49 |
+
return output_path
|
50 |
+
|
51 |
+
# Gradio Function
|
52 |
+
def process_video(video):
|
53 |
+
detector = CrowdDetection()
|
54 |
+
return detector.detect_crowd(video)
|
55 |
+
|
56 |
+
# Gradio Interface
|
57 |
+
interface = gr.Interface(
|
58 |
+
fn=process_video,
|
59 |
+
inputs=gr.Video(label="Upload Video"),
|
60 |
+
outputs=gr.Video(label="Processed Video"),
|
61 |
+
title="Crowd Detection using YOLOv8"
|
62 |
+
)
|
63 |
+
|
64 |
+
if __name__ == "__main__":
|
65 |
+
interface.launch()
|