File size: 1,679 Bytes
6b5b22f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import cv2
import os
from pathlib import Path

def extract_frames(video_path, output_dir):
    """Extract all frames from video."""
    cap = cv2.VideoCapture(video_path)
    fps = cap.get(cv2.CAP_PROP_FPS)
    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

    print(f"Video info: {width}x{height}, {fps:.2f} FPS, {total_frames} frames")

    os.makedirs(output_dir, exist_ok=True)
    frame_idx = 0
    while True:
        ret, frame = cap.read()
        if not ret:
            break

        frame_filename = os.path.join(output_dir, f"frame_{frame_idx:06d}.jpg")
        cv2.imwrite(frame_filename, frame)
        frame_idx += 1

        if frame_idx % 100 == 0:
            print(f"Extracted {frame_idx}/{total_frames} frames")

    cap.release()
    print(f"✅ Extracted {frame_idx} frames to {output_dir}")
    return fps, width, height, frame_idx

def create_video_from_frames(frames_dir, output_path, fps, width, height):
    """Compile frames into an MP4 video."""
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
    
    frame_files = sorted([f for f in os.listdir(frames_dir) if f.endswith('.jpg')])
    print(f"Compiling {len(frame_files)} frames into {output_path}...")
    
    for i, frame_file in enumerate(frame_files):
        frame = cv2.imread(os.path.join(frames_dir, frame_file))
        out.write(frame)
        if (i + 1) % 100 == 0:
            print(f"Written {i+1}/{len(frame_files)} frames")
            
    out.release()
    print(f"✅ Video saved to {output_path}")