AjaykumarPilla commited on
Commit
a653421
·
verified ·
1 Parent(s): fe5ba09

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -22
app.py CHANGED
@@ -10,39 +10,54 @@ import os
10
  # Load the trained YOLOv8n model from the Space's root directory
11
  model = YOLO("best.pt") # Assumes best.pt is in the same directory as app.py
12
 
13
- # Constants for LBW decision
14
  STUMPS_WIDTH = 0.2286 # meters (width of stumps)
15
  BALL_DIAMETER = 0.073 # meters (approx. cricket ball diameter)
16
- FRAME_RATE = 30 # Default frame rate for video processing
 
 
17
 
18
  def process_video(video_path):
19
  # Initialize video capture
 
 
20
  cap = cv2.VideoCapture(video_path)
21
  frames = []
22
  ball_positions = []
 
23
 
 
24
  while cap.isOpened():
25
  ret, frame = cap.read()
26
  if not ret:
27
  break
 
28
  frames.append(frame.copy()) # Store original frame
29
  # Detect ball using the trained YOLOv8n model
30
- results = model.predict(frame, conf=0.5) # Adjust confidence threshold if needed
 
31
  for detection in results[0].boxes:
32
  if detection.cls == 0: # Assuming class 0 is the ball
 
33
  x1, y1, x2, y2 = detection.xyxy[0].cpu().numpy()
34
  ball_positions.append([(x1 + x2) / 2, (y1 + y2) / 2])
35
  # Draw bounding box on frame for visualization
36
  cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)
37
  frames[-1] = frame # Update frame with bounding box
 
38
  cap.release()
39
 
40
- return frames, ball_positions
 
 
 
 
 
41
 
42
  def estimate_trajectory(ball_positions, frames):
43
  # Simplified physics-based trajectory projection
44
  if len(ball_positions) < 2:
45
- return None, None
46
  # Extract x, y coordinates
47
  x_coords = [pos[0] for pos in ball_positions]
48
  y_coords = [pos[1] for pos in ball_positions]
@@ -52,20 +67,22 @@ def estimate_trajectory(ball_positions, frames):
52
  try:
53
  fx = interp1d(times, x_coords, kind='linear', fill_value="extrapolate")
54
  fy = interp1d(times, y_coords, kind='quadratic', fill_value="extrapolate")
55
- except:
56
- return None, None
57
 
58
  # Project trajectory forward (0.5 seconds post-impact)
59
  t_future = np.linspace(times[-1], times[-1] + 0.5, 10)
60
  x_future = fx(t_future)
61
  y_future = fy(t_future)
62
 
63
- return list(zip(x_future, y_future)), t_future
64
 
65
  def lbw_decision(ball_positions, trajectory, frames):
66
  # Simplified LBW logic
 
 
67
  if not trajectory or len(ball_positions) < 2:
68
- return "Not enough data", None
69
 
70
  # Assume stumps are at the bottom center of the frame (calibration needed)
71
  frame_height, frame_width = frames[0].shape[:2]
@@ -90,43 +107,47 @@ def lbw_decision(ball_positions, trajectory, frames):
90
  return "Not Out (Missing stumps)", trajectory
91
 
92
  def generate_slow_motion(frames, trajectory, output_path):
93
- # Generate slow-motion video with ball detection and trajectory overlay
 
 
94
  fourcc = cv2.VideoWriter_fourcc(*'mp4v')
95
- out = cv2.VideoWriter(output_path, fourcc, FRAME_RATE / 2, (frames[0].shape[1], frames[0].shape[0]))
96
 
97
  for frame in frames:
98
  if trajectory:
99
  for x, y in trajectory:
100
  cv2.circle(frame, (int(x), int(y)), 5, (255, 0, 0), -1) # Blue dots for trajectory
101
- out.write(frame)
102
- out.write(frame) # Duplicate frames for slow-motion effect
103
  out.release()
104
  return output_path
105
 
106
  def drs_review(video):
107
  # Process video and generate DRS output
108
- if not os.path.exists(video):
109
- return "Error: Video file not found", None
110
- frames, ball_positions = process_video(video)
111
- trajectory, _ = estimate_trajectory(ball_positions, frames)
112
  decision, trajectory = lbw_decision(ball_positions, trajectory, frames)
113
 
114
- # Generate slow-motion replay
115
  output_path = f"output_{uuid.uuid4()}.mp4"
116
  slow_motion_path = generate_slow_motion(frames, trajectory, output_path)
117
 
118
- return decision, slow_motion_path
 
 
119
 
120
  # Gradio interface
121
  iface = gr.Interface(
122
  fn=drs_review,
123
  inputs=gr.Video(label="Upload Video Clip"),
124
  outputs=[
125
- gr.Textbox(label="DRS Decision"),
126
- gr.Video(label="Slow-Motion Replay with Ball Detection and Trajectory")
127
  ],
128
  title="AI-Powered DRS for LBW in Local Cricket",
129
- description="Upload a video clip of a cricket delivery to get an LBW decision and slow-motion replay showing ball detection and trajectory."
130
  )
131
 
132
  if __name__ == "__main__":
 
10
  # Load the trained YOLOv8n model from the Space's root directory
11
  model = YOLO("best.pt") # Assumes best.pt is in the same directory as app.py
12
 
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 = 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]
 
107
  return "Not Out (Missing stumps)", trajectory
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
 
116
  for frame in frames:
117
  if trajectory:
118
  for x, y in trajectory:
119
  cv2.circle(frame, (int(x), int(y)), 5, (255, 0, 0), -1) # Blue dots for trajectory
120
+ for _ in range(SLOW_MOTION_FACTOR): # Duplicate frames for very slow motion
121
+ out.write(frame)
122
  out.release()
123
  return output_path
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__":