使用Python,OpenCV线程化方式提高视频FPS(每秒帧数)
生活随笔
收集整理的這篇文章主要介紹了
使用Python,OpenCV线程化方式提高视频FPS(每秒帧数)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
使用Python,OpenCV處理視頻流時,獲得更高FPS(Frams Per Second)的“秘密”是將I / O(即從攝像機傳感器讀取幀)交給線程去處理;
讀取幀 I/O是阻塞型的,定義主線程處理讀到的幀,一個新的線程一直讀取幀,等主線程處理完,將新讀取到的幀接過來繼續(xù)處理;
I/O 密集型的用多線程 Threading
CPU 密集型的用多進程 MultiProcessing
不使用cv2.imshow(),相比普通的提升了 608/25~~ 2432%倍;
使用cv2.imshow() 會有1s中的延遲,對于非必要的顯示,去掉將能更好的發(fā)揮多線程提高視頻流的FPS。
# 使用線程化的方式提高FPS(每秒幀數(shù) Frams per second)
# python fps_demo.py
# python fps_deom.py -d 1# 導入必要的包
from __future__ import print_function
from imutils.video import WebcamVideoStream
from imutils.video import FPS
import argparse
import imutils
import cv2# 構(gòu)建命令行參數(shù)
# --num-frames 獲取FPS估算值而要循環(huán)播放的幀數(shù)
# --display 指標變量,指定是否應(yīng)用cv2.imshow()顯示幀
ap = argparse.ArgumentParser()
ap.add_argument("-n", "--num-frames", type=int, default=100,help="# of frames to loop over for FPS test")
ap.add_argument("-d", "--display", type=int, default=-1,help="Whether or not frames should be displayed")
args = vars(ap.parse_args())# 獲取視頻流指針,初始化FPS計數(shù)器
print("[INFO] sampling frames from webcam...")
stream = cv2.VideoCapture(0)
fps = FPS().start()# 循環(huán)遍歷一些幀
while fps._numFrames < args["num_frames"]:# 從流中獲取幀,resize 寬度為400(grabbed, frame) = stream.read()frame = imutils.resize(frame, width=400)# 檢查幀是否要展示if args["display"] > 0:cv2.imshow("Frame", frame)key = cv2.waitKey(1) & 0xFF# 更新FPS計數(shù)器fps.update()# 停止計數(shù)器
fps.stop()
print("[INFO] elasped time: {:.2f}".format(fps.elapsed()))
print("[INFO] approx. FPS: {:.2f}".format(fps.fps()))# 清理、釋放資源
stream.release()
cv2.destroyAllWindows()# 創(chuàng)建線程化的視頻流,允許攝像機傳感器預熱,并且啟動FPS計數(shù)器
print("[INFO] sampling THREADED frames from webcam...")
vs = WebcamVideoStream(src=0).start()
fps = FPS().start()# 使用線程循環(huán)處理每一幀
while fps._numFrames < args["num_frames"]:# 從線程化的視頻流中獲取幀,resize到寬度為400像素frame = vs.read()frame = imutils.resize(frame, width=400)# 檢查是否需要把幀通過cv2展示if args["display"] > 0:cv2.imshow("Frame", frame)key = cv2.waitKey(1) & 0xFF# 更新FPS計數(shù)器fps.update()# 停止計數(shù) 展示FPS的統(tǒng)計信息
fps.stop()
print("[INFO] elasped time: {:.2f}".format(fps.elapsed()))
print("[INFO] approx. FPS: {:.2f}".format(fps.fps()))
# 做一些清理工作 釋放攝像頭 關(guān)閉打開的窗口
cv2.destroyAllWindows()
vs.stop()
參考博客:
- https://www.pyimagesearch.com/2015/12/21/increasing-webcam-fps-with-python-and-opencv/
總結(jié)
以上是生活随笔為你收集整理的使用Python,OpenCV线程化方式提高视频FPS(每秒帧数)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用Python,OpenCV构建透明的
- 下一篇: 环境你我他下一句是什么呢?