Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import cv2
|
3 |
+
import numpy as np
|
4 |
+
import tempfile
|
5 |
+
import os
|
6 |
+
|
7 |
+
def detect_and_predict(video):
|
8 |
+
# Save uploaded video
|
9 |
+
temp_video_path = tempfile.NamedTemporaryFile(delete=False, suffix='.mp4').name
|
10 |
+
with open(temp_video_path, "wb") as f:
|
11 |
+
f.write(video.read())
|
12 |
+
|
13 |
+
cap = cv2.VideoCapture(temp_video_path)
|
14 |
+
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
15 |
+
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
16 |
+
|
17 |
+
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
18 |
+
out_path = tempfile.NamedTemporaryFile(delete=False, suffix='.mp4').name
|
19 |
+
out = cv2.VideoWriter(out_path, fourcc, 20.0, (width, height))
|
20 |
+
|
21 |
+
ball_color_lower = np.array([5, 50, 50]) # Orange/red lower
|
22 |
+
ball_color_upper = np.array([15, 255, 255]) # Orange/red upper
|
23 |
+
trajectory_points = []
|
24 |
+
|
25 |
+
while True:
|
26 |
+
ret, frame = cap.read()
|
27 |
+
if not ret:
|
28 |
+
break
|
29 |
+
|
30 |
+
blurred = cv2.GaussianBlur(frame, (11, 11), 0)
|
31 |
+
hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)
|
32 |
+
mask = cv2.inRange(hsv, ball_color_lower, ball_color_upper)
|
33 |
+
mask = cv2.erode(mask, None, iterations=2)
|
34 |
+
mask = cv2.dilate(mask, None, iterations=2)
|
35 |
+
|
36 |
+
contours, _ = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
37 |
+
|
38 |
+
if contours:
|
39 |
+
c = max(contours, key=cv2.contourArea)
|
40 |
+
((x, y), radius) = cv2.minEnclosingCircle(c)
|
41 |
+
|
42 |
+
if radius > 3:
|
43 |
+
trajectory_points.append((int(x), int(y)))
|
44 |
+
cv2.circle(frame, (int(x), int(y)), int(radius), (0, 0, 255), 2)
|
45 |
+
|
46 |
+
# Draw trajectory
|
47 |
+
for i in range(1, len(trajectory_points)):
|
48 |
+
cv2.line(frame, trajectory_points[i - 1], trajectory_points[i], (255, 0, 0), 2)
|
49 |
+
|
50 |
+
# Draw stumps line (for simplicity, fixed zone)
|
51 |
+
cv2.rectangle(frame, (width // 2 - 20, height - 200), (width // 2 + 20, height - 50), (0, 255, 255), 2)
|
52 |
+
|
53 |
+
out.write(frame)
|
54 |
+
|
55 |
+
cap.release()
|
56 |
+
out.release()
|
57 |
+
|
58 |
+
return out_path
|
59 |
+
|
60 |
+
iface = gr.Interface(fn=detect_and_predict,
|
61 |
+
inputs=gr.Video(label="Upload Bowling Video"),
|
62 |
+
outputs=gr.Video(label="Ball Tracking Result"),
|
63 |
+
title="DRS Ball Tracker",
|
64 |
+
description="Detect and visualize ball trajectory for LBW simulation.")
|
65 |
+
|
66 |
+
iface.launch()
|