Reputation: 11
I just tried to make simple computer vision code that copied from some website using python 3.6.6 and openCV4.1.0 but there's an error,what is my fault?
in every "cv2.imshow" there's always has some error
import cv2
cam = cv2.VideoCapture(1)
cv2.namedWindow("test")
img_counter = 0
while True:
ret, frame = cam.read()
cv2.imshow("test", frame)
if not ret:
break
k = cv2.waitKey(1)
if k%256 == 27:
# ESC pressed
print("Escape hit, closing...")
break
elif k%256 == 32:
# SPACE pressed
img_name = "opencv_frame_{}.png".format(img_counter)
cv2.imwrite(img_name, frame)
print("{} written!".format(img_name))
img_counter += 1
cam.release()
cv2.destroyAllWindows()
it should compile as webcam view on my laptop. but this is what i got:
Exception has occurred: error
OpenCV(4.1.0) ../modules/highgui/src/window.cpp:352: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'imshow'
Upvotes: 0
Views: 2880
Reputation: 6090
This part of your error
size.width>0 && size.height>0
tells you that either the width or the height of your image is zero. This means thatframe
is not valid and can not be shown. Check that your frame
is valid before showing.
The good thing is that cam.read()
already tells you if the reading was successful as can be read in the documentation (cap
is equal to your cam
):
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.
The actual reading and showing should look like this:
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True: # frame is valid
# show the frame
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
Full Example using your code:
import cv2
cam = cv2.VideoCapture(0) # adjusted to the first device '0'
img_counter = 0
while(True):
ret, frame = cam.read()
if ret: # frame is valid
# show the frame
cv2.imshow('frame',frame)
key = cv2.waitKey(1)
if key & 0xFF == ord('s'): # s for saving
print("S hit, saving...")
img_name = "opencv_frame_{}.png".format(img_counter)
cv2.imwrite(img_name, frame)
print("{} written!".format(img_name))
img_counter += 1
if key & 0xFF == ord('q'): # q for quitting
print("Q hit, closing...")
break
else:
print("Frame not valid")
cam.release()
cv2.destroyAllWindows()
If all your frames are invalid (video device not working) it will print
'Frame not valid'
the whole time to show you that something is wrong.
I adjusted the parameter of VideoCapture
to use the first video device of your system (counting starts at 0 not 1).
The Example uses 's' for saving and 'q' for quitting.
Upvotes: 0
Reputation: 3233
The key here is to remember that whenever you perform a cv2.imshow()
operation inside a while True
cycle, the following structure has to be used:
while True:
r, f = cam.read()
if r:
cv2.imshow("f", f)
if cv2.waitkey(1) & 0xff == ord('q'):
break
Then you can build all your application logic around this basic structure.
Upvotes: 2