How To Increase Performance Of Opencv Cv2.videocapture(0).read()
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
Solution 1:
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
Post a Comment for "How To Increase Performance Of Opencv Cv2.videocapture(0).read()"