Skip to content

Video ‐ Frames

qingy1337 edited this page Aug 30, 2024 · 1 revision
import cv2
import os
from tqdm import tqdm
from PIL import Image

# Path to the video file
video_path = '../../Downloads/zi.mp4'

# Output directory for frames
output_dir = 'train_data/Zhi/'
os.makedirs(output_dir, exist_ok=True)

# Open the video file
cap = cv2.VideoCapture(video_path)

frame_count = 0
saved_count = 0

for i in tqdm(range(21168)):
    ret, frame = cap.read()
    if not ret:
        break
    
    frame_count += 1

    # Process every nth frame ---- Change here
    if frame_count % 30 == 0:
        # Convert the frame to RGB (optional)
        rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        
        # Save the frame
        save_path = os.path.join(output_dir, f'frame_{frame_count}.jpg')
        Image.fromarray(rgb_frame).save(save_path)
        saved_count += 1

# Release the video capture object
cap.release()

print(f"Saved {saved_count} frames to {output_dir}")
Clone this wiki locally