動画を連番静止画で出力
2022/10/26
Python3.8.2, OpenCV4.4.0
動画のフレームを連番静止画として保存するスクリプト
import cv2
import os
video_path = r'C:\path\your_file.AVI'
dir_path = r'C:\path\dir_name'
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
print('cannot open video.')
exit()
os.makedirs(dir_path, exist_ok=True)
basename = os.path.basename(video_path)
basename = os.path.splitext(basename)[0]
base_path = os.path.join(dir_path, basename)
digit = len(str(int(cap.get(cv2.CAP_PROP_FRAME_COUNT))))
n = 0
while True:
ret, frame = cap.read()
if ret:
fp = '{}_{}.{}'.format(base_path, str(n).zfill(digit), 'jpg')
cv2.imwrite(fp, frame)
n += 1
print('save %s' % fp)
else:
break
print('fin')