由视频提取图片 发表于 2017-09-27 | 更新于 2020-06-02 | 分类于 scripts 由视频提取图片从视频中隔帧或者使用帧差法提取图片 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283# -*-coding:utf-8 -*-import cv2import osimport globimport numpy as np__author__ = 'Heroinlj <heroinlj@gmail.com>'# 隔帧提取图片def extract_frames_by_frame(video_folders_path, dst_folder, index=1): if not os.path.exists(dst_folder): os.makedirs(dst_folder) video = cv2.VideoCapture() for video_path in glob.glob("{}/*.avi".format(video_path_folder)): if not video.open(video_path): print("can not open the video") continue count = 1 while True: _, frame = video.read() if frame is None: break if count % 100 == 0: save_path = "{}\\{:>08d}.jpg".format(dst_folder, index) if index % 1000 == 0: print("save {:d} images".format(index)) print(video_path) cv2.imwrite(save_path, frame) index += 1 count += 1 video.release() return index# 帧差提取图片def extract_frames_by_frame_diff(video_path_folder, dst_folder): if not os.path.exists(dst_folder): os.makedirs(dst_folder) video = cv2.VideoCapture() pre_frame = None for video_path in glob.glob("{}/*.avi".format(video_path_folder)): video_name = video_path.replace('\\', "/").split('/')[-1].split('.')[0] # print(video_name) index = 1 if not video.open(video_path): print("can not open the video") continue count = 1 # pre_frame = None while True: _, frame = video.read() if frame is None: break if pre_frame is None: pre_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) if count % 5 == 0: gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) frameDelta = cv2.absdiff(pre_frame, gray) empty_image = np.asarray(frameDelta, np.uint8) # cv2.imshow("diff", frameDelta) # cv2.waitKey(1) if np.sum(empty_image)/np.sum(gray) > 0.15: save_path = "{}\\{:s}_{:>03d}.jpg".format(dst_folder, video_name, index) # print(save_path) if count % 10 == 0: cv2.imwrite(save_path, frame) index += 1 pre_frame = gray count += 1 video.release()def main(): video_folders_path = r"./videos" dst_folder = r"./images" # extract_frames_by_frame(video_folders_path, dst_folder) extract_frames_by_frame_diff(video_folders_path, dst_folder)if __name__ == '__main__': main()