mkhodary101 commited on
Commit
7a2e724
·
verified ·
1 Parent(s): cdec70d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -13
app.py CHANGED
@@ -8,14 +8,19 @@ import spaces
8
 
9
  @spaces.GPU
10
 
 
 
 
 
 
11
  class CrowdDetection:
12
- def __init__(self, model_path="yolov8n.pt", crowd_threshold=10):
 
13
  self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
14
- print(f"🔍 Using device: {self.device}")
15
- self.model = YOLO(model_path).to(self.device)
16
- self.crowd_threshold = crowd_threshold
17
 
18
  def detect_crowd(self, video_path):
 
19
  cap = cv2.VideoCapture(video_path)
20
  if not cap.isOpened():
21
  raise ValueError(f"❌ Failed to open video: {video_path}")
@@ -23,38 +28,47 @@ class CrowdDetection:
23
  fps = int(cap.get(cv2.CAP_PROP_FPS))
24
  width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
25
  height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
26
- print(f"🎥 Video details - FPS: {fps}, Width: {width}, Height: {height}")
27
 
28
  output_path = "output_crowd.mp4"
29
  fourcc = cv2.VideoWriter_fourcc(*"mp4v")
30
  out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
31
 
 
32
  frame_count = 0
33
 
34
  while cap.isOpened():
35
  ret, frame = cap.read()
36
  if not ret:
37
- break
38
 
39
  frame_count += 1
 
 
40
  results = self.model(frame)
41
- person_count = 0
42
 
 
 
 
 
 
 
 
43
  for result in results:
44
  boxes = result.boxes.xyxy.cpu().numpy()
45
  classes = result.boxes.cls.cpu().numpy()
46
 
47
  for box, cls in zip(boxes, classes):
48
- if int(cls) == 0: # Class ID 0 = "person"
49
- person_count += 1
50
  x1, y1, x2, y2 = map(int, box)
51
  cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
52
  cv2.putText(frame, "Person", (x1, y1 - 10),
53
  cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
54
 
55
- alert_text = "Crowd Alert!" if person_count > self.crowd_threshold else f"People: {person_count}"
 
56
  cv2.putText(frame, alert_text, (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1,
57
- (0, 0, 255) if person_count > self.crowd_threshold else (0, 255, 0), 2)
 
58
  out.write(frame)
59
 
60
  cap.release()
@@ -66,8 +80,9 @@ class CrowdDetection:
66
  if not os.path.exists(output_path):
67
  raise FileNotFoundError(f"❌ Output video not found: {output_path}")
68
 
69
- print(f"✅ Processed video saved at: {output_path}")
70
- return output_path
 
71
 
72
  class PeopleTracking:
73
  def __init__(self, yolo_model_path="yolov8n.pt"):
 
8
 
9
  @spaces.GPU
10
 
11
+ import cv2
12
+ import torch
13
+ import os
14
+ from ultralytics import YOLO
15
+
16
  class CrowdDetection:
17
+ def __init__(self, model_path="yolov8n.pt"):
18
+ """Initialize the YOLO model once to avoid PicklingError."""
19
  self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
20
+ self.model = YOLO(model_path).to(self.device) # Load model once
 
 
21
 
22
  def detect_crowd(self, video_path):
23
+ """Process video using YOLOv8 for crowd detection."""
24
  cap = cv2.VideoCapture(video_path)
25
  if not cap.isOpened():
26
  raise ValueError(f"❌ Failed to open video: {video_path}")
 
28
  fps = int(cap.get(cv2.CAP_PROP_FPS))
29
  width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
30
  height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
 
31
 
32
  output_path = "output_crowd.mp4"
33
  fourcc = cv2.VideoWriter_fourcc(*"mp4v")
34
  out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
35
 
36
+ CROWD_THRESHOLD = 10
37
  frame_count = 0
38
 
39
  while cap.isOpened():
40
  ret, frame = cap.read()
41
  if not ret:
42
+ break # End of video
43
 
44
  frame_count += 1
45
+
46
+ # Run YOLO inference on the frame
47
  results = self.model(frame)
 
48
 
49
+ # Count detected persons
50
+ person_count = sum(
51
+ 1 for result in results
52
+ for cls in result.boxes.cls.cpu().numpy() if int(cls) == 0
53
+ )
54
+
55
+ # Draw bounding boxes
56
  for result in results:
57
  boxes = result.boxes.xyxy.cpu().numpy()
58
  classes = result.boxes.cls.cpu().numpy()
59
 
60
  for box, cls in zip(boxes, classes):
61
+ if int(cls) == 0: # Person class
 
62
  x1, y1, x2, y2 = map(int, box)
63
  cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
64
  cv2.putText(frame, "Person", (x1, y1 - 10),
65
  cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
66
 
67
+ # Display count on frame
68
+ alert_text = "Crowd Alert!" if person_count > CROWD_THRESHOLD else f"People: {person_count}"
69
  cv2.putText(frame, alert_text, (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1,
70
+ (0, 0, 255) if person_count > CROWD_THRESHOLD else (0, 255, 0), 2)
71
+
72
  out.write(frame)
73
 
74
  cap.release()
 
80
  if not os.path.exists(output_path):
81
  raise FileNotFoundError(f"❌ Output video not found: {output_path}")
82
 
83
+ return output_path # Return file path instead of video object
84
+
85
+
86
 
87
  class PeopleTracking:
88
  def __init__(self, yolo_model_path="yolov8n.pt"):