[Python] cv2 read from webcam lags when window not focused

Discussão em 'Python' iniciado por Stack, Setembro 17, 2024.

  1. Stack

    Stack Membro Participativo

    I've been having a lot of trouble with webcam recording due to videos dropping from 25/30 fps to 10 fps, which speeds the video dramatically.

    After attempting so many different things, it turns out the culprit (on MS Windows 10/11) is simply to focus the window, when the window that displays the recordings with cv2 imshow() (the one with waitkey attached) is being focused, webcams take 0.01-0.03 seconds to get a new frame with cap.read(), however when the window is not focused the time goes to 0.07-0.11 seconds, and the fps drop to 10

    You can see a video of this behaviour here:

    https://www.youtube.com/watch?v=lGSksrtMZfA

    The simplified code looked like this:

    while True:
    camlog.debug("camera loop start %d, %s" % (framecount, str(datetime.now())))
    stream_ok, frame = webcam.read()
    if pipeargs.source2 is not None:
    stream_ok2, frame2 = webcam2.read()
    else:
    stream_ok2 = True
    camlog.debug("camera read %s, %s" % (stream_ok, str(datetime.now())))
    if stream_ok and stream_ok2:
    framecount += 1
    camlog.debug("image show %s" % str(datetime.now()))
    cv2.imshow(self.tablename, frame)
    video.write(frame)
    if cv2.waitKey(1) & 0xFF == 27: break


    So the question is: can I give the window a priority similar to being on focus on windows while it is minimized?

    EDIT: The problem is not exactly that the window is not on the front for higher priority, but rather that it loses priority when it is minimized, so a work around is to not have any window (no imshow, no waitkey), so the recording is at 30FPS

    I tried to show the image on a different thread that the camera comunicates with a FIFO pipe, but the problem repeats itself, windows lowers the priority of the just-camera thread when the other thread is minimized as well, perhaps because they share same class space, or the cv2 module, not sure yet

    Continue reading...

Compartilhe esta Página