Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -13,10 +13,13 @@ model = YOLO("best.pt")
|
|
13 |
# Constants for LBW decision and video processing
|
14 |
STUMPS_WIDTH = 0.2286 # meters (width of stumps)
|
15 |
BALL_DIAMETER = 0.073 # meters (approx. cricket ball diameter)
|
16 |
-
FRAME_RATE = 20 # Input video frame rate
|
17 |
-
SLOW_MOTION_FACTOR = 3 # Adjusted for 20 FPS
|
18 |
CONF_THRESHOLD = 0.25 # Confidence threshold for detection
|
19 |
-
IMPACT_ZONE_Y = 0.85 # Fraction of frame height
|
|
|
|
|
|
|
20 |
|
21 |
def process_video(video_path):
|
22 |
if not os.path.exists(video_path):
|
@@ -37,11 +40,11 @@ def process_video(video_path):
|
|
37 |
results = model.predict(frame, conf=CONF_THRESHOLD)
|
38 |
detections = 0
|
39 |
for detection in results[0].boxes:
|
40 |
-
if detection.cls == 0: #
|
41 |
detections += 1
|
42 |
x1, y1, x2, y2 = detection.xyxy[0].cpu().numpy()
|
43 |
ball_positions.append([(x1 + x2) / 2, (y1 + y2) / 2])
|
44 |
-
detection_frames.append(frame_count - 1) #
|
45 |
cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)
|
46 |
frames[-1] = frame
|
47 |
debug_log.append(f"Frame {frame_count}: {detections} ball detections")
|
@@ -54,36 +57,38 @@ def process_video(video_path):
|
|
54 |
|
55 |
return frames, ball_positions, detection_frames, "\n".join(debug_log)
|
56 |
|
57 |
-
def estimate_trajectory(ball_positions, frames):
|
58 |
if len(ball_positions) < 2:
|
59 |
-
return None, None, None, "Error: Fewer than 2 ball detections for trajectory"
|
60 |
-
|
61 |
frame_height = frames[0].shape[0]
|
62 |
-
|
63 |
# Extract x, y coordinates
|
64 |
x_coords = [pos[0] for pos in ball_positions]
|
65 |
y_coords = [pos[1] for pos in ball_positions]
|
66 |
-
times = np.
|
67 |
|
68 |
-
#
|
69 |
-
|
70 |
for i, y in enumerate(y_coords):
|
71 |
-
if y > frame_height *
|
72 |
-
|
73 |
break
|
74 |
-
|
75 |
-
|
|
|
|
|
76 |
impact_idx = None
|
77 |
-
for i
|
78 |
-
if
|
|
|
79 |
impact_idx = i
|
80 |
break
|
81 |
if impact_idx is None:
|
82 |
-
impact_idx = len(ball_positions) - 1
|
83 |
-
|
84 |
impact_point = ball_positions[impact_idx]
|
|
|
85 |
|
86 |
-
# Use
|
87 |
x_coords = x_coords[:impact_idx + 1]
|
88 |
y_coords = y_coords[:impact_idx + 1]
|
89 |
times = times[:impact_idx + 1]
|
@@ -92,111 +97,124 @@ def estimate_trajectory(ball_positions, frames):
|
|
92 |
fx = interp1d(times, x_coords, kind='linear', fill_value="extrapolate")
|
93 |
fy = interp1d(times, y_coords, kind='quadratic', fill_value="extrapolate")
|
94 |
except Exception as e:
|
95 |
-
return None, None, None, f"Error in trajectory interpolation: {str(e)}"
|
96 |
|
97 |
-
#
|
|
|
|
|
|
|
98 |
t_full = np.linspace(times[0], times[-1] + 0.5, len(times) + 10)
|
99 |
x_full = fx(t_full)
|
100 |
y_full = fy(t_full)
|
101 |
-
|
102 |
|
103 |
-
|
|
|
|
|
|
|
104 |
|
105 |
-
def lbw_decision(ball_positions,
|
106 |
if not frames:
|
107 |
return "Error: No frames processed", None, None, None
|
108 |
-
if not
|
109 |
return "Not enough data (insufficient ball detections)", None, None, None
|
110 |
|
111 |
frame_height, frame_width = frames[0].shape[:2]
|
112 |
stumps_x = frame_width / 2
|
113 |
-
stumps_y = frame_height * 0.9
|
114 |
stumps_width_pixels = frame_width * (STUMPS_WIDTH / 3.0)
|
115 |
|
116 |
pitch_x, pitch_y = pitch_point
|
117 |
impact_x, impact_y = impact_point
|
118 |
|
119 |
-
# Check pitching point
|
120 |
if pitch_x < stumps_x - stumps_width_pixels / 2 or pitch_x > stumps_x + stumps_width_pixels / 2:
|
121 |
-
return f"Not Out (Pitched outside line at x: {pitch_x:.1f}, y: {pitch_y:.1f})",
|
122 |
|
123 |
-
# Check impact point
|
124 |
if impact_x < stumps_x - stumps_width_pixels / 2 or impact_x > stumps_x + stumps_width_pixels / 2:
|
125 |
-
return f"Not Out (Impact outside line at x: {impact_x:.1f}, y: {impact_y:.1f})",
|
126 |
|
127 |
# Check trajectory hitting stumps
|
128 |
-
for x, y in
|
129 |
if abs(x - stumps_x) < stumps_width_pixels / 2 and abs(y - stumps_y) < frame_height * 0.1:
|
130 |
-
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})",
|
131 |
-
|
132 |
-
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
|
133 |
|
134 |
-
def generate_slow_motion(frames,
|
135 |
if not frames:
|
136 |
return None
|
137 |
-
|
138 |
-
|
|
|
|
|
|
|
139 |
|
140 |
-
|
|
|
141 |
|
142 |
-
|
143 |
-
|
144 |
|
145 |
for i, frame in enumerate(frames):
|
146 |
-
# Draw
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
147 |
if i in detection_frames and trajectory_points.size > 0:
|
148 |
-
|
|
|
|
|
149 |
|
150 |
-
# Draw pitch point (red circle
|
151 |
-
if pitch_point and
|
152 |
x, y = pitch_point
|
153 |
-
if y > frame.shape[0] * 0.75: # Adjust this threshold for the ground position
|
154 |
-
pitch_point_detected = True
|
155 |
-
if pitch_point_detected:
|
156 |
cv2.circle(frame, (int(x), int(y)), 8, (0, 0, 255), -1)
|
157 |
cv2.putText(frame, "Pitch Point", (int(x) + 10, int(y) - 10),
|
158 |
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
|
159 |
|
160 |
-
# Draw impact point (yellow circle
|
161 |
-
if impact_point and
|
162 |
x, y = impact_point
|
163 |
-
if y > frame.shape[0] * 0.85: # Adjust this threshold for impact point
|
164 |
-
impact_point_detected = True
|
165 |
-
if impact_point_detected:
|
166 |
cv2.circle(frame, (int(x), int(y)), 8, (0, 255, 255), -1)
|
167 |
cv2.putText(frame, "Impact Point", (int(x) + 10, int(y) + 20),
|
168 |
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2)
|
169 |
|
170 |
-
# Write frames to output video
|
171 |
for _ in range(SLOW_MOTION_FACTOR):
|
172 |
out.write(frame)
|
173 |
-
|
174 |
out.release()
|
175 |
return output_path
|
176 |
|
177 |
def drs_review(video):
|
178 |
frames, ball_positions, detection_frames, debug_log = process_video(video)
|
179 |
if not frames:
|
180 |
-
return f"Error: Failed to process video", None
|
181 |
-
|
182 |
-
decision,
|
183 |
|
184 |
output_path = f"output_{uuid.uuid4()}.mp4"
|
185 |
-
slow_motion_path = generate_slow_motion(frames,
|
186 |
|
187 |
-
|
|
|
188 |
|
189 |
# Gradio interface
|
190 |
iface = gr.Interface(
|
191 |
fn=drs_review,
|
192 |
inputs=gr.Video(label="Upload Video Clip"),
|
193 |
outputs=[
|
194 |
-
gr.Textbox(label="DRS Decision"),
|
195 |
-
gr.Video(label="Slow-Motion Replay with Ball Detection (Green), Trajectory (Blue Line), Pitch Point (Red), Impact Point (Yellow)")
|
196 |
],
|
197 |
title="AI-Powered DRS for LBW in Local Cricket",
|
198 |
description="Upload a video clip of a cricket delivery to get an LBW decision and slow-motion replay showing ball detection (green boxes), trajectory (blue line), pitch point (red circle), and impact point (yellow circle)."
|
199 |
)
|
200 |
|
201 |
if __name__ == "__main__":
|
202 |
-
iface.launch()
|
|
|
13 |
# Constants for LBW decision and video processing
|
14 |
STUMPS_WIDTH = 0.2286 # meters (width of stumps)
|
15 |
BALL_DIAMETER = 0.073 # meters (approx. cricket ball diameter)
|
16 |
+
FRAME_RATE = 20 # Input video frame rate
|
17 |
+
SLOW_MOTION_FACTOR = 3 # Adjusted for 20 FPS
|
18 |
CONF_THRESHOLD = 0.25 # Confidence threshold for detection
|
19 |
+
IMPACT_ZONE_Y = 0.85 # Fraction of frame height for impact zone
|
20 |
+
PITCH_ZONE_Y = 0.75 # Fraction of frame height for pitch zone
|
21 |
+
IMPACT_DELTA_Y = 50 # Pixels for detecting sudden y-position change
|
22 |
+
STUMPS_HEIGHT = 0.711 # meters (height of stumps)
|
23 |
|
24 |
def process_video(video_path):
|
25 |
if not os.path.exists(video_path):
|
|
|
40 |
results = model.predict(frame, conf=CONF_THRESHOLD)
|
41 |
detections = 0
|
42 |
for detection in results[0].boxes:
|
43 |
+
if detection.cls == 0: # Class 0 is the ball
|
44 |
detections += 1
|
45 |
x1, y1, x2, y2 = detection.xyxy[0].cpu().numpy()
|
46 |
ball_positions.append([(x1 + x2) / 2, (y1 + y2) / 2])
|
47 |
+
detection_frames.append(frame_count - 1) # 0-based index
|
48 |
cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)
|
49 |
frames[-1] = frame
|
50 |
debug_log.append(f"Frame {frame_count}: {detections} ball detections")
|
|
|
57 |
|
58 |
return frames, ball_positions, detection_frames, "\n".join(debug_log)
|
59 |
|
60 |
+
def estimate_trajectory(ball_positions, detection_frames, frames):
|
61 |
if len(ball_positions) < 2:
|
62 |
+
return None, None, None, None, None, "Error: Fewer than 2 ball detections for trajectory"
|
|
|
63 |
frame_height = frames[0].shape[0]
|
64 |
+
|
65 |
# Extract x, y coordinates
|
66 |
x_coords = [pos[0] for pos in ball_positions]
|
67 |
y_coords = [pos[1] for pos in ball_positions]
|
68 |
+
times = np.array(detection_frames) / FRAME_RATE
|
69 |
|
70 |
+
# Pitch point: first detection or when y exceeds PITCH_ZONE_Y
|
71 |
+
pitch_idx = 0
|
72 |
for i, y in enumerate(y_coords):
|
73 |
+
if y > frame_height * PITCH_ZONE_Y:
|
74 |
+
pitch_idx = i
|
75 |
break
|
76 |
+
pitch_point = ball_positions[pitch_idx]
|
77 |
+
pitch_frame = detection_frames[pitch_idx]
|
78 |
+
|
79 |
+
# Impact point: sudden y-change or y exceeds IMPACT_ZONE_Y
|
80 |
impact_idx = None
|
81 |
+
for i in range(1, len(y_coords)):
|
82 |
+
if (y_coords[i] > frame_height * IMPACT_ZONE_Y or
|
83 |
+
abs(y_coords[i] - y_coords[i-1]) > IMPACT_DELTA_Y):
|
84 |
impact_idx = i
|
85 |
break
|
86 |
if impact_idx is None:
|
87 |
+
impact_idx = len(ball_positions) - 1
|
|
|
88 |
impact_point = ball_positions[impact_idx]
|
89 |
+
impact_frame = detection_frames[impact_idx]
|
90 |
|
91 |
+
# Use only detected positions for trajectory
|
92 |
x_coords = x_coords[:impact_idx + 1]
|
93 |
y_coords = y_coords[:impact_idx + 1]
|
94 |
times = times[:impact_idx + 1]
|
|
|
97 |
fx = interp1d(times, x_coords, kind='linear', fill_value="extrapolate")
|
98 |
fy = interp1d(times, y_coords, kind='quadratic', fill_value="extrapolate")
|
99 |
except Exception as e:
|
100 |
+
return None, None, None, None, None, f"Error in trajectory interpolation: {str(e)}"
|
101 |
|
102 |
+
# Trajectory for visualization (detected frames only)
|
103 |
+
vis_trajectory = list(zip(x_coords, y_coords))
|
104 |
+
|
105 |
+
# Full trajectory for LBW (includes projection)
|
106 |
t_full = np.linspace(times[0], times[-1] + 0.5, len(times) + 10)
|
107 |
x_full = fx(t_full)
|
108 |
y_full = fy(t_full)
|
109 |
+
full_trajectory = list(zip(x_full, y_full))
|
110 |
|
111 |
+
debug_log = (f"Trajectory estimated successfully\n"
|
112 |
+
f"Pitch point at frame {pitch_frame + 1}: ({pitch_point[0]:.1f}, {pitch_point[1]:.1f})\n"
|
113 |
+
f"Impact point at frame {impact_frame + 1}: ({impact_point[0]:.1f}, {impact_point[1]:.1f})")
|
114 |
+
return full_trajectory, vis_trajectory, pitch_point, pitch_frame, impact_point, impact_frame, debug_log
|
115 |
|
116 |
+
def lbw_decision(ball_positions, full_trajectory, frames, pitch_point, impact_point):
|
117 |
if not frames:
|
118 |
return "Error: No frames processed", None, None, None
|
119 |
+
if not full_trajectory or len(ball_positions) < 2:
|
120 |
return "Not enough data (insufficient ball detections)", None, None, None
|
121 |
|
122 |
frame_height, frame_width = frames[0].shape[:2]
|
123 |
stumps_x = frame_width / 2
|
124 |
+
stumps_y = frame_height * 0.9
|
125 |
stumps_width_pixels = frame_width * (STUMPS_WIDTH / 3.0)
|
126 |
|
127 |
pitch_x, pitch_y = pitch_point
|
128 |
impact_x, impact_y = impact_point
|
129 |
|
130 |
+
# Check pitching point
|
131 |
if pitch_x < stumps_x - stumps_width_pixels / 2 or pitch_x > stumps_x + stumps_width_pixels / 2:
|
132 |
+
return f"Not Out (Pitched outside line at x: {pitch_x:.1f}, y: {pitch_y:.1f})", full_trajectory, pitch_point, impact_point
|
133 |
|
134 |
+
# Check impact point
|
135 |
if impact_x < stumps_x - stumps_width_pixels / 2 or impact_x > stumps_x + stumps_width_pixels / 2:
|
136 |
+
return f"Not Out (Impact outside line at x: {impact_x:.1f}, y: {impact_y:.1f})", full_trajectory, pitch_point, impact_point
|
137 |
|
138 |
# Check trajectory hitting stumps
|
139 |
+
for x, y in full_trajectory:
|
140 |
if abs(x - stumps_x) < stumps_width_pixels / 2 and abs(y - stumps_y) < frame_height * 0.1:
|
141 |
+
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})", full_trajectory, pitch_point, impact_point
|
142 |
+
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})", full_trajectory, pitch_point, impact_point
|
|
|
143 |
|
144 |
+
def generate_slow_motion(frames, vis_trajectory, pitch_point, pitch_frame, impact_point, impact_frame, detection_frames, output_path):
|
145 |
if not frames:
|
146 |
return None
|
147 |
+
frame_height, frame_width = frames[0].shape[:2]
|
148 |
+
stumps_x = frame_width / 2
|
149 |
+
stumps_y = frame_height * 0.9
|
150 |
+
stumps_width_pixels = frame_width * (STUMPS_WIDTH / 3.0)
|
151 |
+
stumps_height_pixels = frame_height * (STUMPS_HEIGHT / 3.0)
|
152 |
|
153 |
+
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
154 |
+
out = cv2.VideoWriter(output_path, fourcc, FRAME_RATE / SLOW_MOTION_FACTOR, (frame_width, frame_height))
|
155 |
|
156 |
+
# Prepare trajectory points for visualization
|
157 |
+
trajectory_points = np.array(vis_trajectory, dtype=np.int32).reshape((-1, 1, 2))
|
158 |
|
159 |
for i, frame in enumerate(frames):
|
160 |
+
# Draw stumps (three white vertical lines)
|
161 |
+
stump_positions = [
|
162 |
+
(stumps_x - stumps_width_pixels / 2, stumps_y), # Left stump
|
163 |
+
(stumps_x, stumps_y), # Middle stump
|
164 |
+
(stumps_x + stumps_width_pixels / 2, stumps_y) # Right stump
|
165 |
+
]
|
166 |
+
for x, y in stump_positions:
|
167 |
+
cv2.line(frame, (int(x), int(y)), (int(x), int(y - stumps_height_pixels)), (255, 255, 255), 2)
|
168 |
+
|
169 |
+
# Draw trajectory (blue line) only for detected frames
|
170 |
if i in detection_frames and trajectory_points.size > 0:
|
171 |
+
idx = detection_frames.index(i) + 1
|
172 |
+
if idx <= len(trajectory_points):
|
173 |
+
cv2.polylines(frame, [trajectory_points[:idx]], False, (255, 0, 0), 2)
|
174 |
|
175 |
+
# Draw pitch point (red circle) only in pitch frame
|
176 |
+
if pitch_point and i == pitch_frame:
|
177 |
x, y = pitch_point
|
|
|
|
|
|
|
178 |
cv2.circle(frame, (int(x), int(y)), 8, (0, 0, 255), -1)
|
179 |
cv2.putText(frame, "Pitch Point", (int(x) + 10, int(y) - 10),
|
180 |
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
|
181 |
|
182 |
+
# Draw impact point (yellow circle) only in impact frame
|
183 |
+
if impact_point and i == impact_frame:
|
184 |
x, y = impact_point
|
|
|
|
|
|
|
185 |
cv2.circle(frame, (int(x), int(y)), 8, (0, 255, 255), -1)
|
186 |
cv2.putText(frame, "Impact Point", (int(x) + 10, int(y) + 20),
|
187 |
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2)
|
188 |
|
|
|
189 |
for _ in range(SLOW_MOTION_FACTOR):
|
190 |
out.write(frame)
|
|
|
191 |
out.release()
|
192 |
return output_path
|
193 |
|
194 |
def drs_review(video):
|
195 |
frames, ball_positions, detection_frames, debug_log = process_video(video)
|
196 |
if not frames:
|
197 |
+
return f"Error: Failed to process video\nDebug Log:\n{debug_log}", None
|
198 |
+
full_trajectory, vis_trajectory, pitch_point, pitch_frame, impact_point, impact_frame, trajectory_log = estimate_trajectory(ball_positions, detection_frames, frames)
|
199 |
+
decision, full_trajectory, pitch_point, impact_point = lbw_decision(ball_positions, full_trajectory, frames, pitch_point, impact_point)
|
200 |
|
201 |
output_path = f"output_{uuid.uuid4()}.mp4"
|
202 |
+
slow_motion_path = generate_slow_motion(frames, vis_trajectory, pitch_point, pitch_frame, impact_point, impact_frame, detection_frames, output_path)
|
203 |
|
204 |
+
debug_output = f"{debug_log}\n{trajectory_log}"
|
205 |
+
return f"DRS Decision: {decision}\nDebug Log:\n{debug_output}", slow_motion_path
|
206 |
|
207 |
# Gradio interface
|
208 |
iface = gr.Interface(
|
209 |
fn=drs_review,
|
210 |
inputs=gr.Video(label="Upload Video Clip"),
|
211 |
outputs=[
|
212 |
+
gr.Textbox(label="DRS Decision and Debug Log"),
|
213 |
+
gr.Video(label="Very Slow-Motion Replay with Ball Detection (Green), Trajectory (Blue Line), Pitch Point (Red), Impact Point (Yellow)")
|
214 |
],
|
215 |
title="AI-Powered DRS for LBW in Local Cricket",
|
216 |
description="Upload a video clip of a cricket delivery to get an LBW decision and slow-motion replay showing ball detection (green boxes), trajectory (blue line), pitch point (red circle), and impact point (yellow circle)."
|
217 |
)
|
218 |
|
219 |
if __name__ == "__main__":
|
220 |
+
iface.launch()
|