0

I am new to python. I am trying open my webcam using the cv2 model. But I have errors like this I can't understand.

This is my python code: -

import cv2

video = cv2.VideoCapture(0)

while True:
    ret, frame = video.read()
    cv2.imshow("WindowFrame", frame)
    k = cv2.waitKey(1)
    if k == ord('q'):
        break
    video.release()
    cv2.destroyAllWindows()

This is my error:

enter image description here

Zenixo
  • 727
  • 1
  • 12
  • 36
  • You should use a debugger, and inspect `frame` after the call to `video.read()`. My bet is that you fail to get a valid frame from the VideoCapture / camera. – wohlstad Jun 04 '22 at 08:13
  • 3
    Line "video.release()" must be outside of while loop. You are destroying camera object you are trying to get image data. – unlut Jun 04 '22 at 08:13
  • please take the [tour] and review [ask]. you should have searched for this issue. there are answers. – Christoph Rackwitz Jun 04 '22 at 11:27

1 Answers1

2

Most of the time when you read !_src.empty() in your stacktrace it means that your frame, that should be a numpy tensor with numbers within it, is empty.

I suggest you to edit your code in the following way:

video = cv2.VideoCapture(0)

while True:
    if video.isOpened():
        ret, frame = video.read()
        if ret:
            cv2.imshow("WindowFrame", frame)
   
    if cv2.waitKey(1) == ord('q'):
        break

video.release()
cv2.destroyAllWindows()

So first you create the VideoCapture() object specifying the index of the camera

VideoCapture (int index) --> Open a camera for video capturing

Then, inside the while True you check if the camera object has already been initialized with isOpened()

isOpened () const --> Returns true if video capturing has been initialized already.

and if this is true then you can start reading frames from the camera. You do this with video.read() which returns a frame (in particular it reads the next frame) and a boolean value (we called it ret) that tells you if the frame is available or not. Thus, if ret == True, we show the frame with cv2.imshow("WindowFrame", frame).

Furthermore, inside your code there's an error. Since release() method closes the camera, you can not put it inside the while True loop

virtual void release () --> Closes video file or capturing device

Also cv2.destroyAllWindows() must stay outside the loop because otherwise you keep opening and closing the window which shows you the frame.

https://docs.opencv.org/3.4/d8/dfe/classcv_1_1VideoCapture.html