pythonopencvruntime-error

OpenCV error when trying to capture frame every seconds


I am trying to capture an image every 5 seconds in Opencv using my webcam however I am getting an error whenever I try.

Python Code:

def imgcap():
    cap = cv2.VideoCapture(0)
    framerate = cap.get(5)
    x=1

    while(True):
        # Capture frame-by-frame
        ret, frame = cap.read()
        cap.release()
        # Our operations on the frame come here

        filename = 'Captures/capture' +  str(int(x)) + ".png"
        x=x+1
        cv2.imwrite(filename, frame)
        time.sleep(5)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    # When everything done, release the capture
    cap.release()
    cv2.destroyAllWindows()

imgcap()

Error I am Getting:

  File "vision.py", line 30, in <module>
    imgcap()
  File "vision.py", line 21, in imgcap
    cv2.imwrite(filename, frame)
cv2.error: OpenCV(4.5.1) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-oduouqig\opencv\modules\imgcodecs\src\loadsave.cpp:753: error: (-215:Assertion failed) !_img.empty() in function 'cv::imwrite'

Solution

  • The problem is you release the cap instance inside the loop. You wouldn't be able to read from cap from the 2nd iteration:

    while(True):
        # Capture frame-by-frame
        ret, frame = cap.read()
        
        # comment this
        # cap.release()
        # Our operations on the frame come here
    
        filename = 'Captures/capture' +  str(int(x)) + ".png"
        #... other code