Python多线程快速提取视频帧及剔除指定帧实现详解

白榆
白榆
发布时间:2026-10-15 | 3人浏览过
原创

本文详解如何利用Python和OpenCV实现视频帧的快速提取。通过引入threading库进行多线程处理,显著提升单线程下的处理速度。同时提供剔除中间指定帧数的代码示例,展示如何按条件跳过写入,适用于需要特定帧序列的视频处理场景。

Python多线程快速提取视频帧方案

本文介绍一种从视频中高效抽取视频帧的技术。鉴于单线程方式处理视频帧时速度较慢,本文引入了多线程机制以优化处理效率。

1、视频帧抽取基础

视频帧的抽取核心依赖于OpenCV模块。

具体实现涉及以下关键步骤:

使用cv2.VideoCapture()函数初始化视频读取对象,该函数通常用于调用系统摄像头或读取本地视频文件以获取视频流;

通过camera.read()函数按帧读取视频内容,该函数返回两个值:布尔型变量“res”表示读取是否成功(成功返回True,失败返回False),以及图像对象“image”;

最后利用cv2.imwrite()函数将读取到的视频帧保存为图片文件。

关于视频帧抽取的基础方法,可参考相关技术文章。

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、多线程加速方案

多线程功能的实现主要依赖Python标准库threading。

具体应用包括:

使用threading.Thread()函数创建并调用多线程任务,其中参数“target”指定要执行的函数(即上述视频处理函数),参数“args”传递该函数所需的输入参数;

关于多线程的详细用法及性能提升效果,可参考相关技术文章。

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)

补充说明

此外,还可以利用Python开发剔除特定视频帧的工具。

代码示例

以下展示使用OpenCV抽取视频中间部分帧并剔除指定区间的实现方法。

核心逻辑是在读取每一帧(frame)时,判断是否满足写入条件,若满足则写入文件。

对于不需要保留或剔除的帧,直接通过continue语句跳过当前循环,进入下一帧处理。

样例代码主要针对MP4格式视频进行处理。

#!/user/bin/env python
# coding=utf-8
"""
@project : csdn-pro
@author  : 剑客阿良_ALiang
@file   : test.py
@ide    : PyCharm
@time   : 2022-06-30 17:55:48
"""
 
import cv2
 
 
# 视频抽帧
def extract_frame(video_path: str, result_path: str, fps, weight, height, start, end):
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    videoWriter = cv2.VideoWriter(result_path, fourcc, fps, (weight, height))
    vc = cv2.VideoCapture(video_path)
    if vc.isOpened():
        ret, frame = vc.read()
    else:
        ret = False
    count = 0  # count the number of pictures
    while ret:
        ret, frame = vc.read()
        if start <= count <= end:
            count += 1
            continue
        else:
            videoWriter.write(frame)
            count += 1
    print(count)
    videoWriter.release()
    vc.release()
 
 
if __name__ == '__main__':
    extract_frame('C:\\Users\\xxx\\Desktop\\123.mp4', 'C:\\Users\\xxx\\Desktop\\114.mp4', 25, 640, 368, 119, 125)

注意事项

1、extract_frame函数的参数定义如下:输入视频路径、输出视频路径、视频帧率(fps)、视频宽度、视频高度、需要剔除的起始帧索引、需要剔除的结束帧索引。

至此,关于Python快速从视频中提取视频帧及剔除指定帧的方法介绍完毕,更多Python视频处理相关内容可搜索本站历史文章或继续浏览后续教程,感谢支持。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表