Python快速从视频中提取视频帧(多线程)
生活随笔
收集整理的這篇文章主要介紹了
Python快速从视频中提取视频帧(多线程)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
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 osdef video_to_frames(video_path, outPutDirName):times = 0# 提取視頻的頻率,每1幀提取一個frame_frequency = 1# 如果文件目錄不存在則創(chuàng)建目錄if not os.path.exists(outPutDirName):os.makedirs(outPutDirName)# 讀取視頻幀camera = cv2.VideoCapture(video_path)while True:times = times + 1res, 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 threadingthreading.Thread(target=video_to_frames, args=(video_path, outPutDirName)).start()經驗證,速度提升還是很快的!
3、整體代碼
import cv2 import os import threadingdef video_to_frames(video_path, outPutDirName):times = 0# 提取視頻的頻率,每1幀提取一個frame_frequency = 1# 如果文件目錄不存在則創(chuàng)建目錄if not os.path.exists(outPutDirName):os.makedirs(outPutDirName)# 讀取視頻幀camera = cv2.VideoCapture(video_path)while True:times = times + 1res, image = camera.read()if not res:print('not res , not image')breakif 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 + 1print("%s th video has been finished!" % count)日常學習記錄,一起交流討論吧!侵權聯(lián)系~
總結
以上是生活随笔為你收集整理的Python快速从视频中提取视频帧(多线程)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 人工智能高性能计算、神经形态计算和量子计
- 下一篇: 计算机辅助药物设计的基本原理