File size: 1,736 Bytes
0d68b6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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.")