import cv2
import os

# 配置
video_path = r'J:\git\3D-pano\video.mp4'
output_dir = r'J:\git\3D-pano\images'
total_frames = 336

# 确保输出目录存在
os.makedirs(output_dir, exist_ok=True)

# 打开视频
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
    print('Error: Cannot open video')
    exit(1)

video_frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
print(f'Video total frames: {video_frame_count}')

# 计算帧间隔
interval = video_frame_count // total_frames

for i in range(total_frames):
    frame_idx = i * interval
    cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx)
    ret, frame = cap.read()
    
    if ret:
        output_path = os.path.join(output_dir, f'car_{str(i+1).zfill(3)}.jpg')
        cv2.imwrite(output_path, frame, [cv2.IMWRITE_JPEG_QUALITY, 90])
        print(f'Saved: {output_path}')
    else:
        print(f'Failed to read frame {frame_idx}')

cap.release()
print(f'Done! Extracted {total_frames} frames to {output_dir}')
