Max Max - 1 year ago 160
Python Question

webcam does not work in pip version of opencv-python and opencv-contrib-python

I've been facing a problem with the webcam in opencv in python using anaconda.

The problem is the following:
I cannot open the webcam if opencv is installed via any of the two:

pip install opencv-python
(available 3.1,3.2,3.3), or

pip install opencv-contrib-python
(available 3.2,3.3)

However it will work if and only if I install it from

conda install opencv
(available opencv 3.1)

However, some functionality of opencv is only given in newer versions or in the contrib version currently not available via conda.
Does anyone have an idea why the pip versions won't work?

Here the code used to use the webcam:
(Yes I tried various variations suggested

import cv2
print (cv2.__version__)
camera = cv2.VideoCapture(0) #tried -1,0,1,...

if camera.isOpened(): # isOpened is always False for pip version
print ("successfully opened Webcam")
print ("Webcam error")
success,img = # success is always False for pip version
print (success,img.shape)

I tried various webcams, and various alternations to the code as suggested on the web.

Answer Source

The underlying libraries are not linked in the pip package. This was a design choice for the package to be more universally installable.

From the Python Package Index (PyPI) documentation for the opencv-python package:

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

A: OpenCV video I/O depends heavily on FFmpeg. Manylinux and macOS OpenCV binaries are not compiled against it. The purpose of these packages is to provide as easy as possible installation experience for OpenCV Python bindings and they should work directly out-of-the-box. Adding FFmpeg as an additional dependency without a “universal” FFmpeg build (e.g. LGPL licensed build like in the Windows wheels) the goal is considerably harder to achieve. This might change in the future.

You could compile OpenCV from source if you want to use the newer versions and not have these problems. There's a number of such tutorials. OpenCV has a Python specific tutorial for compiling on Windows and on Fedora. Additionally, PyImageSearch has a very popular number of blog posts on compiling OpenCV from source on macOS and Linux: Ubuntu 16.04, Ubuntu 14.04, macOS, macOS via Homebrew (with an accompanying troubleshooting article), along with a number of other Linux flavors (e.g. Raspbian) and posts for older Python versions; just search the web if that doesn't cover you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download