import cv2 import numpy as np from pathlib import Path from PIL import Image # Select files using glob (for now, only process the first file for testing) shots_dir = Path('data/shots') files = sorted(shots_dir.glob('sample-000-0.webp')) # Change pattern to 'sample-*.webp' for batch if not files: print('No files found.') exit(1) # Process each file serially (for now, just one file) for webp_path in files: print(f'Processing {webp_path}') # Extract all frames from the animated webp using PIL frames = [] frame_durations = [] with Image.open(webp_path) as im: try: while True: frame = im.convert('RGB') frames.append(np.array(frame)[:, :, ::-1]) # Convert RGB to BGR for OpenCV # Get duration in ms for this frame (default to 100ms if not present) duration = im.info.get('duration', 100) frame_durations.append(duration) im.seek(im.tell() + 1) except EOFError: pass # Debug: check extracted frames print(f"Extracted {len(frames)} frames from {webp_path}") if len(frames) > 0: print(f"First frame shape: {frames[0].shape}, dtype: {frames[0].dtype}, min: {frames[0].min()}, max: {frames[0].max()}") # Compute dense optical flow and overlay visualization hsv = None motion_frames = [] for i in range(1, len(frames)): prev = cv2.cvtColor(frames[i-1], cv2.COLOR_BGR2GRAY) curr = cv2.cvtColor(frames[i], cv2.COLOR_BGR2GRAY) flow = cv2.calcOpticalFlowFarneback(prev, curr, None, 0.5, 3, 15, 3, 5, 1.2, 0) mag, ang = cv2.cartToPolar(flow[...,0], flow[...,1]) print(f"Frame {i}: flow mag min={mag.min()}, max={mag.max()}, mean={mag.mean()}") if np.all(mag == 0): print(f"Frame {i}: All zero motion, skipping.") continue # Draw flow as arrows on a grid step = 16 # grid size arrow_color = (0, 255, 0) # green arrow_thickness = 1 overlay = frames[i].copy() h, w = prev.shape for y in range(0, h, step): for x in range(0, w, step): fx, fy = flow[y, x] end_x = int(x + fx * 4) end_y = int(y + fy * 4) cv2.arrowedLine(overlay, (x, y), (end_x, end_y), arrow_color, arrow_thickness, tipLength=0.3) motion_frames.append(overlay) # Save as mp4 if motion_frames: height, width, _ = motion_frames[0].shape # Calculate FPS from frame durations (use mean duration between frames) if len(frame_durations) > 1: # Use durations between frames (skip first frame) mean_duration = np.mean(frame_durations[1:]) else: mean_duration = 100 fps = 1000.0 / mean_duration if mean_duration > 0 else 10 print(f"Using FPS: {fps:.2f} (mean frame duration: {mean_duration} ms)") if hasattr(cv2, 'VideoWriter_fourcc'): fourcc = cv2.VideoWriter_fourcc(*'avc1') # More compatible MP4 codec for macOS else: raise RuntimeError('cv2.VideoWriter_fourcc is not available in your OpenCV installation. Please update OpenCV.') out_path = webp_path.parent / f"{webp_path.stem}.motion.mp4" out = cv2.VideoWriter(str(out_path), fourcc, fps, (width, height)) for f in motion_frames: out.write(f) out.release() print(f'Saved {out_path}') else: print('No motion frames to save for', webp_path)