|
|
import cv2 |
|
|
import numpy as np |
|
|
from pathlib import Path |
|
|
from PIL import Image |
|
|
|
|
|
|
|
|
shots_dir = Path('data/shots') |
|
|
files = sorted(shots_dir.glob('sample-000-0.webp')) |
|
|
if not files: |
|
|
print('No files found.') |
|
|
exit(1) |
|
|
|
|
|
|
|
|
for webp_path in files: |
|
|
print(f'Processing {webp_path}') |
|
|
|
|
|
frames = [] |
|
|
frame_durations = [] |
|
|
with Image.open(webp_path) as im: |
|
|
try: |
|
|
while True: |
|
|
frame = im.convert('RGB') |
|
|
frames.append(np.array(frame)[:, :, ::-1]) |
|
|
|
|
|
duration = im.info.get('duration', 100) |
|
|
frame_durations.append(duration) |
|
|
im.seek(im.tell() + 1) |
|
|
except EOFError: |
|
|
pass |
|
|
|
|
|
|
|
|
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()}") |
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
step = 16 |
|
|
arrow_color = (0, 255, 0) |
|
|
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) |
|
|
|
|
|
|
|
|
if motion_frames: |
|
|
height, width, _ = motion_frames[0].shape |
|
|
|
|
|
if len(frame_durations) > 1: |
|
|
|
|
|
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') |
|
|
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) |
|
|
|