ameerazam08 commited on
Commit
206505f
·
verified ·
1 Parent(s): 0e87018

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -0
app.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import cv2
3
+ import numpy as np
4
+ import tempfile
5
+ import os
6
+ from ultralytics import YOLO
7
+
8
+ def stream_object_detection(video_path, conf_threshold):
9
+ # Load the YOLO model
10
+ model = YOLO("weights/best.pt")
11
+ cap = cv2.VideoCapture(video_path)
12
+
13
+ # Get video properties
14
+ fps = int(cap.get(cv2.CAP_PROP_FPS))
15
+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH) // 2)
16
+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) // 2)
17
+
18
+ # Temporary file for processed video
19
+ temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4")
20
+ temp_file_path = temp_file.name
21
+
22
+ # VideoWriter to save processed frames
23
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
24
+ out = cv2.VideoWriter(temp_file_path, fourcc, fps, (width, height))
25
+
26
+ while cap.isOpened():
27
+ ret, frame = cap.read()
28
+ if not ret:
29
+ break
30
+ frame = cv2.resize(frame, (width, height))
31
+
32
+ # Run YOLO predictions
33
+ results = model.predict(frame)
34
+
35
+ # Annotate frame with detection results
36
+ annotated_frame = results[0].plot()
37
+
38
+ # Write annotated frame to the video file
39
+ out.write(annotated_frame)
40
+
41
+ cap.release()
42
+ out.release()
43
+
44
+ return temp_file_path
45
+
46
+ with gr.Blocks() as app:
47
+ with gr.Row():
48
+ with gr.Column():
49
+ video_input = gr.Video(label="Upload Video")
50
+ conf_threshold = gr.Slider(
51
+ label="Confidence Threshold",
52
+ minimum=0.0,
53
+ maximum=1.0,
54
+ step=0.05,
55
+ value=0.30,
56
+ )
57
+ with gr.Column():
58
+ video_output = gr.Video(label="Processed Video")
59
+ with gr.Row():
60
+
61
+ with gr.Column():
62
+ detect_button = gr.Button("Start Detection", variant="primary")
63
+ detect_button.click(
64
+ fn=stream_object_detection,
65
+ inputs=[video_input, conf_threshold],
66
+ outputs=video_output,
67
+ )
68
+
69
+ if __name__ == "__main__":
70
+ app.launch()
71
+