原文链接
import cv2
import os
from pathlib import Path
VID_FORMATS = ('.mov', '.avi', '.mp4', '.mpg', '.mpeg', '.m4v', '.wmv', '.mkv', '.mp3')
def videos2images(root_video_path, root_save_dir):
for video_dir_path in root_video_path:
path_video = Path(video_dir_path)
if path_video.is_dir():
print(video_dir_path + '\t ok')
videos = os.listdir(video_dir_path)
else:
print('\033[31mLine36 error: \033[31m' + video_dir_path + 'is not exist!')
return
save_name_dir = Path(path_video.name)
save_name_dir = os.path.join(root_save_dir, save_name_dir)
if not os.path.exists(save_name_dir):
os.makedirs(save_name_dir)
file_count = 0
for video in videos:
if Path(video).suffix in VID_FORMATS:
file_count += 1
save_jpg_dir = os.path.join(save_name_dir, Path(video).stem)
if not os.path.exists(save_jpg_dir):
os.makedirs(save_jpg_dir)
each_video_path = os.path.join(path_video, video)
save_dir = save_jpg_dir
else:
print('\033[33mLine56 warning: \033[33m' + os.path.basename(video) + ' is not a video file, so skip.')
continue
print('\033[38m' + str(file_count) + ':' + Path(video).stem + '\033[38m')
cap = cv2.VideoCapture(each_video_path)
flag = cap.isOpened()
if not flag:
print("\033[31mLine 65 error\033[31m: open" + each_video_path + "error!")
frame_count = 0
while True:
frame_count += 1
flag, frame = cap.read()
if not flag:
break
if os.path.exists(
save_dir + str(frame_count) + '.jpg'):
break
if frame_count % 5 == 0:
cv2.imwrite(save_dir + '\\' + str(frame_count) + '.jpg', frame)
cap.release()
print('\033[38m' + Path(video).stem + ' save to ' + save_dir + 'finished. \033[38m')
if __name__ == '__main__':
video_path_list = [r'E:\code\tools\video']
image_save_dir = r'E:\code\tools\image'
path_save = Path(image_save_dir)
if not path_save.exists():
path_save.mkdir()
videos2images(video_path_list, image_save_dir)