mkhodary101 commited on
Commit
1a67c1d
·
verified ·
1 Parent(s): 81284aa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -15
app.py CHANGED
@@ -131,23 +131,18 @@ class PeopleTracking:
131
  class FallDetection:
132
  def __init__(self, yolo_model_path="yolov8l.pt"):
133
  self.model_path = yolo_model_path
134
-
135
- @spaces.GPU
136
  def fall_detect(self, video_path):
137
  try:
138
- import torch
139
- import os
140
- import cv2
141
- import numpy as np
142
- from ultralytics import YOLO
143
-
144
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
145
-
 
146
  if not os.path.exists(self.model_path):
147
  model = YOLO("yolov8l.pt")
148
  model.save(self.model_path)
149
  else:
150
  model = YOLO(self.model_path)
 
151
  model.to(device)
152
 
153
  cap = cv2.VideoCapture(video_path)
@@ -159,19 +154,29 @@ class FallDetection:
159
  height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) * 0.5)
160
  output_path = "output_fall.mp4"
161
  out = cv2.VideoWriter(output_path, cv2.VideoWriter_fourcc(*"mp4v"), fps, (width, height))
 
162
  if not out.isOpened():
163
  cap.release()
164
  raise ValueError(f"❌ Failed to initialize video writer")
165
 
 
 
 
166
  while cap.isOpened():
167
  ret, frame = cap.read()
168
  if not ret:
 
169
  break
170
-
 
 
 
 
171
  frame = cv2.resize(frame, (width, height))
172
 
173
- # FIX: Use `.predict()` to ensure proper YOLO inference
174
- results = model.predict(frame, imgsz=640, device=device)
 
175
 
176
  for result in results:
177
  boxes = result.boxes.xyxy.cpu().numpy()
@@ -180,9 +185,9 @@ class FallDetection:
180
  for box, cls in zip(boxes, classes):
181
  if int(cls) == 0:
182
  x1, y1, x2, y2 = map(int, box)
183
- width = x2 - x1
184
- height = y2 - y1
185
- aspect_ratio = width / height if height > 0 else float('inf')
186
 
187
  if aspect_ratio > 0.55:
188
  color = (0, 0, 255)
@@ -196,14 +201,19 @@ class FallDetection:
196
 
197
  out.write(frame)
198
 
 
199
  cap.release()
200
  out.release()
 
201
  if not os.path.exists(output_path):
202
  raise ValueError("❌ Processing failed")
 
203
  return output_path
 
204
  except Exception as e:
205
  raise ValueError(f"Error in fall_detection: {str(e)}")
206
 
 
207
  class FightDetection:
208
  def __init__(self, yolo_model_path="yolov8n-pose.pt"):
209
  self.model_path = yolo_model_path
 
131
  class FallDetection:
132
  def __init__(self, yolo_model_path="yolov8l.pt"):
133
  self.model_path = yolo_model_path
134
+ spaces@GPU
 
135
  def fall_detect(self, video_path):
136
  try:
 
 
 
 
 
 
137
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
138
+
139
+ # Load YOLOv8 model
140
  if not os.path.exists(self.model_path):
141
  model = YOLO("yolov8l.pt")
142
  model.save(self.model_path)
143
  else:
144
  model = YOLO(self.model_path)
145
+
146
  model.to(device)
147
 
148
  cap = cv2.VideoCapture(video_path)
 
154
  height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) * 0.5)
155
  output_path = "output_fall.mp4"
156
  out = cv2.VideoWriter(output_path, cv2.VideoWriter_fourcc(*"mp4v"), fps, (width, height))
157
+
158
  if not out.isOpened():
159
  cap.release()
160
  raise ValueError(f"❌ Failed to initialize video writer")
161
 
162
+ frame_skip = 3 # Process every 3rd frame to optimize performance
163
+ frame_count = 0
164
+
165
  while cap.isOpened():
166
  ret, frame = cap.read()
167
  if not ret:
168
+ print("⚠️ No more frames to read. Exiting loop.")
169
  break
170
+
171
+ frame_count += 1
172
+ if frame_count % frame_skip != 0:
173
+ continue # Skip frames to optimize performance
174
+
175
  frame = cv2.resize(frame, (width, height))
176
 
177
+ # Ensure YOLO runs without unnecessary graph tracking
178
+ with torch.no_grad():
179
+ results = model.predict(frame, imgsz=640, device=device)
180
 
181
  for result in results:
182
  boxes = result.boxes.xyxy.cpu().numpy()
 
185
  for box, cls in zip(boxes, classes):
186
  if int(cls) == 0:
187
  x1, y1, x2, y2 = map(int, box)
188
+ obj_width = x2 - x1
189
+ obj_height = y2 - y1
190
+ aspect_ratio = obj_width / obj_height if obj_height > 0 else float('inf')
191
 
192
  if aspect_ratio > 0.55:
193
  color = (0, 0, 255)
 
201
 
202
  out.write(frame)
203
 
204
+ # ✅ Release resources after processing
205
  cap.release()
206
  out.release()
207
+
208
  if not os.path.exists(output_path):
209
  raise ValueError("❌ Processing failed")
210
+
211
  return output_path
212
+
213
  except Exception as e:
214
  raise ValueError(f"Error in fall_detection: {str(e)}")
215
 
216
+
217
  class FightDetection:
218
  def __init__(self, yolo_model_path="yolov8n-pose.pt"):
219
  self.model_path = yolo_model_path