Python快速从视频中提取视频帧(多线程)

Python快速提取视频帧(多线程)

今天介绍一种从视频中抽取视频帧的方法,由于单线程抽取视频帧速度较慢,因此这里我们增加了多线程的方法。

1、抽取视频帧

抽取视频帧主要使用了 Opencv 模块。

其中:
camera = cv2.Videocapture( ) ,函数主要是通过调用笔记本内置摄像头读取视频帧;

res, image = camera.read( ) 函数主要是按帧读取视频,返回值 “res” 是布尔型,成功读取返回 True,读取失败返回 False;

最后用 cv2.imwrite( ) 函数存储读取到的视频帧。

视频帧抽取方法可参考博客:https://blog.csdn.net/qq_43071209/article/details/115345299

import cv2
import os

def video_to_frames(video_path, outPutDirName):
    times = 0
    
    # 提取视频的频率,每1帧提取一个
    frame_frequency = 1
    
	# 如果文件目录不存在则创建目录
    if not os.path.exists(outPutDirName):
        os.makedirs(outPutDirName)
        
    # 读取视频帧
    camera = cv2.VideoCapture(video_path)
    
    while True:
        times = times + 1
        res, image = camera.read()
        if not res:
            print('not res , not image')
            break
        # 按照设置间隔存储视频帧
        if times % frame_frequency == 0:
            cv2.imwrite(outPutDirName + '\\' + str(times)+'.jpg', image)
            
    print('图片提取结束')
    # 释放摄像头设备
    camera.release()

2、多线程方法

多线程的应用主要使用了 threading 库。

其中:
threading.Thread( ) 函数主要用来调用多线程,其中参数 “target” 是上面用到的函数,参数 “args” 是上面函数的输入参数。

其中有关多线程的详细介绍,以及速度提升效果可参考博客: https://blog.csdn.net/qq_36044523/article/details/108849365

import threading

threading.Thread(target=video_to_frames, args=(video_path, outPutDirName)).start()

经验证,速度提升还是很快的!

3、整体代码

import cv2
import os
import threading

def video_to_frames(video_path, outPutDirName):
    times = 0
    
    # 提取视频的频率,每1帧提取一个
    frame_frequency = 1
    
	# 如果文件目录不存在则创建目录
    if not os.path.exists(outPutDirName):
        os.makedirs(outPutDirName)
        
    # 读取视频帧
    camera = cv2.VideoCapture(video_path)
    
    while True:
        times = times + 1
        res, image = camera.read()
        if not res:
            print('not res , not image')
            break
        if times % frame_frequency == 0:
            cv2.imwrite(outPutDirName + '\\' + str(times)+'.jpg', image)
            
    print('图片提取结束')
    camera.release()


if __name__ == "__main__":
    input_dir = r'D:\datasets\cow_dataset'       # 输入的video文件夹位置
    save_dir = r'E:\relate_code\dataset'         # 输出图片到当前目录video文件夹下
    count = 0   # 视频数
    for video_name in os.listdir(input_dir):
        video_path = os.path.join(input_dir, video_name)
        outPutDirName = os.path.join(save_dir, video_name[:-4])
        threading.Thread(target=video_to_frames, args=(video_path, outPutDirName)).start()
        count = count + 1
        print("%s th video has been finished!" % count)

日常学习记录,一起交流讨论吧!侵权联系~

来源:WYKB_Mr_Q

物联沃分享整理
物联沃-IOTWORD物联网 » Python快速从视频中提取视频帧(多线程)

发表评论