opencv 视频自动截图-小工具

采用:python多进程
实测:
cpu:i7-9700

92秒 13456张,

平均约每秒146张

import multiprocessing as mp
import os
import cv2
import sys
import time


# 截图保存
def git_img(path: str, n: int, len_n: int,
            name: str, suffix: str, save_path: str,
            frames: str) -> None:
    """
    :param path:完整视频文件路径
    :param n: 起始帧数
    :param len_n: 终止帧数
    :param name: 保存图像文件名
    :param suffix: 保存文件名后缀
    :param save_path: 保存图像文件路径
    :param frames: 隔几帧 保存
    :return: None
    """

    # 读取视频
    cap = cv2.VideoCapture(path)
    cap.set(cv2.CAP_PROP_POS_FRAMES, n)
    l = n
    l1 = 0
    while len_n > l:

        l += 1
        # 设置要获取的帧号
        ret, frame = cap.read()

        if l1 == frames:
            print(len_n, l, "计数")
            l1 = 0
            cv2.imwrite(save_path + name + str(l) + suffix, frame)

        l1 += 1
    cv2.destroyAllWindows()


# 读取视频
path = "./01.mp4"
# 保存图片路径
save_path = "./images/"
# 间隔多少帧
frames = 1
# 文件后缀
suffix = '.jpg'
# 文件名前面加什么区分
name = '2022_'

cap = cv2.VideoCapture(path)
# 获取视频总帧数
cap_len = cap.get(7)
cv2.destroyAllWindows()

# if cap == 0:
#     print("视频未读取到, 请检查文件是否存在")
#     sys.exit()

# 读取电脑有几核
cpu_len = os.cpu_count()
# cpu_len = 6
# print(cap_len)
# print(cpu_len)

# 将视频分为多份 几份根据电脑核数来定
# 每个进程分配多少帧
Average = int(cap_len / cpu_len)

# print(Average)

# 进程 调用git_img函数
list_process = []

for i in range(cpu_len):
    list_process.append(git_img)

# print(list_process)
# print(list_process_name)
if __name__ == '__main__':

    t1 = time.time()

    jobs = []
    start, Termination = 0, Average
    for i in list_process:
        pw = mp.Process(target=i, args=(path, start, Termination, name, suffix, save_path, frames))
        start += Average
        Termination += Average

        # 启动子进程pw,写入:
        pw.start()
        jobs.append(pw)

    # pr.start()

    for i1 in jobs:
        i1.join()

    print("所有进程结束")

    # 需要测试的代码
    t2 = time.time()
    print("以上代码运行时长:", t2 - t1)

opencv 视频自动截图-小工具_第1张图片
opencv 视频自动截图-小工具_第2张图片

你可能感兴趣的:(opencv-python,常用小工具,opencv,音视频,python)