Update app.py
Browse files
app.py
CHANGED
@@ -6,7 +6,6 @@ import gradio as gr
|
|
6 |
from scipy.interpolate import interp1d
|
7 |
import uuid
|
8 |
import os
|
9 |
-
import time
|
10 |
|
11 |
# Load the trained YOLOv8n model
|
12 |
model = YOLO("best.pt")
|
@@ -15,14 +14,11 @@ model = YOLO("best.pt")
|
|
15 |
STUMPS_WIDTH = 0.2286 # meters
|
16 |
BALL_DIAMETER = 0.073 # meters
|
17 |
FRAME_RATE = 30 # Input video frame rate
|
18 |
-
SLOW_MOTION_FACTOR =
|
19 |
CONF_THRESHOLD = 0.3
|
20 |
-
|
21 |
-
PROCESS_EVERY_N_FRAME = 2 # Process every 2nd frame
|
22 |
-
RESIZE_FACTOR = 0.5 # Downscale frames to 50% for faster processing
|
23 |
|
24 |
def process_video(video_path):
|
25 |
-
start_time = time.time()
|
26 |
if not os.path.exists(video_path):
|
27 |
return [], [], "Error: Video file not found"
|
28 |
cap = cv2.VideoCapture(video_path)
|
@@ -30,123 +26,162 @@ def process_video(video_path):
|
|
30 |
ball_positions = []
|
31 |
debug_log = []
|
32 |
frame_count = 0
|
33 |
-
|
34 |
|
35 |
-
while cap.isOpened():
|
36 |
ret, frame = cap.read()
|
37 |
if not ret:
|
38 |
break
|
39 |
frame_count += 1
|
40 |
-
|
41 |
-
|
42 |
-
processed_frames += 1
|
43 |
-
# Resize frame for faster processing
|
44 |
-
frame_small = cv2.resize(frame, (0, 0), fx=RESIZE_FACTOR, fy=RESIZE_FACTOR)
|
45 |
frames.append(frame.copy()) # Store original frame
|
46 |
# Detect ball
|
47 |
-
results = model.predict(
|
48 |
detections = 0
|
|
|
49 |
for detection in results[0].boxes:
|
50 |
if detection.cls == 0: # Ball class
|
51 |
detections += 1
|
52 |
x1, y1, x2, y2 = detection.xyxy[0].cpu().numpy()
|
53 |
# Scale coordinates back to original frame size
|
54 |
-
x1,
|
55 |
-
|
56 |
-
|
|
|
57 |
cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)
|
58 |
frames[-1] = frame
|
59 |
debug_log.append(f"Frame {frame_count}: {detections} ball detections")
|
60 |
-
if len(ball_positions) >= MAX_DETECTIONS:
|
61 |
-
debug_log.append(f"Stopping early after {len(ball_positions)} detections")
|
62 |
-
break
|
63 |
cap.release()
|
64 |
|
65 |
-
debug_log.append(f"Processed {processed_frames} frames in {time.time() - start_time:.2f} seconds")
|
66 |
if not ball_positions:
|
67 |
debug_log.append("No balls detected in any frame")
|
68 |
else:
|
69 |
debug_log.append(f"Total ball detections: {len(ball_positions)}")
|
|
|
70 |
return frames, ball_positions, "\n".join(debug_log)
|
71 |
|
72 |
def estimate_trajectory(ball_positions, frames):
|
73 |
-
start_time = time.time()
|
74 |
if len(ball_positions) < 2:
|
75 |
-
return
|
76 |
x_coords = [pos[0] for pos in ball_positions]
|
77 |
y_coords = [pos[1] for pos in ball_positions]
|
78 |
times = np.arange(len(ball_positions)) / FRAME_RATE
|
|
|
79 |
try:
|
80 |
fx = interp1d(times, x_coords, kind='linear', fill_value="extrapolate")
|
81 |
fy = interp1d(times, y_coords, kind='quadratic', fill_value="extrapolate")
|
82 |
except Exception as e:
|
83 |
-
return
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
89 |
|
90 |
def lbw_decision(ball_positions, trajectory, frames):
|
91 |
-
start_time = time.time()
|
92 |
if not frames:
|
93 |
return "Error: No frames processed", None, None, None
|
94 |
-
if
|
95 |
return "Not enough data (insufficient ball detections)", None, None, None
|
|
|
96 |
frame_height, frame_width = frames[0].shape[:2]
|
97 |
stumps_x = frame_width / 2
|
98 |
stumps_y = frame_height * 0.9
|
99 |
stumps_width_pixels = frame_width * (STUMPS_WIDTH / 3.0)
|
|
|
100 |
pitch_point = ball_positions[0]
|
101 |
-
impact_point = ball_positions
|
|
|
|
|
102 |
pitch_x, pitch_y = pitch_point
|
103 |
-
if pitch_x < stumps_x - stumps_width_pixels / 2 or pitch_x > stumps_x + stumps_width_pixels / 2:
|
104 |
return f"Not Out (Pitched outside line at x: {pitch_x:.1f}, y: {pitch_y:.1f})", trajectory, pitch_point, impact_point
|
|
|
|
|
105 |
impact_x, impact_y = impact_point
|
106 |
if impact_x < stumps_x - stumps_width_pixels / 2 or impact_x > stumps_x + stumps_width_pixels / 2:
|
107 |
return f"Not Out (Impact outside line at x: {impact_x:.1f}, y: {impact_y:.1f})", trajectory, pitch_point, impact_point
|
|
|
|
|
108 |
for x, y in trajectory:
|
109 |
if abs(x - stumps_x) < stumps_width_pixels / 2 and abs(y - stumps_y) < frame_height * 0.1:
|
110 |
return f"Out (Ball hits stumps, Pitch at x: {pitch_x:.1f}, y: {pitch_y:.1f}, Impact at x: {impact_x:.1f}, y: {impact_y:.1f})", trajectory, pitch_point, impact_point
|
111 |
-
debug_log = f"LBW decision computed in {time.time() - start_time:.2f} seconds"
|
112 |
return f"Not Out (Missing stumps, Pitch at x: {pitch_x:.1f}, y: {pitch_y:.1f}, Impact at x: {impact_x:.1f}, y: {impact_y:.1f})", trajectory, pitch_point, impact_point
|
113 |
|
114 |
-
def generate_slow_motion(frames, trajectory, pitch_point, impact_point, output_path):
|
115 |
-
start_time = time.time()
|
116 |
if not frames:
|
117 |
return None
|
118 |
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
119 |
out = cv2.VideoWriter(output_path, fourcc, FRAME_RATE / SLOW_MOTION_FACTOR, (frames[0].shape[1], frames[0].shape[0]))
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
|
|
|
|
|
|
|
|
125 |
x, y = pitch_point
|
126 |
-
cv2.circle(frame, (int(x), int(y)), 8, (0, 0, 255), -1)
|
127 |
cv2.putText(frame, "Pitch Point", (int(x) + 10, int(y) - 10),
|
128 |
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
|
129 |
-
|
|
|
|
|
130 |
x, y = impact_point
|
131 |
-
cv2.circle(frame, (int(x), int(y)), 8, (0, 255, 255), -1)
|
132 |
cv2.putText(frame, "Impact Point", (int(x) + 10, int(y) + 20),
|
133 |
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2)
|
|
|
134 |
for _ in range(SLOW_MOTION_FACTOR):
|
135 |
out.write(frame)
|
136 |
out.release()
|
137 |
-
|
138 |
-
return output_path, debug_log
|
139 |
|
140 |
def drs_review(video):
|
141 |
-
start_time = time.time()
|
142 |
frames, ball_positions, debug_log = process_video(video)
|
143 |
if not frames:
|
144 |
return f"Error: Failed to process video\nDebug Log:\n{debug_log}", None
|
145 |
trajectory, _, trajectory_log = estimate_trajectory(ball_positions, frames)
|
146 |
decision, trajectory, pitch_point, impact_point = lbw_decision(ball_positions, trajectory, frames)
|
|
|
|
|
147 |
output_path = f"output_{uuid.uuid4()}.mp4"
|
148 |
-
slow_motion_path
|
149 |
-
|
|
|
150 |
return f"DRS Decision: {decision}\nDebug Log:\n{debug_output}", slow_motion_path
|
151 |
|
152 |
# Gradio interface
|
@@ -155,10 +190,9 @@ iface = gr.Interface(
|
|
155 |
inputs=gr.Video(label="Upload Video Clip"),
|
156 |
outputs=[
|
157 |
gr.Textbox(label="DRS Decision and Debug Log"),
|
158 |
-
gr.Video(label="Slow-Motion Replay with Ball Detection (Green), Trajectory (Blue), Pitch Point (Red), Impact Point (Yellow)")
|
159 |
],
|
160 |
title="AI-Powered DRS for LBW in Local Cricket",
|
161 |
-
description="Upload a 3-second video clip of a cricket delivery to get an LBW decision and slow-motion replay showing ball detection (green boxes), trajectory (blue dots), pitch point (red circle), and impact point (yellow circle)."
|
162 |
)
|
163 |
|
164 |
if __name__ == "__main__":
|
|
|
6 |
from scipy.interpolate import interp1d
|
7 |
import uuid
|
8 |
import os
|
|
|
9 |
|
10 |
# Load the trained YOLOv8n model
|
11 |
model = YOLO("best.pt")
|
|
|
14 |
STUMPS_WIDTH = 0.2286 # meters
|
15 |
BALL_DIAMETER = 0.073 # meters
|
16 |
FRAME_RATE = 30 # Input video frame rate
|
17 |
+
SLOW_MOTION_FACTOR = 6
|
18 |
CONF_THRESHOLD = 0.3
|
19 |
+
RESIZE_DIM = 640 # Resize frames for faster processing
|
|
|
|
|
20 |
|
21 |
def process_video(video_path):
|
|
|
22 |
if not os.path.exists(video_path):
|
23 |
return [], [], "Error: Video file not found"
|
24 |
cap = cv2.VideoCapture(video_path)
|
|
|
26 |
ball_positions = []
|
27 |
debug_log = []
|
28 |
frame_count = 0
|
29 |
+
max_frames = FRAME_RATE * 3 # Limit to 3 seconds of frames
|
30 |
|
31 |
+
while cap.isOpened() and frame_count < max_frames:
|
32 |
ret, frame = cap.read()
|
33 |
if not ret:
|
34 |
break
|
35 |
frame_count += 1
|
36 |
+
# Resize frame for faster YOLO inference
|
37 |
+
frame_resized = cv2.resize(frame, (RESIZE_DIM, RESIZE_DIM), interpolation=cv2.INTER_AREA)
|
|
|
|
|
|
|
38 |
frames.append(frame.copy()) # Store original frame
|
39 |
# Detect ball
|
40 |
+
results = model.predict(frame_resized, conf=CONF_THRESHOLD, imgsz=RESIZE_DIM)
|
41 |
detections = 0
|
42 |
+
scale_x, scale_y = frame.shape[1] / RESIZE_DIM, frame.shape[0] / RESIZE_DIM
|
43 |
for detection in results[0].boxes:
|
44 |
if detection.cls == 0: # Ball class
|
45 |
detections += 1
|
46 |
x1, y1, x2, y2 = detection.xyxy[0].cpu().numpy()
|
47 |
# Scale coordinates back to original frame size
|
48 |
+
x1, x2 = x1 * scale_x, x2 * scale_x
|
49 |
+
y1, y2 = y1 * scale_y, y2 * scale_y
|
50 |
+
ball_center = [(x1 + x2) / 2, (y1 + y2) / 2]
|
51 |
+
ball_positions.append(ball_center)
|
52 |
cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)
|
53 |
frames[-1] = frame
|
54 |
debug_log.append(f"Frame {frame_count}: {detections} ball detections")
|
|
|
|
|
|
|
55 |
cap.release()
|
56 |
|
|
|
57 |
if not ball_positions:
|
58 |
debug_log.append("No balls detected in any frame")
|
59 |
else:
|
60 |
debug_log.append(f"Total ball detections: {len(ball_positions)}")
|
61 |
+
|
62 |
return frames, ball_positions, "\n".join(debug_log)
|
63 |
|
64 |
def estimate_trajectory(ball_positions, frames):
|
|
|
65 |
if len(ball_positions) < 2:
|
66 |
+
return [], [], "Error: Fewer than 2 ball detections for trajectory"
|
67 |
x_coords = [pos[0] for pos in ball_positions]
|
68 |
y_coords = [pos[1] for pos in ball_positions]
|
69 |
times = np.arange(len(ball_positions)) / FRAME_RATE
|
70 |
+
|
71 |
try:
|
72 |
fx = interp1d(times, x_coords, kind='linear', fill_value="extrapolate")
|
73 |
fy = interp1d(times, y_coords, kind='quadratic', fill_value="extrapolate")
|
74 |
except Exception as e:
|
75 |
+
return [], [], f"Error in trajectory interpolation: {str(e)}"
|
76 |
+
|
77 |
+
# Interpolate for all frames and future projection
|
78 |
+
t_all = np.linspace(0, times[-1] + 0.5, len(frames) + 10)
|
79 |
+
x_all = fx(t_all)
|
80 |
+
y_all = fy(t_all)
|
81 |
+
trajectory = list(zip(x_all, y_all))
|
82 |
+
return trajectory, t_all, "Trajectory estimated successfully"
|
83 |
+
|
84 |
+
def detect_impact_point(ball_positions, frames):
|
85 |
+
if len(ball_positions) < 3:
|
86 |
+
return ball_positions[-1] if ball_positions else None, len(ball_positions) - 1
|
87 |
+
# Assume batsman is near stumps (bottom center of frame)
|
88 |
+
frame_height, frame_width = frames[0].shape[:2]
|
89 |
+
batsman_x = frame_width / 2
|
90 |
+
batsman_y = frame_height * 0.8 # Approximate batsman position
|
91 |
+
min_dist = float('inf')
|
92 |
+
impact_idx = len(ball_positions) - 1
|
93 |
+
impact_point = ball_positions[-1]
|
94 |
+
|
95 |
+
# Look for sudden change in trajectory or proximity to batsman
|
96 |
+
for i in range(1, len(ball_positions) - 1):
|
97 |
+
x, y = ball_positions[i]
|
98 |
+
prev_x, prev_y = ball_positions[i-1]
|
99 |
+
next_x, next_y = ball_positions[i+1]
|
100 |
+
# Check direction change (simplified)
|
101 |
+
dx1, dy1 = x - prev_x, y - prev_y
|
102 |
+
dx2, dy2 = next_x - x, next_y - y
|
103 |
+
angle_change = abs(np.arctan2(dy2, dx2) - np.arctan2(dy1, dx1))
|
104 |
+
dist_to_batsman = np.sqrt((x - batsman_x)**2 + (y - batsman_y)**2)
|
105 |
+
if angle_change > np.pi/4 or dist_to_batsman < frame_width * 0.1:
|
106 |
+
impact_idx = i
|
107 |
+
impact_point = ball_positions[i]
|
108 |
+
break
|
109 |
+
|
110 |
+
return impact_point, impact_idx
|
111 |
|
112 |
def lbw_decision(ball_positions, trajectory, frames):
|
|
|
113 |
if not frames:
|
114 |
return "Error: No frames processed", None, None, None
|
115 |
+
if len(ball_positions) < 2:
|
116 |
return "Not enough data (insufficient ball detections)", None, None, None
|
117 |
+
|
118 |
frame_height, frame_width = frames[0].shape[:2]
|
119 |
stumps_x = frame_width / 2
|
120 |
stumps_y = frame_height * 0.9
|
121 |
stumps_width_pixels = frame_width * (STUMPS_WIDTH / 3.0)
|
122 |
+
|
123 |
pitch_point = ball_positions[0]
|
124 |
+
impact_point, impact_idx = detect_impact_point(ball_positions, frames)
|
125 |
+
|
126 |
+
# Check pitching point
|
127 |
pitch_x, pitch_y = pitch_point
|
128 |
+
if pitch_x < stumps_x - stumps_width_pixels / 2 or pitch_x > stumps_x Moderation: x > stumps_x + stumps_width_pixels / 2:
|
129 |
return f"Not Out (Pitched outside line at x: {pitch_x:.1f}, y: {pitch_y:.1f})", trajectory, pitch_point, impact_point
|
130 |
+
|
131 |
+
# Check impact point
|
132 |
impact_x, impact_y = impact_point
|
133 |
if impact_x < stumps_x - stumps_width_pixels / 2 or impact_x > stumps_x + stumps_width_pixels / 2:
|
134 |
return f"Not Out (Impact outside line at x: {impact_x:.1f}, y: {impact_y:.1f})", trajectory, pitch_point, impact_point
|
135 |
+
|
136 |
+
# Check trajectory hitting stumps
|
137 |
for x, y in trajectory:
|
138 |
if abs(x - stumps_x) < stumps_width_pixels / 2 and abs(y - stumps_y) < frame_height * 0.1:
|
139 |
return f"Out (Ball hits stumps, Pitch at x: {pitch_x:.1f}, y: {pitch_y:.1f}, Impact at x: {impact_x:.1f}, y: {impact_y:.1f})", trajectory, pitch_point, impact_point
|
|
|
140 |
return f"Not Out (Missing stumps, Pitch at x: {pitch_x:.1f}, y: {pitch_y:.1f}, Impact at x: {impact_x:.1f}, y: {impact_y:.1f})", trajectory, pitch_point, impact_point
|
141 |
|
142 |
+
def generate_slow_motion(frames, trajectory, pitch_point, impact_point, impact_idx, output_path):
|
|
|
143 |
if not frames:
|
144 |
return None
|
145 |
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
146 |
out = cv2.VideoWriter(output_path, fourcc, FRAME_RATE / SLOW_MOTION_FACTOR, (frames[0].shape[1], frames[0].shape[0]))
|
147 |
+
|
148 |
+
for i, frame in enumerate(frames):
|
149 |
+
# Draw trajectory up to current frame
|
150 |
+
traj_points = [p for j, p in enumerate(trajectory) if j / SLOW_MOTION_FACTOR <= i]
|
151 |
+
for x, y in traj_points:
|
152 |
+
cv2.circle(frame, (int(x), int(y)), 5, (255, 0, 0), -1) # Blue dots
|
153 |
+
|
154 |
+
# Draw pitch point in early frames
|
155 |
+
if pitch_point and i < len(frames) // 2:
|
156 |
x, y = pitch_point
|
157 |
+
cv2.circle(frame, (int(x), int(y)), 8, (0, 0, 255), -1) # Red circle
|
158 |
cv2.putText(frame, "Pitch Point", (int(x) + 10, int(y) - 10),
|
159 |
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
|
160 |
+
|
161 |
+
# Draw impact point around impact frame
|
162 |
+
if impact_point and abs(i - impact_idx) < 5:
|
163 |
x, y = impact_point
|
164 |
+
cv2.circle(frame, (int(x), int(y)), 8, (0, 255, 255), -1) # Yellow circle
|
165 |
cv2.putText(frame, "Impact Point", (int(x) + 10, int(y) + 20),
|
166 |
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2)
|
167 |
+
|
168 |
for _ in range(SLOW_MOTION_FACTOR):
|
169 |
out.write(frame)
|
170 |
out.release()
|
171 |
+
return output_path
|
|
|
172 |
|
173 |
def drs_review(video):
|
|
|
174 |
frames, ball_positions, debug_log = process_video(video)
|
175 |
if not frames:
|
176 |
return f"Error: Failed to process video\nDebug Log:\n{debug_log}", None
|
177 |
trajectory, _, trajectory_log = estimate_trajectory(ball_positions, frames)
|
178 |
decision, trajectory, pitch_point, impact_point = lbw_decision(ball_positions, trajectory, frames)
|
179 |
+
_, impact_idx = detect_impact_point(ball_positions, frames)
|
180 |
+
|
181 |
output_path = f"output_{uuid.uuid4()}.mp4"
|
182 |
+
slow_motion_path = generate_slow_motion(frames, trajectory, pitch_point, impact_point, impact_idx, output_path)
|
183 |
+
|
184 |
+
debug_output = f"{debug_log}\n{trajectory_log}"
|
185 |
return f"DRS Decision: {decision}\nDebug Log:\n{debug_output}", slow_motion_path
|
186 |
|
187 |
# Gradio interface
|
|
|
190 |
inputs=gr.Video(label="Upload Video Clip"),
|
191 |
outputs=[
|
192 |
gr.Textbox(label="DRS Decision and Debug Log"),
|
193 |
+
gr.Video(label="Very Slow-Motion Replay with Ball Detection (Green), Trajectory (Blue), Pitch Point (Red), Impact Point (Yellow)")
|
194 |
],
|
195 |
title="AI-Powered DRS for LBW in Local Cricket",
|
|
|
196 |
)
|
197 |
|
198 |
if __name__ == "__main__":
|