如何提高OpenCV cv2.VideoCapture(0).read()的性能 [英] How to increase performance of OpenCV cv2.VideoCapture(0).read()
问题描述
我正在具有intel核心i7-4510u的Kali linux上运行此脚本:
I'm running this script on Kali linux with intel core i7-4510u:
import cv2
from datetime import datetime
vid_cam = cv2.VideoCapture(0)
vid_cam.set(cv2.CAP_PROP_FPS, 25)
vid_cam.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
vid_cam.set(cv2.CAP_PROP_FRAME_HEIGHT, 360)
lastDate = datetime.now().second
fcount = 0
while(vid_cam.isOpened()):
if(datetime.now().second>lastDate):
lastDate = datetime.now().second
print("Fps: " + str(fcount))
fcount = 0
else:
fcount += 1
ret, image_frame = vid_cam.read()
cv2.imshow('frame', image_frame)
if cv2.waitKey(100) & 0xFF == ord('q'):
break
vid_cam.release()
cv2.destroyAllWindows()
如果我运行它,它会显示 Fps:4 .
如果我检查任务管理器我的CPU大约是2%.
问题出在哪里?
If I run it, it prints Fps: 4.
If I check Task Manager my cpu is at about 2%.
Where can the problem be?
推荐答案
一个潜在的原因可能是由于读取帧时的I/O延迟.由于cv2.VideoCapture().read()
是阻止操作,因此主程序将停顿,直到从相机设备读取帧并返回为止.一种提高性能的方法是生成另一个线程来处理 parallel 中的抓帧,而不是依赖单个线程来按 sequential 顺序抓帧.我们可以通过创建一个仅轮询新帧而主线程处理当前帧的新线程来提高性能.这是多线程框架的代码段.
One potential reason could because of I/O latency when reading frames. Since cv2.VideoCapture().read()
is a blocking operation, the main program is stalled until the frame is read from the camera device and returned. A method to improve performance would be to spawn another thread to handle grabbing frames in parallel instead of relying on a single thread to grab frames in sequential order. We can improve performance by creating a new thread that only polls for new frames while the main thread handles processing the current frame. Here's a snippet for multithreading frames.
from threading import Thread
import cv2, time
class VideoStreamWidget(object):
def __init__(self, src=0):
self.capture = cv2.VideoCapture(src)
# Start the thread to read frames from the video stream
self.thread = Thread(target=self.update, args=())
self.thread.daemon = True
self.thread.start()
def update(self):
# Read the next frame from the stream in a different thread
while True:
if self.capture.isOpened():
(self.status, self.frame) = self.capture.read()
time.sleep(.01)
def show_frame(self):
# Display frames in main program
cv2.imshow('frame', self.frame)
key = cv2.waitKey(1)
if key == ord('q'):
self.capture.release()
cv2.destroyAllWindows()
exit(1)
if __name__ == '__main__':
video_stream_widget = VideoStreamWidget()
while True:
try:
video_stream_widget.show_frame()
except AttributeError:
pass
这篇关于如何提高OpenCV cv2.VideoCapture(0).read()的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!