File size: 1,985 Bytes
a63ce99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 cv2
import os

def video_to_keyframes(video_path, output_folder, frame_interval=1, prefix='frame'):
    """

    Convert video to keyframes (individual frames) and save as images

    

    Args:

        video_path (str): Path to input video file

        output_folder (str): Directory to save extracted frames

        frame_interval (int): Extract every nth frame (1=every frame)

        prefix (str): Prefix for saved frame files

    """
    # Create output directory if it doesn't exist
    os.makedirs(output_folder, exist_ok=True)
    
    # Open the video file
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        raise ValueError(f"Could not open video {video_path}")
    
    # Get video properties
    fps = cap.get(cv2.CAP_PROP_FPS)
    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    duration = total_frames / fps
    
    print(f"Video Info:")
    print(f"- Path: {video_path}")
    print(f"- FPS: {fps}")
    print(f"- Total Frames: {total_frames}")
    print(f"- Duration: {duration:.2f} seconds")
    print(f"- Extracting every {frame_interval} frame(s)")
    
    frame_count = 0
    saved_count = 0
    
    while True:
        ret, frame = cap.read()
        
        # Stop if we've reached the end of the video
        if not ret:
            break
            
        # Only process frames at the specified interval
        if frame_count % frame_interval == 0:
            # Save frame as image file
            frame_filename = f"{prefix}_{saved_count:06d}.jpg"
            output_path = os.path.join(output_folder, frame_filename)
            cv2.imwrite(output_path, frame)
            saved_count += 1
            
            # Print progress every 100 frames
            if saved_count % 100 == 0:
                print(f"Saved frame {saved_count} (original frame {frame_count})")
        
        frame_count += 1
    
    # Release resources
    cap.release()