python工具:从视频中提取图片

import cv2
import os
import hashlib

#视频文件名与对应提取帧数的索引
file_dict = {"2017-07-04-07-39-28_fovs5.h264": (list(range(2030,3150)) + list(range(3960,4050))),
             "2017-07-04-09-41-55_fovs5.h264": (list(range(1100,1700)) + list(range(2430,4450))),
             "2017-07-04-09-50-22_fovs5.h264": (list(range(0,1240)) + list(range(2200,9000)) + list(range(11320,14000)))}

#计算视频文件的md5值
def getFileMD5(filepath):
    f = open(filepath, 'rb')
    md5obj = hashlib.md5()
    md5obj.update(f.read())
    hash = md5obj.hexdigest()
    f.close()
    return str(hash).upper()

#提取视频中对应帧数段的图片
def selct_sample(video_path,target_path,video_index,filemd5,frameFrequency,extract_num):
    
    cap = cv2.VideoCapture(video_path)
    frame_index = 0
    while True:
        res, image = cap.read()
        if not res:
            print('not res, not image')
            break

        if frame_index % frameFrequency == 0 and frame_index in extract_num:
            image_name = ("{}_{}_{}.png".format(
                          (str(video_index)).zfill(4),  #视频的序列索引
                          filemd5,      #视频的md5值
                          (str(frame_index)).zfill(5))  #帧数
                         )
            cv2.imwrite(os.path.join(target_path,image_name),image)
            print("正在截取:{} ---> {}帧".format(os.path.basename(target_path),frame_index))
        frame_index += 1
    print("图片提取结束")
    cap.release()


def gen_sample(video_path,target_path,video_index,filemd5,frameFrequency):

    cap = cv2.VideoCapture(video_path)
    frame_index = 0
    while True:
        res, image = cap.read()
        if not res:
            print('not res, not image')
            break
        if frame_index % frameFrequency == 0:
            image_name = ("{}_{}_{}.png".format(
                          (str(video_index)).zfill(4),  #视频的序列索引
                          filemd5,      #视频的md5值
                          (str(frame_index)).zfill(5))  #帧数
                         )
            cv2.imwrite(os.path.join(target_path,image_name),image)
            print("正在截取:{} ---> {}帧".format(os.path.basename(target_path),frame_index))
        frame_index += 1
    print("图片提取结束")
    cap.release()


def main():
    #需要处理的视频路径; linux和windows下面注意路径的读取方式有所不同
    src_path = r'D:/Desktop/fovs5_rc/02/'
    #目标文件夹路径
    target_path = r'D:/Desktop/fovs5_rc/02/'
    #设置间隔帧数
    frameFrequency = 10
    # 获取文件路径
    filelist = os.listdir(src_path)
    video_num = len(filelist)
    print("视频个数为:%d" % video_num)
    for item in filelist:
        #设置视频的索引个数
        video_index = 0
        if item.endswith(('.h264','.mp4','.mkv','avi')):
            video_path = os.path.join(src_path,item)
            #获取视频唯一的md5值
            filemd5 = getFileMD5(video_path)
            filename  = item.split(".")[0]
            outPutDir = os.path.join(target_path,filename)
            if not os.path.exists(outPutDir):
                os.mkdir(outPutDir)
            #截取图片
            gen_sample(video_path,outPutDir,video_index,filemd5,frameFrequency)
#            extract_num = file_dict[item]
#            selct_sample(video_path,outPutDir,video_index,filemd5,frameFrequency,extract_num)
            video_index += 1

if __name__ == '__main__':
    main()
  • 通过读取视频的md5值能够保证在批量处理视频文件时,生成的图片文件名不会有重复的情况,图片的命名可以根据实际情况添加相应的标签
  • select_sample支持提取视频中特定帧数段的图片,使用较少
  • 代码运行过程中会打印相应的信息
    python工具:从视频中提取图片_第1张图片
  • 代码运行结束后,会在对应的目标文件夹下,按照设置的隔间帧数生成对应的文件,如设置每隔10帧取一帧,将得到如下结果:
    python工具:从视频中提取图片_第2张图片

你可能感兴趣的:(python,python)