栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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:datasetscow_dataset'       # 输入的video文件夹位置
    save_dir = r'E:relate_codedataset'         # 输出图片到当前目录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)

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/929712.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号