我尝试使用网络摄像头在 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()
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()
我遇到的错误:
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'
问题是您在循环内释放了
cap
实例。您将无法从第二次迭代中读取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