opencv python3 API open camera failed
jacknlliu opened this issue · comments
Using these codes with python3 API will open camera failed.
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())
But python2 works.
The package opencv-python
did not compile against FFmpeg, V4L(webcam support, Linux) and other 3rd parties driver for video/camera, so we can't read video from the camera directly with opencv-python
.
Solution
Recompile opencv following Installing OpenCV from source , and then copy following file to the installed path
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
NOTE: this method should reserve the opencv source repo, and keep the relative path to cv2.cpython-35m-x86_64-linux-gnu.so
. If we build it in docker, we should remove the opencv-python
package by pip3
, then installing opencv from source, or we should copy the opencv source to the docker image and link to the system path.
Reference
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 no file like cv2.cpython-34m.so
UPD: Issue solved. See my comments here:
opencv/opencv#8471 (comment)
Actually, we also use OpenCV 3.3.1 from source but work with Ubuntu 16.04. I think you may have unsuccessfully compiled. Did you have similar output from cmake
config options with Configuring and Installing. Some warnings also may show some dependent libraries missing, then you will not get the python support.
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 —— From opencv/opencv#8471 (comment)