尝试每秒捕获帧时出现 OpenCV 错误

OpenCV error when trying to capture frame every seconds

我尝试使用我的网络摄像头在 Opencv 中每 5 秒捕获一次图像,但是每次尝试时都会出现错误。

Python代码:

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

    while(True):
        # Capture frame-by-frame
        ret, frame = cap.read()
        if ret:
            # 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
        else:
            print("Ret False")

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

imgcap()

imgcap()

我得到的错误:

  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\pip-req-build-oduouqig\opencv\modules\imgcodecs\src\loadsave.cpp:753: error: (-215:Assertion failed) !_img.empty() in function 'cv::imwrite'

问题是您在循环内释放了 cap 实例。您将无法从第 2 次迭代中读取 cap

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