Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCv error can't open camera through video capture

I was using my cam through opencv and suddenly after restarting I ran my code it shows below error:

[ WARN:0] global /io/opencv/modules/videoio/src/cap_v4l.cpp (802) open VIDEOIO ERROR: V4L: can't open camera by index 0
Traceback (most recent call last):
  File "test.py", line 20, in <module>
    retval, buffer_img = cv2.imencode('.jpg', frame)
cv2.error: OpenCV(4.1.2) /io/opencv/modules/imgcodecs/src/loadsave.cpp:877: error: (-215:Assertion failed) !image.empty() in function 'imencode'
cap = cv2.VideoCapture(0)  # here it throws an error


import json
while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    retval, buffer_img = cv2.imencode('.jpg', frame)

    resdata = base64.b64encode(buffer_img)

    resdata = "data:image/png;base64,"+ str(resdata.decode("utf-8"))
    PARAMS = {'image': resdata}

    # Our operations on the frame come here
    #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Display the resulting frame
    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

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

I also tried with cap = cv2.VideoCapture(1) but then it shows can't find camera

How can I fix this issue?

like image 953
Nabeel Ayub Avatar asked Dec 17 '19 09:12

Nabeel Ayub


People also ask

Can OpenCV capture video?

Capture Video from CameraOpenCV allows a straightforward interface to capture live stream with the camera (webcam). It converts video into grayscale and display it. We need to create a VideoCapture object to capture a video. It accepts either the device index or the name of a video file.


2 Answers

I got the same error. Try changing 0 to -1

cap = cv2.VideoCapture(-1)

This solved the issue.

like image 91
abey Avatar answered Nov 15 '22 18:11

abey


I got the same problem when I created more than one instance of the cv2.VideoCapture(0). So check if your code contains multiple initializations or sections which call cv2.VideoCapture(0) more than once. I was facing this problem while running the flask server in debug mode because it called cv2.VideoCapture(0) twice.

import cv2
cap = cv2.VideoCapture(0)
cap2 = cv2.VideoCapture(0)
while True:

    ret, frame = cap.read()
    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

Error:

python3 debugCamera.py 
[ WARN:0] global /io/opencv/modules/videoio/src/cap_v4l.cpp (887) open VIDEOIO(V4L2:/dev/video0): can't open camera by index
like image 28
ankit Avatar answered Nov 15 '22 18:11

ankit