Skip to content

Instantly share code, notes, and snippets.

@royshil
Created March 4, 2016 18:59
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save royshil/0f674c96281b686a9a62 to your computer and use it in GitHub Desktop.
Save royshil/0f674c96281b686a9a62 to your computer and use it in GitHub Desktop.
A way to set V4L2 camera params for OpenCV, when cv2.VideoCapture doesn't work. This requires the python-v42lcapture module (https://github.com/gebart/python-v4l2capture)
#!/usr/bin/env python
import numpy as np
import cv2
import os
import v4l2capture
import select
if __name__ == '__main__':
#cap = cv2.VideoCapture(0)
#cap.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, 1920) # <-- this doesn't work. OpenCV tries to set VIDIO_S_CROP instead of the frame format
#cap.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, 1080)
# The following is from: https://github.com/gebart/python-v4l2capture
# Open the video device.
video = v4l2capture.Video_device("/dev/video0")
# Suggest an image size to the device. The device may choose and
# return another size if it doesn't support the suggested one.
size_x, size_y = video.set_format(1920, 1080, fourcc='MJPG')
print "device chose {0}x{1} res".format(size_x, size_y)
# Create a buffer to store image data in. This must be done before
# calling 'start' if v4l2capture is compiled with libv4l2. Otherwise
# raises IOError.
video.create_buffers(30)
# Send the buffer to the device. Some devices require this to be done
# before calling 'start'.
video.queue_all_buffers()
# Start the device. This lights the LED if it's a camera that has one.
print "start capture"
video.start()
while(True):
#We used to do the following, but it doesn't work :(
#ret, frame = cap.read()
#Instead...
# Wait for the device to fill the buffer.
select.select((video,), (), ())
# The rest is easy :-)
image_data = video.read_and_queue()
print "decode"
frame = cv2.imdecode(np.frombuffer(image_data, dtype=np.uint8), cv2.cv.CV_LOAD_IMAGE_COLOR)
cv2.imshow('frame', frame)
key = cv2.waitKey(1)
if key & 0xFF == ord('q'):
break
#cap.release()
video.close()
cv2.destroyAllWindows()
@meirm
Copy link

meirm commented Oct 14, 2016

I had to change the code with the following lines
fourcc = cv2.cv.CV_FOURCC(*'MJPG')
size_x, size_y = video.set_format(640, 480, fourcc)

This is the output I get:
device chose 640x480 res
start capture
decode
OpenCV Error: Assertion failed (size.width>0 && size.height>0) in imshow, file /build/opencv-SviWsf/opencv-2.4.9.1+dfsg/modules/highgui/src/window.cpp, line 269
Traceback (most recent call last):
File "v4l2cap.py", line 56, in
cv2.imshow('frame', frame)
cv2.error: /build/opencv-SviWsf/opencv-2.4.9.1+dfsg/modules/highgui/src/window.cpp:269: error: (-215) size.width>0 && size.height>0 in function imshow

@HassankSalim
Copy link

mine is stuck here, webcam is on but no image

device chose 640x480 res
start capture

@ronbarak
Copy link

Trying to install v4l2capture (on Ubuntu 16.04, Python 3.5), I get the errors below, and the installation fails.
Any suggestions how to get v4l2capture to install?

$ sudo pip3 install v4l2capture --upgrade
The directory '/home/openstack/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/openstack/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting v4l2capture
  Downloading v4l2capture-12.tar.gz
Installing collected packages: v4l2capture
  Running setup.py install for v4l2capture ... error
    Complete output from command /usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-ombg9f55/v4l2capture/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-asoxf0ri-record/install-record.txt --single-version-externally-managed --compile:
    running install
    running build
    running build_ext
    building 'v4l2capture' extension
    creating build
    creating build/temp.linux-x86_64-3.5
    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/usr/include/python3.5m -c v4l2capture.c -o build/temp.linux-x86_64-3.5/v4l2capture.o
    v4l2capture.c: In function ‘Video_device_dealloc’:
    v4l2capture.c:116:7: error: ‘Video_device {aka struct <anonymous>}’ has no member named ‘ob_type’
       self->ob_type->tp_free((PyObject *)self);
           ^
    v4l2capture.c: In function ‘Video_device_fileno’:
    v4l2capture.c:161:10: warning: implicit declaration of function ‘PyInt_FromLong’ [-Wimplicit-function-declaration]
       return PyInt_FromLong(self->fd);
              ^
    v4l2capture.c:161:10: warning: return makes pointer from integer without a cast [-Wint-conversion]
    v4l2capture.c: In function ‘Video_device_get_info’:
    v4l2capture.c:187:18: warning: implicit declaration of function ‘PyString_FromString’ [-Wimplicit-function-declaration]
        PyObject *s = PyString_FromString(capability->name);
                      ^
    v4l2capture.c:187:18: warning: initialization makes pointer from integer without a cast [-Wint-conversion]
    v4l2capture.c: In function ‘Video_device_read_internal’:
    v4l2capture.c:381:22: warning: implicit declaration of function ‘PyString_FromStringAndSize’ [-Wimplicit-function-declaration]
       PyObject *result = PyString_FromStringAndSize(
                          ^
    v4l2capture.c:381:22: warning: initialization makes pointer from integer without a cast [-Wint-conversion]
    In file included from /usr/include/python3.5m/pytime.h:6:0,
                     from /usr/include/python3.5m/Python.h:65,
                     from v4l2capture.c:14:
    v4l2capture.c: At top level:
    /usr/include/python3.5m/object.h:86:5: warning: missing braces around initializer [-Wmissing-braces]
         { _PyObject_EXTRA_INIT              \
         ^
    v4l2capture.c:500:3: note: in expansion of macro ‘PyObject_HEAD_INIT’
       PyObject_HEAD_INIT(NULL)
       ^
    /usr/include/python3.5m/object.h:86:5: note: (near initialization for ‘Video_device_type.ob_base’)
         { _PyObject_EXTRA_INIT              \
         ^
    v4l2capture.c:500:3: note: in expansion of macro ‘PyObject_HEAD_INIT’
       PyObject_HEAD_INIT(NULL)
       ^
    v4l2capture.c:501:10: warning: initialization makes integer from pointer without a cast [-Wint-conversion]
           0, "v4l2capture.Video_device", sizeof(Video_device), 0,
              ^
    v4l2capture.c:501:10: note: (near initialization for ‘Video_device_type.tp_basicsize’)
    v4l2capture.c:502:7: warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]
           (destructor)Video_device_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
           ^
    v4l2capture.c:502:7: note: (near initialization for ‘Video_device_type.tp_print’)
    In file included from /usr/include/python3.5m/pytime.h:6:0,
                     from /usr/include/python3.5m/Python.h:65,
                     from v4l2capture.c:14:
    /usr/include/python3.5m/object.h:651:29: warning: initialization makes pointer from integer without a cast [-Wint-conversion]
     #define Py_TPFLAGS_DEFAULT  ( \
                                 ^
    v4l2capture.c:503:10: note: in expansion of macro ‘Py_TPFLAGS_DEFAULT’
           0, Py_TPFLAGS_DEFAULT, "Video_device(path)\n\nOpens the video device at "
              ^
    /usr/include/python3.5m/object.h:651:29: note: (near initialization for ‘Video_device_type.tp_doc’)
     #define Py_TPFLAGS_DEFAULT  ( \
                                 ^
    v4l2capture.c:503:10: note: in expansion of macro ‘Py_TPFLAGS_DEFAULT’
           0, Py_TPFLAGS_DEFAULT, "Video_device(path)\n\nOpens the video device at "
              ^
    v4l2capture.c:503:30: warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]
           0, Py_TPFLAGS_DEFAULT, "Video_device(path)\n\nOpens the video device at "
                                  ^
    v4l2capture.c:503:30: note: (near initialization for ‘Video_device_type.tp_traverse’)
    v4l2capture.c:506:16: warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]
           0, 0, 0, Video_device_methods, 0, 0, 0, 0, 0, 0, 0,
                    ^
    v4l2capture.c:506:16: note: (near initialization for ‘Video_device_type.tp_members’)
    v4l2capture.c:507:7: warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]
           (initproc)Video_device_init
           ^
    v4l2capture.c:507:7: note: (near initialization for ‘Video_device_type.tp_alloc’)
    v4l2capture.c:499:41: warning: missing braces around initializer [-Wmissing-braces]
     static PyTypeObject Video_device_type = {
                                             ^
    v4l2capture.c:499:41: note: (near initialization for ‘Video_device_type’)
    v4l2capture.c: In function ‘initv4l2capture’:
    v4l2capture.c:520:7: warning: ‘return’ with no value, in function returning non-void
           return;
           ^
    v4l2capture.c:523:22: warning: implicit declaration of function ‘Py_InitModule3’ [-Wimplicit-function-declaration]
       PyObject *module = Py_InitModule3("v4l2capture", module_methods,
                          ^
    v4l2capture.c:523:22: warning: initialization makes pointer from integer without a cast [-Wint-conversion]
    v4l2capture.c:528:7: warning: ‘return’ with no value, in function returning non-void
           return;
           ^
    error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

    ----------------------------------------
Command "/usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-ombg9f55/v4l2capture/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-asoxf0ri-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-ombg9f55/v4l2capture/

@wendal
Copy link

wendal commented May 4, 2017

@ronbarak

apt-get install python-dev

@BassyKuo
Copy link

@ronbarak
Try to install libudev-dev, or other "udev" packages. (use apt search udev to check)
I have same error and I install this package to fix it.

@schnapper79
Copy link

I know this is quite old stuff.... and still works like a charm... thanks...

@zimenglan-sysu-512
Copy link

hi

i met libv4l2: error dequeuing buf: Broken pipe, when run the code.

anyone have encoutered it before?

@lrob
Copy link

lrob commented Sep 3, 2018

In order to make it working with the last version of OpenCV I changed the row
frame = cv2.imdecode(np.frombuffer(image_data, dtype=np.uint8), cv2.cv.CV_LOAD_IMAGE_COLOR)
to
frame = cv2.imdecode(np.frombuffer(image_data, dtype=np.uint8), cv2.IMREAD_COLOR)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment