视频逐帧分离脚本,用于快速分析动效抖动问题

import cv2
import argparse
import os

# 定义默认的视频路径和输出文件夹
DEFAULT_VIDEO_PATH = "C:\\Users\\sober\\Videos\\Captures\\VID_20230822_160700.mp4"
DEFAULT_OUTPUT_FOLDER = "C:\\Users\\sober\\OneDrive\\work\\python\\video_analysis\\video"

def extract_frames(video_path, output_folder, interval_ms=16):
    # Create output folder if it doesn't exist
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    cap = cv2.VideoCapture(video_path)
    
    # Fetch video properties
    frame_rate = cap.get(cv2.CAP_PROP_FPS)
    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    video_duration = total_frames / frame_rate
    video_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    video_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    
    # Print video properties
    print(f"Video Path: {video_path}")
    print(f"Frame Rate: {frame_rate} fps")
    print(f"Total Frames: {total_frames}")
    print(f"Duration: {video_duration:.2f} seconds")
    print(f"Resolution: {video_width}x{video_height}")
    
    frame_interval = frame_rate * interval_ms / 1000

    for frame_count in range(total_frames):
        ret, frame = cap.read()
        if not ret:
            break

        # Calculate the timestamp for the current frame
        timestamp_ms = frame_count * (1000 / frame_rate)

        if frame_count % frame_interval < 1:  # This condition helps in handling non-integer frame intervals
            output_file = os.path.join(output_folder, f"{int(timestamp_ms)}.png")
            cv2.imwrite(output_file, frame)

    cap.release()

    print(f"\nExtracted frames from {video_path} to {output_folder}.")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Extract frames from a video every 16ms.")
    parser.add_argument("--video_path", type=str, default=DEFAULT_VIDEO_PATH, help=f"Path to the video file. Default is {DEFAULT_VIDEO_PATH}")
    parser.add_argument("--output_folder", type=str, default=DEFAULT_OUTPUT_FOLDER, help=f"Folder to save the extracted frames. Default is {DEFAULT_OUTPUT_FOLDER}")
    args = parser.parse_args()

    extract_frames(args.video_path, args.output_folder)