# -*- coding: utf-8-*-import os
import cv2 ##加載OpenCV模塊def video2frames(pathIn='', pathOut='', only_output_video_info = False, extract_time_points = None, initial_extract_time =0,end_extract_time = None,extract_time_interval =-1, output_prefix ='frame',jpg_quality =100,isColor = True):'''pathIn:視頻的路徑,比如:F:\python_tutorials\test.mp4pathOut:設(shè)定提取的圖片保存在哪個(gè)文件夾下,比如:F:\python_tutorials\frames1\。如果該文件夾不存在,函數(shù)將自動(dòng)創(chuàng)建它only_output_video_info:如果為True,只輸出視頻信息(長(zhǎng)度、幀數(shù)和幀率),不提取圖片extract_time_points:提取的時(shí)間點(diǎn),單位為秒,為元組數(shù)據(jù),比如,(2,3,5)表示只提取視頻第2秒, 第3秒,第5秒圖片initial_extract_time:提取的起始時(shí)刻,單位為秒,默認(rèn)為0(即從視頻最開始提取)end_extract_time:提取的終止時(shí)刻,單位為秒,默認(rèn)為None(即視頻終點(diǎn))extract_time_interval:提取的時(shí)間間隔,單位為秒,默認(rèn)為-1(即輸出時(shí)間范圍內(nèi)的所有幀)output_prefix:圖片的前綴名,默認(rèn)為frame,圖片的名稱將為frame_000001.jpg、frame_000002.jpg、frame_000003.jpg......jpg_quality:設(shè)置圖片質(zhì)量,范圍為0到100,默認(rèn)為100(質(zhì)量最佳)isColor:如果為False,輸出的將是黑白圖片'''cap = cv2.VideoCapture(pathIn) ##打開視頻文件n_frames =int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) ##視頻的幀數(shù)fps = cap.get(cv2.CAP_PROP_FPS) ##視頻的幀數(shù)dur = n_frames/fps ##視頻的時(shí)間##如果only_output_video_info=True, 只輸出視頻信息,不提取圖片if only_output_video_info:print('only output the video information (without extract frames)::::::')print("Duration of the video: {} seconds".format(dur))print("Number of frames: {}".format(n_frames))print("Frames per second (FPS): {}".format(fps)) ##提取特定時(shí)間點(diǎn)圖片elif extract_time_points is not None:ifmax(extract_time_points)> dur: ##判斷時(shí)間點(diǎn)是否符合要求raise NameError('the max time point is larger than the video duration....')try:os.mkdir(pathOut)except OSError:passsuccess = Truecount =0while success and count <len(extract_time_points):cap.set(cv2.CAP_PROP_POS_MSEC,(1000*extract_time_points[count])) success,image = cap.read()if success:if not isColor:image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) ##轉(zhuǎn)化為黑白圖片print('Write a new frame: {}, {}th'.format(success, count+1))cv2.imwrite(os.path.join(pathOut,"{}_{:06d}.jpg".format(output_prefix, count+1)), image,[int(cv2.IMWRITE_JPEG_QUALITY), jpg_quality]) # save frame asJPEG filecount = count +1else:##判斷起始時(shí)間、終止時(shí)間參數(shù)是否符合要求if initial_extract_time > dur:raise NameError('initial extract time is larger than the video duration....')if end_extract_time is not None:if end_extract_time > dur:raise NameError('end extract time is larger than the video duration....')if initial_extract_time > end_extract_time:raise NameError('end extract time is less than the initial extract time....')##時(shí)間范圍內(nèi)的每幀圖片都輸出if extract_time_interval ==-1:if initial_extract_time >0:cap.set(cv2.CAP_PROP_POS_MSEC,(1000*initial_extract_time))try:os.mkdir(pathOut)except OSError:passprint('Converting a video into frames......')if end_extract_time is not None:N=(end_extract_time - initial_extract_time)*fps +1success = Truecount =0while success and count <N:success,image = cap.read()if success:if not isColor:image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)print('Write a new frame: {}, {}/{}'.format(success, count+1, n_frames))cv2.imwrite(os.path.join(pathOut,"{}_{:06d}.jpg".format(output_prefix, count+1)), image,[int(cv2.IMWRITE_JPEG_QUALITY), jpg_quality]) # save frame asJPEG filecount = count +1else:success = Truecount =0while success:success,image = cap.read()if success:if not isColor:image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)print('Write a new frame: {}, {}/{}'.format(success, count+1, n_frames))cv2.imwrite(os.path.join(pathOut,"{}_{:06d}.jpg".format(output_prefix, count+1)), image,[int(cv2.IMWRITE_JPEG_QUALITY), jpg_quality]) # save frame asJPEG filecount = count +1##判斷提取時(shí)間間隔設(shè)置是否符合要求 elif extract_time_interval >0 and extract_time_interval <1/fps:raise NameError('extract_time_interval is less than the frame time interval....')elif extract_time_interval >(n_frames/fps):raise NameError('extract_time_interval is larger than the duration of the video....')##時(shí)間范圍內(nèi)每隔一段時(shí)間輸出一張圖片else:try:os.mkdir(pathOut)except OSError:passprint('Converting a video into frames......')if end_extract_time is not None:N=(end_extract_time - initial_extract_time)/extract_time_interval +1success = Truecount =0while success and count <N:cap.set(cv2.CAP_PROP_POS_MSEC,(1000*initial_extract_time+count*1000*extract_time_interval)) success,image = cap.read()if success:if not isColor:image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)print('Write a new frame: {}, {}th'.format(success, count+1))cv2.imwrite(os.path.join(pathOut,"{}_{:06d}.jpg".format(output_prefix, count+1)), image,[int(cv2.IMWRITE_JPEG_QUALITY), jpg_quality]) # save frame asJPEG filecount = count +1else:success = Truecount =0while success:cap.set(cv2.CAP_PROP_POS_MSEC,(1000*initial_extract_time+count*1000*extract_time_interval)) success,image = cap.read()if success:if not isColor:image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)print('Write a new frame: {}, {}th'.format(success, count+1))cv2.imwrite(os.path.join(pathOut,"{}_{:06d}.jpg".format(output_prefix, count+1)), image,[int(cv2.IMWRITE_JPEG_QUALITY), jpg_quality]) # save frame asJPEG filecount = count +1##### 測(cè)試
pathIn ='test.mp4'video2frames(pathIn, only_output_video_info = True)pathOut ='./frames1/'video2frames(pathIn, pathOut)pathOut ='./frames2'video2frames(pathIn, pathOut, extract_time_points=(1,2,5))pathOut ='./frames3'video2frames(pathIn, pathOut,initial_extract_time=1,end_extract_time=3,extract_time_interval =0.5) pathOut ='./frames4/'video2frames(pathIn, pathOut, extract_time_points=(0.3,2), isColor = False)pathOut ='./frames5/'video2frames(pathIn, pathOut, extract_time_points=(0.3,2), jpg_quality=50)