import os import cv2 import numpy as np # Paths videos_dir = "test_vid" frames_dir = "test_frame" # Define how many frames to extract for each video (should be same in GT file last row) frames_to_extract = { "task_day_left_turn-2024_07_31_02_12_05-mot 1.1.mp4": 1965, # add more here... } os.makedirs(frames_dir, exist_ok=True) for video_file in os.listdir(videos_dir): if video_file.lower().endswith(".mp4"): video_path = os.path.join(videos_dir, video_file) # Subdirectory name (remove .mp4) subdir_name = os.path.splitext(video_file)[0] subdir_path = os.path.join(frames_dir, subdir_name) os.makedirs(subdir_path, exist_ok=True) cap = cv2.VideoCapture(video_path) total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) desired_frames = frames_to_extract.get(video_file, total_frames) saved = 0 frames = [] while True: ret, frame = cap.read() if not ret: break frames.append(frame) cap.release() if desired_frames > len(frames): last_frame = frames[-1] while len(frames) < desired_frames: frames.append(last_frame) if desired_frames < len(frames): indices = np.linspace(0, len(frames) - 1, desired_frames, dtype=int) frames = [frames[i] for i in indices] for idx, frame in enumerate(frames): frame_filename = os.path.join(subdir_path, f"frame_{idx:05d}.jpg") cv2.imwrite(frame_filename, frame) saved += 1 print(f"Extracted {saved} frames from {video_file} into {subdir_name}/") print(" Done extracting frames for all videos.")