How to increase performance of OpenCV cv2.VideoCapture(0).read()

前端 未结 1 1271
北恋
北恋 2021-01-14 05:55

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_P         


        
相关标签:
1条回答
  • 2021-01-14 06:42

    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
    
    0 讨论(0)
提交回复
热议问题