Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't open webcan or video file with python3 and opencv #8471

Closed
patrickelectric opened this issue Mar 28, 2017 · 25 comments
Closed

Can't open webcan or video file with python3 and opencv #8471

patrickelectric opened this issue Mar 28, 2017 · 25 comments
Labels
question (invalid tracker) ask questions and other "no action" items here: https://forum.opencv.org

Comments

@patrickelectric
Copy link

System information (version)
  • OpenCV => 3.2.0-1
  • Python OpenCV => 3.2.0.6
  • Python => 3.5.2
  • Operating System / Platform => ArchLinux 64bits
Detailed description

Can't open VideoCapture don't work with files and /dev/video

Steps to reproduce
import cv2
video = cv2.VideoCapture(0)
if video.isOpened():
    while True:
        check, frame = video.read()
        if check:
            cv2.imshow('Color Frame', frame)
            key = cv2.waitKey(50)
            if key == ord('q'):
                break
        else:
            print('Frame not available')
            print(video.isOpened())

The code don't show webcan or video file
Works with python2 ..

@patrickelectric
Copy link
Author

@alalek what is missing ?

@alalek
Copy link
Member

alalek commented Mar 28, 2017

Provided details is not enough to reproduce the issue.
Especially difference between Python2/3 looks strange.

What does "3.2.0-1" mean in OpenCV version? Is it Arch package version? AUR?

Please check correctness of loaded modules (cv2.__file__, cv2.__version__).
Also please provide OpenCV build configuration: cv2.getBuildInformation()

@mgruben
Copy link

mgruben commented May 21, 2017

Can't open videos or webcam:

System information (version)
opencv-python Version: 3.2.0.7
python Version: 3.6.1
Operating System / Platform: 4.10.11-1-ARCH Linux

Detailed description
VideoCapture doesn't work with files or with /dev/video

Steps to reproduce

# Fails with files, direct instantiation
import cv2
camera = cv2.VideoCapture("path/to/a/valid/video.mp4")
print(camera.isOpened()) # False
print(camera.read()) # (False, None)
# Fails with files, using .open() method
import cv2
camera = cv2.VideoCapture()
camera.open("path/to/a/valid/video.mp4") # False
print(camera.read()) # (False, None)
# Fails with webcam
import cv2
camera = cv2.VideoCapture(0)
print(camera.isOpened()) # False
print(camera.read()) # (False, None)

@dkloving
Copy link

Same issue with Python 3.6.0 under MacOS 10.12 Sierra.

@alalek
Copy link
Member

alalek commented May 21, 2017

This is still looks like an usage question. OpenCV requires 3rdparty libraries to work with cameras/videos. You need to install them properly before building OpenCV Python bindings.

opencv-python doesn't support them (almost all 3rdparty dependencies are turned off, because they are system dependent - system with minimal configuration is used during build).

For more information please refer to this question and others:

Q: Why I can't open video files on GNU/Linux distribution X or on macOS?

(https://pypi.python.org/pypi/opencv-python)

opencv-python binary package is not officially supported by OpenCV dev team, so we can't help here.

Usage questions should go to Users OpenCV Q/A forum: http://answers.opencv.org

@iiAnthony
Copy link

iiAnthony commented Aug 9, 2017

I have had a comparable issue on Ubuntu, using the pip install opencv-python process.
Solution used : I recompiled both ffmpeg and opencv 3.2 from sources on my station (following the install processes indicated on offical portals). Everything worked well, but I still was not able to open video from cv2.videocapture on python.

My solution has been to replace the cv2.so library provided by pypi with the one compiled from sources :
sudo cp opencv-3.2.0/build/lib/cv2.so /usr/local/lib/python2.7/dist-packages/cv2/

And I now can play videos with cv2, from my python scripts. Hope this will help those experiencing the same issue (I spent some time on trying to find a solution and never found this suggestion so ...).

@chutsu
Copy link

chutsu commented Sep 26, 2017

I did a similar thing to @iiAnthony where I compiled OpenCV 3.2.0 from source, double checking with CMake that it can find both python 2 and python 3

screenshot_2017-09-26_13-10-50

then I replaced the compiled .so dynamic library with the one that comes with opencv-python python3 package. The difference between my comment and @iiAnthony's is that his caters for Python2 users?

sudo cp <path to opencv source repo>/build/lib/python3/cv2.cpython-35m-x86_64-linux-gnu.so /usr/local/lib/python3.5/dist-packages/cv2/cv2.cpython-35m-x86_64-linux-gnu.so

Or better yet, just the ln command to symlink the built .so instead of copying, so that if you decide to compile OpenCV3 with different compilation flags you don't have to copy the library file over again.

Note: Your .so library file may have a different name to mine, but the idea is the same, compile your own opencv3 .so library file and replace the one that opencv-python comes with.

@alundiak
Copy link

alundiak commented Dec 6, 2017

Considering these 2 commands:

sudo cp build/lib/cv2.so /usr/local/lib/python2.7/dist-packages/cv2/
sudo cp build/lib/python3/cv2.cpython-35m-x86_64-linux-gnu.so /usr/local/lib/python3.5/dist-packages/cv2/cv2.cpython-35m-x86_64-linux-gnu.so

In my case opencv-3.3.1/build/lib doesn't have folder python nor python 2.7 nor python 3.6.
It contains lot of files with prefix libopencv_XYZ.so
And I'm on CentOS 7.0

UPD: ISSUE solved see my last comment here.

@chutsu
Copy link

chutsu commented Dec 6, 2017

That could be a number of things:

  1. CMake failed to find your python version, double check it is listed in the cmake .. stage (like in the screenshot I took in the previous post).
  2. You don't have the python development library (on debian based systems this corresponds to python-dev or python3-dev packages)
  3. Try and checkout a specific version of OpenCV instead of building master (i.e. git checkout 3.3.1)
  4. Maybe do a find . -name "cv2.*.so" to find if it is hidden somewhere? Though I am not convinced that building on CentOS would mean the .so file is at a different location during build.

I just downloaded and built the zipped OpenCV 3.3.1 in Ubuntu 16.04 and have found the cv2.so in the build/lib/python3 folder so you'll have to double check your environment.
screenshot_2017-12-06_11-15-20

@alundiak
Copy link

alundiak commented Dec 6, 2017

@chutsu thanks.
I tried master and simple download of 3.3.1, both behaves similarly, But for sure, smth wrong with Python. Researching again....

From $ opencv-3.3.1/build cmake ..

-- 
--   Python 2:
--     Interpreter:                 /usr/bin/python2.7 (ver 2.7.5)
-- 
--   Python 3:
--     Interpreter:                 /usr/bin/python3.4 (ver 3.4.5)
-- 
--   Python (for build):            /usr/bin/python2.7

I also see, that CmakeCache.txt file has predefined key/values, and I don't know how to tell cmake to know about my Python version.

I used this command:

which python3 => /usr/local/bin/python3

 build] $ cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -DPYTHON_EXECUTABLE:FILEPATH=/usr/local/bin/python3 ..

Regarding python-dev it's odd, because I installed Installing OpenCV from source https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_setup/py_setup_in_fedora/py_setup_in_fedora.html

In fact
yum install python-devel installed 2.7 version, and yum install python3-devel is not available, and ym install python34-devel is not the version I need. I use Python 3.6.

Doing double checking of all...

I dropped build folder and tried again. I tried:

build]$ cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -DPYTHON_EXECUTABLE:FILEPATH=/usr/local/bin/python3 -D PYTHON_EXECUTABLE:FILEPATH=/usr/local/bin/python3  PYTHON_EXECUTABLE:FILEPATH=/usr/local/bin/python3 ..

And now I have now folder build/lib/python3 but it's empty.

btw,

I have this

ls -la /usr/local/lib/python3.6/site-packages/cv2/
total 50196
drwxr-xr-x   4 root root      205 Dec  6 15:15 .
drwxr-xr-x. 53 poc  root     4096 Dec  6 12:21 ..
-rwxr-xr-x   1 root root 25676848 Dec  6 12:21 cv2.cpython-36m-x86_64-linux-gnu.so
-rwxr-xr-x   1 root root 25676848 Dec  6 15:15 cv2.cpython-36m-x86_64-linux-gnu.so_backup_dec_06
-rw-r--r--   1 root root      411 Dec  6 12:21 __init__.py
drwxr-xr-x   2 root root      140 Dec  6 12:21 .libs
-rw-r--r--   1 root root    29170 Dec  6 12:21 LICENSE-3RD-PARTY.txt
-rw-r--r--   1 root root     1097 Dec  6 12:21 LICENSE.txt
drwxr-xr-x   2 root root       37 Dec  6 12:21 __pycache__

and

ls /usr/lib/python
python2.7/ python3.4/ 

So should I create manually /usr/lib/python3.6 and copy *.so file to /usr/lib/python3.6/cv2.cpython-36m-x86_64-linux-gnu.so or /usr/lib/python3.6/cv2.so ?

or

sudo cp /usr/local/lib/python3.6/site-packages/cv2/cv2.cpython-36m-x86_64-linux-gnu.so /usr/lib/python3.6/site-packages/cv2/cv2.cpython-36m-x86_64-linux-gnu.so

?

@alundiak
Copy link

alundiak commented Dec 6, 2017

When I git checkout 3.3.1 && rm -rf build && mkdir build && cd build
Odd. Or I just don't know proper syntax of external params:

cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -DPYTHON_EXECUTABLE:FILEPATH=/usr/local/bin/python3 -D PYTHON_EXECUTABLE:FILEPATH=/usr/local/bin/python3  PYTHON_EXECUTABLE:FILEPATH=/usr/local/bin/python3 ..

In output I see trace of some version logic and error:

-- Found PythonInterp: /usr/local/bin/python3 (found suitable version "3.6.3", minimum required is "2.7") 
-- Found PythonInterp: /usr/bin/python3.4 (found suitable version "3.4.5", minimum required is "3.4") 
-- Found PythonLibs: /lib64/libpython3.4m.so (found suitable exact version "3.4.5") 
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/numpy/core/__init__.py", line 16, in <module>
    from . import multiarray
ImportError: cannot import name 'multiarray'


@alalek
Copy link
Member

alalek commented Dec 6, 2017

ImportError: cannot import name 'multiarray'

There is build/installation issue of numpy package on your machine.
Check issues about this message - for example, numpy/numpy#9047

@alalek
Copy link
Member

alalek commented Dec 6, 2017

BTW,

which python3 => /usr/local/bin/python3

You have custom python setup (without any information how you get it).

ls -la /usr/local/lib/python3.6/site-packages/cv2/

This file set is not generated by original OpenCV. You have installed something else from other sources.

@alundiak
Copy link

alundiak commented Dec 8, 2017

I recently solved issue for my use case.
So my old (BAD configs) were:

  • OpenCV 2.4.5 (after yum install opencv)
  • opencv_python 3.3.0.10 (after pip3 install opencv_python)

And in fact I have Assertion error, as it's described here: ageitgey/face_recognition#191 (comment)

Then, I compiled GOOD config - OpenCV from sources (git cloned and checked out 3.3.1 branch) and I had 3.3.1 version. But even with opencv 3.3.0.10 IT WAS NOT working, because

/usr/lib64/python3.4/site-packages/cv2/cv2.cpython-34m.so is 3.3.0

yes, opencv_python installs into ... lib64 ...

So, then there are 2 ways of resolving issue:

  1. replace of so file
sudo cp ~/opencv/build/lib/python3/cv2.cpython-34m.so /usr/lib64/python3.4/site-packages/cv2 
# meaning 3.3.1 version replaces 3.3.0 version of so file
  1. Remove opencv_python and don't use it later
sudo pip3 uninstall opencv_python

And later on import cv2 will import from /usr/lib/python3.4/site-packages/ (which is 3.3.1)

I did both, and my application was working in both cases. But still, I am not confident what is the best way.

PS.

So far I have 2 web cameras: built in and external via USB, and my python code can't access external. It always open built in. If someone know how to do it, please let me know. Here is piece of code:

print(cv2.__file__)
print(cv2.__version__)
# pprint(vars(cv2))

# https://docs.opencv.org/3.3.0/d8/dfe/classcv_1_1VideoCapture.html#a5d5f5dacb77bbebdcbfb341e3d4355c1
# to open default camera using default backend just pass 0. 
self.video = cv2.VideoCapture(0) # connects to built in camera in 640x480
# self.video = cv2.VideoCapture(1) # connects to built in camera, but in 1280x720

# self.video = cv2.VideoCapture(2) # should connect to 3nd installed camera - BUT NOT
# https://docs.opencv.org/3.3.0/d4/d15/group__videoio__flags__base.html#gga023786be1ee68a9105bf2e48c700294dacf10e9692c4166f74de62b7d00c377d0
# self.video = cv2.VideoCapture(cv2.CAP_FFMPEG) # connects to built in camera in 640x480

# TODO - HOW TO connect/switch to another web cam?

@netcoms
Copy link

netcoms commented Jan 20, 2018

In my case i simply un-installed and installed back opencv-python
Before re-installation i had opencv-python-3.3.0.10. after re-install i got a newer version opencv-python-3.4.0.12

  • pip3 uninstall opencv_python
  • pip3 install opencv_python --user

@skvark
Copy link
Member

skvark commented Jan 20, 2018

For future reference:

If you have installed either one of the precompiled distributions opencv-python or opencv-contrib-python from pip there are a few things to note if you are using Linux or macOS (Windows builds have had video support always):

  • versions < 3.3.1.11 are not compiled with FFmpeg (macOS, Linux) and V4L (webcam support, Linux)
  • versions >= 3.3.1.11 have been compiled with FFmpeg and V4L

Changelogs are available for every release at the opencv-python package repository https://github.com/skvark/opencv-python/releases.

@FilipBielickiPL
Copy link

I had this problem and couldn't find a solution, but on the web, it was working. My solution was almost funny - you can't have two streams. I turned off the web stream and then it was fine!

@bedssys
Copy link

bedssys commented Jul 21, 2019

I know people don't appreciate you @FilipBielickiPL, but that is certainly my problem, so thx! Basically, I have a configurable program (video vs webcam) and despite the WebcamVideoStream is not used during video mode, it'll disturb the way VideoCapture working.

@chutsu
Copy link

chutsu commented Jul 22, 2019

it would help if you can share a minimal reproducible example so that people can try out what the error is. Without example code we can't help you.

@bedssys
Copy link

bedssys commented Jul 28, 2019

@chutsu Why the thumbs down? I solved my error exactly like what @FilipBielickiPL did. Is that not clear enough?

@santhoshnumberone
Copy link

I have opencv running on cloud, This is not solving my issue. The file is present in the particular location but still unable to open the file.

For future reference:

If you have installed either one of the precompiled distributions opencv-python or opencv-contrib-python from pip there are a few things to note if you are using Linux or macOS (Windows builds have had video support always):

* versions < 3.3.1.11 are not compiled with FFmpeg (macOS, Linux) and V4L (webcam support, Linux)

* versions  >= 3.3.1.11 have been compiled with FFmpeg and V4L

Changelogs are available for every release at the opencv-python package repository https://github.com/skvark/opencv-python/releases.

@mhkmcp
Copy link

mhkmcp commented Jun 1, 2020

Where is @FilipBielickiPL 's solution. i can't find out

@lhaippp
Copy link

lhaippp commented Aug 19, 2020

I did a similar thing to @iiAnthony where I compiled OpenCV 3.2.0 from source, double checking with CMake that it can find both python 2 and python 3

screenshot_2017-09-26_13-10-50

then I replaced the compiled .so dynamic library with the one that comes with opencv-python python3 package. The difference between my comment and @iiAnthony's is that his caters for Python2 users?

sudo cp <path to opencv source repo>/build/lib/python3/cv2.cpython-35m-x86_64-linux-gnu.so /usr/local/lib/python3.5/dist-packages/cv2/cv2.cpython-35m-x86_64-linux-gnu.so

Or better yet, just the ln command to symlink the built .so instead of copying, so that if you decide to compile OpenCV3 with different compilation flags you don't have to copy the library file over again.

Note: Your .so library file may have a different name to mine, but the idea is the same, compile your own opencv3 .so library file and replace the one that opencv-python comes with.

Great answer!
It works for me

@YasPHP
Copy link

YasPHP commented Jun 12, 2021

Had same issue and found that meeting all these steps made it work on mac:

  • make sure it's cap = cv2.VideoCapture(0) if using default mac camera and if using more external x cameras, scale and include VideoCapture(1), 2, 3, etc.
  • don't forget to release the video source at the proper time by calling the release() method or else it will leave your camera unusable and you'll have to either restart your mac or reset the system entirely to recover the camera with sudo killall VDCAssistant
  • running main program directly on terminal vs pycharm run worked
  • make sure to close webcam window at end with
    cv2.destroyAllWindows() cap.release() break
  • have opencv-contrib-python properly installed via your requirements.txt

These are just the basics you could be missing and leading it to error or it could be something else but this is a good checklist for a first step. Good luck!

@MoussaBessou
Copy link

it works for me
just
authorize camera on your compiler or browser

Screenshot 2021-12-09 114639

if didn't work try open your camera and make sure its working before running your code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question (invalid tracker) ask questions and other "no action" items here: https://forum.opencv.org
Projects
None yet
Development

No branches or pull requests