Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV input delay in capturing frames

Tags:

python

opencv

I have written a code to enable capturing images from webcam feed using OpenCV. However there is an input delay whenever I press the key to capture my frame. There is no delay when I use it to quit, but there a significant delay when I use capture. I measured this by printing a statement inside both the cases, on pressing c the statement takes a delay before printing. The problem seems to me something like...the camera resources are being used and not freed up in time for the next key press or something like that....but not sure.

import cv2 as cv
import numpy as np
import glob
import matplotlib.pyplot as plt

cap = cv.VideoCapture(1)

img_counter = 0

while True:
    ret, frame = cap.read()
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
    # cv.imshow('frame',frame)
    cv.imshow('gray', gray)
    if not ret:
        break

    if cv.waitKey(1) & 0xFF == ord('q'):
        print('helloq')
        break

    elif cv.waitKey(1) & 0xFF == ord('c'):
        print('hello{}'.format(img_counter))
        img_name = "opencv_frame_{}.png".format(img_counter)
        cv.imwrite(img_name, gray)
        img_counter += 1

I am using an external web camera and cv2.__version__ = 3.4.2`

like image 566
PyWalker2797 Avatar asked Jun 29 '26 14:06

PyWalker2797


1 Answers

Solved your issue, it seems like its caused by your key check.

You should not call waitKey(1) more than once. It causes lag.

Try this solution:

cap = cv.VideoCapture(0)

img_counter = 0

while True:
    ret, frame = cap.read()
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
    # cv.imshow('frame',frame)
    cv.imshow('gray', gray)
    if not ret:
        break

    key = cv.waitKey(1)

    if key==ord('c'):
        print('img{}'.format(img_counter))
        img_name = "opencv_frame_{}.png".format(img_counter)
        cv.imwrite(img_name, gray)
        img_counter += 1
        print("Succesfully saved!")

    if key==ord('q'):
        print('Closing cam...')
        break

# When everything done, release the capture
cap.release()
cv.destroyAllWindows()
like image 115
isydmr Avatar answered Jul 02 '26 12:07

isydmr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!