Extract Frames from a Video#
This runnable notebook migrates Annolid’s classic frame-extraction tutorial into a self-contained local workflow powered by annolid.data.videos and annolid.data.frame_sampling.
What you will learn:
Inspect video metadata (
fps, resolution, frame count) withextract_video_metadata.Sample evenly spaced or visually diverse keyframes (
uniform,kmeans,flow) usingextract_frames_smart.Extract explicit frame indices with
extract_frames_from_video.Batch-extract frames across a directory of videos with
extract_frames_from_videos.
Tip: Set
VIDEO_PATHbelow to your own.mp4/.avi/.movrecording. When left asNone, the notebook generates a short synthetic demo video automatically so every cell runs offline.
1. Setup & Sample Video Preparation#
from pathlib import Path
import cv2
import matplotlib.pyplot as plt
import numpy as np
from annolid.data.frame_sampling import extract_frames_smart
from annolid.data.videos import (
extract_frames_from_video,
extract_frames_from_videos,
extract_video_metadata,
)
WORK_DIR = Path("./annolid_extract_frames_demo")
WORK_DIR.mkdir(parents=True, exist_ok=True)
# Point VIDEO_PATH to your own recording, or leave as None to use a synthetic clip.
VIDEO_PATH = None
def create_demo_video(output_path: Path, *, num_frames: int = 45, fps: float = 15.0) -> Path:
"""Generate a small synthetic arena clip with two moving subjects."""
width, height = 320, 240
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
writer = cv2.VideoWriter(str(output_path), fourcc, fps, (width, height))
if not writer.isOpened():
raise RuntimeError(f"Could not open VideoWriter for {output_path}")
for idx in range(num_frames):
frame = np.full((height, width, 3), 235, dtype=np.uint8)
# Arena border
cv2.rectangle(frame, (18, 18), (width - 18, height - 18), (90, 90, 90), 2)
# Subject 1 moving horizontally with slight vertical wave
x1 = int(50 + (width - 100) * (idx / max(num_frames - 1, 1)))
y1 = int(95 + 28 * np.sin(idx * 0.25))
cv2.ellipse(frame, (x1, y1), (22, 13), 0, 0, 360, (55, 115, 210), -1)
# Subject 2 moving in a circular loop
angle = 2.0 * np.pi * idx / max(num_frames, 1)
x2 = int(160 + 70 * np.cos(angle))
y2 = int(150 + 40 * np.sin(angle))
cv2.ellipse(frame, (x2, y2), (18, 12), int(np.degrees(angle)), 0, 360, (45, 165, 110), -1)
cv2.putText(
frame,
f"Frame {idx:03d}",
(24, 42),
cv2.FONT_HERSHEY_SIMPLEX,
0.55,
(30, 30, 30),
1,
cv2.LINE_AA,
)
writer.write(frame)
writer.release()
return output_path
video_path = Path(VIDEO_PATH) if VIDEO_PATH else create_demo_video(WORK_DIR / "demo_arena.mp4")
cap = cv2.VideoCapture(str(video_path))
try:
meta = extract_video_metadata(cap)
finally:
cap.release()
print(f"Video: {video_path.name}")
print(
f"Resolution: {int(meta['frame_width'])}x{int(meta['frame_height'])} | "
f"FPS: {meta['fps']:.1f} | Frames: {int(meta['frame_count'])}"
)
Video: demo_arena.mp4
Resolution: 320x240 | FPS: 15.0 | Frames: 45
2. Smart Frame Sampling (uniform vs. kmeans Diversity)#
extract_frames_smart supports uniform, kmeans, hybrid, farthest, and flow (optical-flow motion peaks). For building a compact training set for YOLO or pose models, kmeans selects visually distinct frames instead of redundant idle frames.
uniform_res = extract_frames_smart(
video_path,
output_dir=WORK_DIR / "frames_uniform",
algo="uniform",
num_frames=6,
)
kmeans_res = extract_frames_smart(
video_path,
output_dir=WORK_DIR / "frames_kmeans",
algo="kmeans",
num_frames=6,
seed=42,
)
print("Uniform indices:", list(uniform_res.selected_indices))
print("K-means indices:", list(kmeans_res.selected_indices))
print(f"Saved {len(kmeans_res.saved_paths)} k-means PNG frames to {Path(kmeans_res.output_dir).name}/")
Uniform indices: [0, 9, 18, 26, 35, 44]
K-means indices: [2, 7, 20, 29, 34, 42]
Saved 6 k-means PNG frames to frames_kmeans/
3. Preview Extracted Frames#
fig, axes = plt.subplots(2, 3, figsize=(9.5, 5.2))
for ax, img_path, frame_idx in zip(
axes.flat, kmeans_res.saved_paths, kmeans_res.selected_indices
):
img_bgr = cv2.imread(img_path)
img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
ax.imshow(img_rgb)
ax.set_title(f"k-means frame #{frame_idx}", fontsize=9)
ax.axis("off")
fig.suptitle("Visually Diverse Frames Selected via Annolid extract_frames_smart", fontsize=11)
plt.tight_layout()
plt.show()
4. Extract Specific Frame Indices & Batch Process a Folder#
When you already know key behavioral timestamps (for example from Track QC or an ethogram), pass frame_indices=[...] directly to extract_frames_from_video. For multi-session cohorts, use extract_frames_from_videos(folder, output_folder, num_frames=...).
specific_paths = extract_frames_from_video(
str(video_path),
output_folder=str(WORK_DIR / "frames_specific"),
frame_indices=[0, 12, 24, 36],
)
print("Extracted explicit frames:", [Path(p).name for p in specific_paths])
batch_in = WORK_DIR / "batch_videos"
batch_in.mkdir(exist_ok=True)
create_demo_video(batch_in / "trial_01.mp4", num_frames=30, fps=15.0)
create_demo_video(batch_in / "trial_02.mp4", num_frames=30, fps=15.0)
batch_out = WORK_DIR / "batch_extracted"
extract_frames_from_videos(str(batch_in), output_folder=str(batch_out), num_frames=4)
batch_pngs = sorted(p.name for p in batch_out.glob("*.png"))
print(f"Batch-extracted {len(batch_pngs)} frames across 2 videos:", batch_pngs)
Extracted explicit frames: ['demo_arena_frame000000000.png', 'demo_arena_frame000000012.png', 'demo_arena_frame000000024.png', 'demo_arena_frame000000036.png']
Batch-extracted 8 frames across 2 videos: ['trial_01_frame000000000.png', 'trial_01_frame000000010.png', 'trial_01_frame000000019.png', 'trial_01_frame000000029.png', 'trial_02_frame000000000.png', 'trial_02_frame000000010.png', 'trial_02_frame000000019.png', 'trial_02_frame000000029.png']
Next Steps#
Open the extracted folder in the GUI via
File → Open Dirto annotate polygons or keypoints.Or skip frame extraction altogether and open the video directly with
File → Open Video.See Extracting Frames (GUI & CLI) for the interactive dialog and
annolid-runcommands.