AjaykumarPilla commited on
Commit
0fb91cc
·
verified ·
1 Parent(s): e60a036

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -17
app.py CHANGED
@@ -14,36 +14,50 @@ model = YOLO("best.pt") # Assumes best.pt is in the same directory as app.py
14
  STUMPS_WIDTH = 0.2286 # meters (width of stumps)
15
  BALL_DIAMETER = 0.073 # meters (approx. cricket ball diameter)
16
  FRAME_RATE = 30 # Input video frame rate
17
- SLOW_MOTION_FACTOR = 4 # For very slow motion (4x slower)
 
18
 
19
  def process_video(video_path):
20
  # Initialize video capture
 
 
21
  cap = cv2.VideoCapture(video_path)
22
  frames = []
23
  ball_positions = []
 
24
 
 
25
  while cap.isOpened():
26
  ret, frame = cap.read()
27
  if not ret:
28
  break
 
29
  frames.append(frame.copy()) # Store original frame
30
  # Detect ball using the trained YOLOv8n model
31
- results = model.predict(frame, conf=0.5) # Adjust confidence threshold if needed
 
32
  for detection in results[0].boxes:
33
  if detection.cls == 0: # Assuming class 0 is the ball
 
34
  x1, y1, x2, y2 = detection.xyxy[0].cpu().numpy()
35
  ball_positions.append([(x1 + x2) / 2, (y1 + y2) / 2])
36
  # Draw bounding box on frame for visualization
37
  cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)
38
  frames[-1] = frame # Update frame with bounding box
 
39
  cap.release()
40
 
41
- return frames, ball_positions
 
 
 
 
 
42
 
43
  def estimate_trajectory(ball_positions, frames):
44
  # Simplified physics-based trajectory projection
45
  if len(ball_positions) < 2:
46
- return None, None
47
  # Extract x, y coordinates
48
  x_coords = [pos[0] for pos in ball_positions]
49
  y_coords = [pos[1] for pos in ball_positions]
@@ -53,20 +67,22 @@ def estimate_trajectory(ball_positions, frames):
53
  try:
54
  fx = interp1d(times, x_coords, kind='linear', fill_value="extrapolate")
55
  fy = interp1d(times, y_coords, kind='quadratic', fill_value="extrapolate")
56
- except:
57
- return None, None
58
 
59
  # Project trajectory forward (0.5 seconds post-impact)
60
  t_future = np.linspace(times[-1], times[-1] + 0.5, 10)
61
  x_future = fx(t_future)
62
  y_future = fy(t_future)
63
 
64
- return list(zip(x_future, y_future)), t_future
65
 
66
  def lbw_decision(ball_positions, trajectory, frames):
67
  # Simplified LBW logic
 
 
68
  if not trajectory or len(ball_positions) < 2:
69
- return "Not enough data", None
70
 
71
  # Assume stumps are at the bottom center of the frame (calibration needed)
72
  frame_height, frame_width = frames[0].shape[:2]
@@ -92,6 +108,8 @@ def lbw_decision(ball_positions, trajectory, frames):
92
 
93
  def generate_slow_motion(frames, trajectory, output_path):
94
  # Generate very slow-motion video with ball detection and trajectory overlay
 
 
95
  fourcc = cv2.VideoWriter_fourcc(*'mp4v')
96
  out = cv2.VideoWriter(output_path, fourcc, FRAME_RATE / SLOW_MOTION_FACTOR, (frames[0].shape[1], frames[0].shape[0]))
97
 
@@ -106,28 +124,30 @@ def generate_slow_motion(frames, trajectory, output_path):
106
 
107
  def drs_review(video):
108
  # Process video and generate DRS output
109
- if not os.path.exists(video):
110
- return "Error: Video file not found", None
111
- frames, ball_positions = process_video(video)
112
- trajectory, _ = estimate_trajectory(ball_positions, frames)
113
  decision, trajectory = lbw_decision(ball_positions, trajectory, frames)
114
 
115
- # Generate slow-motion replay
116
  output_path = f"output_{uuid.uuid4()}.mp4"
117
  slow_motion_path = generate_slow_motion(frames, trajectory, output_path)
118
 
119
- return decision, slow_motion_path
 
 
120
 
121
  # Gradio interface
122
  iface = gr.Interface(
123
  fn=drs_review,
124
  inputs=gr.Video(label="Upload Video Clip"),
125
  outputs=[
126
- gr.Textbox(label="DRS Decision"),
127
- gr.Video(label="Slow-Motion Replay with Ball Detection and Trajectory")
128
  ],
129
  title="AI-Powered DRS for LBW in Local Cricket",
130
- description="Upload a video clip of a cricket delivery to get an LBW decision and very slow-motion replay showing ball detection and trajectory."
131
  )
132
 
133
  if __name__ == "__main__":
 
14
  STUMPS_WIDTH = 0.2286 # meters (width of stumps)
15
  BALL_DIAMETER = 0.073 # meters (approx. cricket ball diameter)
16
  FRAME_RATE = 30 # Input video frame rate
17
+ SLOW_MOTION_FACTOR = 6 # For very slow motion (6x slower)
18
+ CONF_THRESHOLD = 0.3 # Lowered confidence threshold for better detection
19
 
20
  def process_video(video_path):
21
  # Initialize video capture
22
+ if not os.path.exists(video_path):
23
+ return [], [], "Error: Video file not found"
24
  cap = cv2.VideoCapture(video_path)
25
  frames = []
26
  ball_positions = []
27
+ debug_log = []
28
 
29
+ frame_count = 0
30
  while cap.isOpened():
31
  ret, frame = cap.read()
32
  if not ret:
33
  break
34
+ frame_count += 1
35
  frames.append(frame.copy()) # Store original frame
36
  # Detect ball using the trained YOLOv8n model
37
+ results = model.predict(frame, conf=CONF_THRESHOLD)
38
+ detections = 0
39
  for detection in results[0].boxes:
40
  if detection.cls == 0: # Assuming class 0 is the ball
41
+ detections += 1
42
  x1, y1, x2, y2 = detection.xyxy[0].cpu().numpy()
43
  ball_positions.append([(x1 + x2) / 2, (y1 + y2) / 2])
44
  # Draw bounding box on frame for visualization
45
  cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)
46
  frames[-1] = frame # Update frame with bounding box
47
+ debug_log.append(f"Frame {frame_count}: {detections} ball detections")
48
  cap.release()
49
 
50
+ if not ball_positions:
51
+ debug_log.append("No balls detected in any frame")
52
+ else:
53
+ debug_log.append(f"Total ball detections: {len(ball_positions)}")
54
+
55
+ return frames, ball_positions, "\n".join(debug_log)
56
 
57
  def estimate_trajectory(ball_positions, frames):
58
  # Simplified physics-based trajectory projection
59
  if len(ball_positions) < 2:
60
+ return None, None, "Error: Fewer than 2 ball detections for trajectory"
61
  # Extract x, y coordinates
62
  x_coords = [pos[0] for pos in ball_positions]
63
  y_coords = [pos[1] for pos in ball_positions]
 
67
  try:
68
  fx = interp1d(times, x_coords, kind='linear', fill_value="extrapolate")
69
  fy = interp1d(times, y_coords, kind='quadratic', fill_value="extrapolate")
70
+ except Exception as e:
71
+ return None, None, f"Error in trajectory interpolation: {str(e)}"
72
 
73
  # Project trajectory forward (0.5 seconds post-impact)
74
  t_future = np.linspace(times[-1], times[-1] + 0.5, 10)
75
  x_future = fx(t_future)
76
  y_future = fy(t_future)
77
 
78
+ return list(zip(x_future, y_future)), t_future, "Trajectory estimated successfully"
79
 
80
  def lbw_decision(ball_positions, trajectory, frames):
81
  # Simplified LBW logic
82
+ if not frames:
83
+ return "Error: No frames processed", None
84
  if not trajectory or len(ball_positions) < 2:
85
+ return "Not enough data (insufficient ball detections)", None
86
 
87
  # Assume stumps are at the bottom center of the frame (calibration needed)
88
  frame_height, frame_width = frames[0].shape[:2]
 
108
 
109
  def generate_slow_motion(frames, trajectory, output_path):
110
  # Generate very slow-motion video with ball detection and trajectory overlay
111
+ if not frames:
112
+ return None
113
  fourcc = cv2.VideoWriter_fourcc(*'mp4v')
114
  out = cv2.VideoWriter(output_path, fourcc, FRAME_RATE / SLOW_MOTION_FACTOR, (frames[0].shape[1], frames[0].shape[0]))
115
 
 
124
 
125
  def drs_review(video):
126
  # Process video and generate DRS output
127
+ frames, ball_positions, debug_log = process_video(video)
128
+ if not frames:
129
+ return f"Error: Failed to process video\nDebug Log:\n{debug_log}", None
130
+ trajectory, _, trajectory_log = estimate_trajectory(ball_positions, frames)
131
  decision, trajectory = lbw_decision(ball_positions, trajectory, frames)
132
 
133
+ # Generate slow-motion replay even if Trajectory fails
134
  output_path = f"output_{uuid.uuid4()}.mp4"
135
  slow_motion_path = generate_slow_motion(frames, trajectory, output_path)
136
 
137
+ # Combine debug logs for output
138
+ debug_output = f"{debug_log}\n{trajectory_log}"
139
+ return f"DRS Decision: {decision}\nDebug Log:\n{debug_output}", slow_motion_path
140
 
141
  # Gradio interface
142
  iface = gr.Interface(
143
  fn=drs_review,
144
  inputs=gr.Video(label="Upload Video Clip"),
145
  outputs=[
146
+ gr.Textbox(label="DRS Decision and Debug Log"),
147
+ gr.Video(label="Very Slow-Motion Replay with Ball Detection and Trajectory")
148
  ],
149
  title="AI-Powered DRS for LBW in Local Cricket",
150
+ description="Upload a video clip of a cricket delivery to get an LBW decision and very slow-motion replay showing ball detection (green boxes) and trajectory (blue dots)."
151
  )
152
 
153
  if __name__ == "__main__":