import cv2 import numpy as np import tempfile import os from moviepy.editor import ImageSequenceClip def draw_virtual_stumps(frame, stump_zone=(280, 360), pitch_y=570): """ Draw stumps and crease lines on the pitch. """ for x in range(stump_zone[0], stump_zone[1] + 1, 20): cv2.line(frame, (x, pitch_y), (x, pitch_y - 60), (255, 255, 255), 2) cv2.line(frame, (stump_zone[0] - 40, pitch_y), (stump_zone[1] + 40, pitch_y), (255, 255, 255), 2) def draw_trajectory(frame, trajectory_points): """ Draws the predicted ball trajectory curve on frame. """ for pt in trajectory_points: x, y = pt cv2.circle(frame, (int(x), int(y)), 5, (0, 255, 0), -1) def add_decision_text(frame, decision): """ Overlay OUT / NOT OUT decision on top of the frame. """ color = (0, 0, 255) if decision == "OUT" else (0, 255, 0) cv2.putText(frame, f"Decision: {decision}", (30, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.5, color, 3) def generate_output_video(frames, detection_data, prediction_data, fps=25): """ Generates replay video with overlays and returns its file path and decision. """ impact_frame = detection_data["impact_frame"] decision = prediction_data["decision"] trajectory = prediction_data["trajectory_points"] annotated_frames = [] for idx, frame in enumerate(frames): frame_copy = frame.copy() draw_virtual_stumps(frame_copy) if idx <= impact_frame: # Draw live ball trajectory up to impact draw_trajectory(frame_copy, trajectory[:idx + 1]) else: # Draw full trajectory post-impact draw_trajectory(frame_copy, trajectory) if idx == impact_frame: cv2.rectangle(frame_copy, (0, 0), (frame.shape[1], frame.shape[0]), (255, 0, 0), 6) add_decision_text(frame_copy, decision) annotated_frames.append(cv2.cvtColor(frame_copy, cv2.COLOR_BGR2RGB)) # Save as video using moviepy temp_dir = tempfile.mkdtemp() output_path = os.path.join(temp_dir, "lbw_replay.mp4") clip = ImageSequenceClip(annotated_frames, fps=fps) clip.write_videofile(output_path, codec="libx264", audio=False, verbose=False, logger=None) return output_path, decision