import cv2
import os
import threading

# 获取所有文件
def getAllFiles(fire_dir):
    filepath_list = []
    for root,folder_names,file_names in os.walk(fire_dir):
        for file_name in file_names:
            file_path = root+os.sep+file_name
            filepath_list.append(file_path)
            print(file_path)
    print(filepath_list)
    return filepath_list

def save_image(image, addr, num, type=".jpg"):
    address = addr + "img_" + str(num) + type
    cv2.imwrite(address, image)

def video_to_frames(video_path, frame_frequency=1,pic_type=".png"):
    wenjianhouzui =  os.path.splitext(video_path)[-1]

    fi = 0

    # 提取视频的频率,每1帧提取一个
    frame_frequency = frame_frequency

    outPutDirName = video_path.strip(wenjianhouzui)+"\\"
    # 如果文件目录不存在则创建目录
    if not os.path.exists(outPutDirName):
        os.makedirs(outPutDirName)

    # 读取视频帧
    camera = cv2.VideoCapture(video_path)

    while True:
        fi = fi + 1
        res, image = camera.read()
        if not res:
            print('not res , not image')
            break
        # 按照设置间隔存储视频帧
        if fi % frame_frequency == 0:
            save_image(image, addr=outPutDirName, num=fi, type=pic_type)
            print('save image: ', fi)

    print('图片提取结束')
    # 释放摄像头设备
    camera.release()

def getAllAndZhuanHua(src,frame_frequency=1):
    filepath_list = getAllFiles(src)
    for f in filepath_list:
        print(f)
        video_to_frames(video_path=f, frame_frequency=frame_frequency)


def getAllAndZhuanHuaDuoXiancheng(src,frame_frequency=1,pic_type=".png"):
    filepath_list = getAllFiles(src)
    for f in filepath_list:
        print(f)
        threading.Thread(target=video_to_frames, args=(f, frame_frequency,pic_type)).start()



if __name__ == '__main__':
    src = r"E:\englishpic\xintu\video"     #路径不要有中文
    frame_frequency = 1000
    pic_type = ".png"
    getAllAndZhuanHuaDuoXiancheng(src=src, frame_frequency=frame_frequency,pic_type=pic_type)

 

posted on 2022-07-31 08:28  大话人生  阅读(409)  评论(0编辑  收藏  举报