Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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?

your got error cause -1 index. -1 index meaning last element of list. i recommend you. you may use 0 if you have webcam. – MD. Saiful Islam Nov 17, 2020 at 3:12

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
                You try to open a camera two times. When a hardware ingress a work then it don't allow outer command at same time .
– MD. Saiful Islam
                Nov 17, 2020 at 3:04

Most likely a permission issue on /dev/video0.

Check if you are part of "video" group.
id -a

if you don't see video in your group list add sudo usermod -a -G video

for Ubuntu users:(20.04)
sudo usermod -a -G video $LOGNAME

Logout and log back in and try it.

It worked for me to run a X application inside docker container. I have also needed to install v4l-utils. Just like this tutorial. – Diego Medeiros Aug 20, 2021 at 21:15 I am using a rdp user for the xrdp server on the raspberry 4, and giving permissions was the solution, Thanks. For the pi, must be sudo usermod -a -G video $LOGNAME – Jaume Dec 27, 2022 at 0:07

I've encountered the same issue and attempted several methods like cv2.VideoCapture(-1) or cv2.VideoCapture(1) but without much success.

I succeeded after reading this article and disabling debug-mode

I found a solution in https://github.com/opencv/opencv/issues/19527 where the video capture is inside the function instead of outside. That worked for me (ubuntu)

def frame_generation():
camera = cv2.VideoCapture(0) #resolved, correct position
while(True):
                Didn't solve this problem for me, but this is much neater and more logical than leaving it within the loop. So I've done it anyway,
– Hugh Barnard
                Feb 1 at 13:09

I will not go to that part What you are trying to do, here is just a block of code that can open your camera every time you run it,

python: 3.7.3

OpenCV: 4.1.0

import cv2
cap = 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()
                cap = cv2.VideoCapture(0), its not working,its giving me the error I mentioned in the beginning
– Nabeel Ayub
                Dec 17, 2019 at 9:57
                what kind of camera are you using? Laptop default camera(0), external camera(1-....), just change the value 0-... and see what happen.
– Sohel Reza
                Dec 17, 2019 at 10:01
                just change it 0 to 1 or 2 or 3 , if it is not work then problem maybe you python or openCV version. you can reinstall it and see what happen, just a quick suggestion
– Sohel Reza
                Dec 17, 2019 at 10:04
                did all sort of things still can't fix,I think there is ubuntu compatibility issue otherwise it should run.
– Nabeel Ayub
                Dec 17, 2019 at 10:13

I also had the same problem. Just changed it to 1 and it was perfectly working. I guess it's related to the number of camera devices you have used.

For example, I guess I have Iruin external camera as my first option which I didn't connect this time.

Here is the error and corrected code.

global /tmp/pip-req-build-f51eratu/opencv/modules/videoio/src/cap_v4l.cpp (890) open VIDEOIO(V4L2:/dev/video0): can't open camera by index

Code to change:

vid = cv2.VideoCapture(1)

The OP appears to be operating on a Raspberry PI. Raspberry is moving to a new system to manage cameras, so when the user upgrades the OS via sudo apt-get upgrade the camera system gets the new library and the legacy camera system is disabled. To enable the legacy camera system again, try

sudo raspi-config

Then select

3 Interface Options    Configure connections to peripherals

then select

I1 Legacy Camera Enable/disable legacy camera support

and follow the directions to enable and then reboot.

Of course, this patch will only work for so long, as the legacy system has been deprecated.

I don't think answers to software problems should include hardware/manual solutions. I might be as helpful as "restart your program" when you stumble upon an error somewhere – quqa123 Apr 14 at 11:29

I've also had this problem on Ubuntu

I've solved this by these comands

sudo adduser username video sudo usermod -a -G video username

username - it is the name of your device

than write

id -a

and copy index from ()

for me it is 1000

so than just write:

camera = cv2.VideoCapture(1000)

Welcome to Stack Overflow. Are you sure this answers the question at the top of the page? It doesn't appear to be related. Please read How to Answer. – Chris Dec 8, 2021 at 21:12

Don't know if this is still an issue. In my case, I was getting the same error until I unplugged and plugged the usb camera. Even if I reboot, the error happened.

It's similar to someone said: my camera was already been captured. The problem is that it was not used by my script, so it was hard to identify.

A few days before the issue, I installed the motion library, but just to test something and I didn't use it anymore. The motion starts at boot, so the camera was being captured by the service. That's why only the unplug-plug worked.

I uninstalled the library, and the error was gone.

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center. – user11717481 Oct 24, 2022 at 13:41

This issue is due to the interruption. Try to end the execution with the key 'q' for example, don't close the window suddenly.

I solved the same issue by opening terminal again and execute the same script again.

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.