video_to_img.py 2.26 KB
Newer Older
mashun1's avatar
mashun1 committed
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import cv2
import os


def v2i(video_path,
        output_dir,
        frame_rate: int,
        frame_nums: int):
    
    video_capture = cv2.VideoCapture(video_path)

    if not video_capture.isOpened():
        print("Error: Cannot open video file.")
        exit()
    
    # 创建文件夹及timestamps.txt
    os.makedirs(os.path.join(output_dir, "images"), exist_ok=True)
    timestamps_path = os.path.join(output_dir, "timestamps.txt")
    with open(timestamps_path, "w") as f:
        pass
    
    video_fps = video_capture.get(cv2.CAP_PROP_FPS)
    print(f"Video FPS: {video_fps}")

    frame_interval = video_fps // frame_rate
    
    frame_count = 0
    saved_frame_cout = 0
    timestamps = []
    
    while True:
        ret, frame = video_capture.read()
        
        if frame_count > frame_nums:
            break
        
        if ret:
            if frame_count % frame_interval == 0:
                
                timestamp = video_capture.get(cv2.CAP_PROP_POS_MSEC) / 1000.0
                
                if frame_count == 0:
                    timestamps.append(0/1000.0)
                
                else:
                    timestamps.append(timestamp)
                
                frame_filename = os.path.join(output_dir, "images", f"image_{saved_frame_cout:06d}.png")

                cv2.imwrite(frame_filename, frame)

                print(f"Saved {frame_filename}, timestamp: {timestamp}")

                saved_frame_cout += 1
        
            frame_count += 1
        
        else:
            break
    
    video_capture.release()
    
    with open(timestamps_path, "w") as f:
        for idx, t in enumerate(timestamps):
            if idx + 1 < len(timestamps):
                f.write(str(t)+'\n')
            else:
                f.write(str(t))
    
    print("Finished extracting frames.")


if __name__ == "__main__":
    import argparse
    
    parser = argparse.ArgumentParser()
    
    parser.add_argument("--video_path", type=str)
    
    parser.add_argument("--output_dir", type=str)
    
    parser.add_argument("--frame_rate", type=int, default=25)
    
    parser.add_argument("--frame_nums", type=int, default=90)
    
    args = parser.parse_args()
    
    v2i(args.video_path, args.output_dir, args.frame_rate, args.frame_nums)