0

I'm learning OpenCV using python. I'm trying to run the following code to capture snapshots using OpenCV. I'm able to run the script correctly through Anaconda spyder however getting error when I'm using command prompt. I referred to questions on stackoverflow Assertion failure : size.width>0 && size.height>0 in function imshow However, here I'm not loading any external image. My code is:

import cv2

videoObject = cv2.VideoCapture(0)  #0== integrated webcam 1==External webcam
i=0
while True:
    check, frame = videoObject.read()
    cv2.imshow("Webcam Shot",frame)
    key = cv2.waitKey(1)
    # 'c' button to capture the image
    # the 'q' button is set as the quit
    if key == ord('c'):
        cv2.imwrite('Image_'+str(i)+'.png', frame)
        i+=1
        print('Image saved')
    if key == ord('q'):
        break

# shutdown the camera
videoObject.release()
cv2.destroyAllWindows()

Error I'm getting:

cv2.error: OpenCV(4.3.0) C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp:376: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'

Please help.

1 Answers1

0

https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html

From the tutorial link:

Sometimes, cap may not have initialized the capture. In that case, this code shows error. You can check whether it is initialized or not by the method cap.isOpened(). If it is True, OK. Otherwise open it using cap.open().

cap.read() returns a bool (True/False). If frame is read correctly, it will be True. So you can check end of the video by checking this return value.

From the above, here is code that would use the result from read, before calling imshow.

import cv2
videoObject = cv2.VideoCapture(0)  #0== integrated webcam 1==External webcam
i=0
while True:
    check, frame = videoObject.read()
    if not check:
      continue
    cv2.imshow("Webcam Shot",frame)
    ...
darless
  • 101
  • 3
  • I tried but getting same error and even warnings: **[ WARN:1] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (386) `anonymous-namespace'::SourceReaderCB::OnReadSample videoio(MSMF): async ReadSample() call is failed with error status: -1072875772 [ WARN:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (906) CvCapture_MSMF::grabFrame videoio(MSMF): can't grab frame. Error: -1072875772** – Mavis_Ackerman Jul 28 '20 at 22:47