jake2004 commited on
Commit
57e64d1
·
verified ·
1 Parent(s): 42daa38

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -0
app.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ !pip install gradio ultralytics opencv-python
2
+
3
+ import gradio as gr
4
+ from ultralytics import YOLO
5
+ import cv2
6
+ import numpy as np
7
+
8
+ # Load the model (do this outside the function for efficiency)
9
+ try:
10
+ model = YOLO("yolov8n.pt") # Or your model path
11
+ except Exception as e:
12
+ print(f"Error loading model: {e}")
13
+ exit() # Exit if the model fails to load
14
+
15
+ def detect_pedestrians(video):
16
+ try:
17
+ cap = cv2.VideoCapture(video)
18
+ frames = []
19
+ while True:
20
+ ret, frame = cap.read()
21
+ if not ret:
22
+ break
23
+
24
+ results = model(frame)
25
+
26
+ for result in results:
27
+ boxes = result.boxes
28
+ for box in boxes:
29
+ if result.names[int(box.cls)] == 'person':
30
+ x1, y1, x2, y2 = map(int, box.xyxy[0])
31
+ cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
32
+ cv2.putText(frame, 'Person', (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
33
+ frames.append(frame)
34
+ cap.release()
35
+
36
+ if not frames: #if no frame return a blank image
37
+ return np.zeros((480, 640, 3), dtype=np.uint8)
38
+
39
+ # Combine frames into a video (optional - if you want to return a video)
40
+ # For simplicity, we'll return the last frame for now.
41
+ return frames[-1] #return the last frame
42
+ except Exception as e:
43
+ print(f"Error in detection: {e}")
44
+ return f"Error: {e}" # Return the error message as a string
45
+
46
+ iface = gr.Interface(
47
+ fn=detect_pedestrians,
48
+ inputs=gr.Video(source="upload"), # Use gr.Video for video input
49
+ outputs=gr.Image(), # Use gr.Image for image output
50
+ title="Pedestrian Detection",
51
+ description="Upload a video to detect pedestrians.",
52
+ allow_flagging="never", #removes flag button
53
+ )
54
+
55
+ iface.launch()