Open images from USB camera on linux using V4L2 with OpenCV
I have always been using OpenCV’s VideoCapture API to capture images from webcam or USB cameras. OpenCV supports V4L2 and I wanted to use something other than OpenCV’s VideoCapture API so I started digging up about v4l2 and got few links using and few examples using which I successfully wrote a small code to grab an image using V4L2 and convert it to OpenCV’s Mat structure and display the image.
What is V4L2?
V4L2 is the second version of Video For Linux which is a video capturing API for Linux. Hereyou can find amazing documentation about the API. So it gives you a very easy inteface to use it with C, C++ and Python. I haven’t tried Python bindings yet.
How To Use V4L2 API?
I started reading documentation but didn’t really understand much until I found this example. The code had some issues and wasn’t working properly. But I just copied it and tried understanding it. So this is my understanding of the code.
Step 1: Open the Capture Device.
In Linux, default capture devide is generally /dev/video0, but if you’re using USB webcams, the index will vary accordingly.
int fd;
fd = open("/dev/video0", O_RDWR);
if (fd == -1)
{
// couldn't find capture device
perror("Opening Video device");
return 1;
}
Step 2: Query the Capture
So, basically you check if the capture is available or not. V4L2 doesn’t support some cameras so it would throw an error here. We need to use v4l2_capability structure and VIDIOC_QUERYCAPto query the capture. Read More here.
struct v4l2_capability caps = {0};
if (-1 == xioctl(fd, VIDIOC_QUERYCAP, &caps))
{
perror("Querying Capabilites");
return 1;
}
Here xioctl is a wrapper function over ioctl. ioctl() is a function to manipulate device parameters of special files. Read more here.
#include <sys/ioctl.h>
static int xioctl(int fd, int request, void *arg)
{
int r;
do r = ioctl (fd, request, arg);
while (-1 == r && EINTR == errno);
return r;
}
Step 3: Image Format
V4L2 provides an easy interface to check the image formats and colorspace that your webcam supports and provide. v4l2_format sturcture is to be used to change image format.
struct v4l2_format fmt = {0};
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
fmt.fmt.pix.width = 320;
fmt.fmt.pix.height = 240;
fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_MJPEG;
fmt.fmt.pix.field = V4L2_FIELD_NONE;
if (-1 == xioctl(fd, VIDIOC_S_FMT, &fmt))
{
perror("Setting Pixel Format");
return 1;
}
I have set image width and height to be 320 and 240 respectively. You should check out the format that your camera supports. My Camera supports MJPEG and YUV and hence I have set image format to MJPEG.
Step 4: Request Buffers
A buffer contains data exchanged by application and driver using Streaming I/O methods. v4l2_requestbuffers is used to allocate device buffers. Read more here.
struct v4l2_requestbuffers req = {0};
req.count = 1;
req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
req.memory = V4L2_MEMORY_MMAP;
if (-1 == xioctl(fd, VIDIOC_REQBUFS, &req))
{
perror("Requesting Buffer");
return 1;
}
The ioctl is used to initialize memory mapped(mmap), user pointer based I/O.
Step 5: Query Buffer
After requesting buffer from the device, we need to query the buffer in order to get raw data. Read more here
struct v4l2_buffer buf = {0};
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = bufferindex;
if(-1 == xioctl(fd, VIDIOC_QUERYBUF, &buf))
{
perror("Querying Buffer");
return 1;
}
buffer = mmap (NULL, buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, buf.m.offset);
The mmap() function asks to map length bytes starting at offset in the memory of the device specified by fd into the application address space, preferably at address start. Read more here
Step 6: Capture Image
After querying the buffer, the only thing left is capturing the frame and saving it in the buffer.
if(-1 == xioctl(fd, VIDIOC_STREAMON, &buf.type))
{
perror("Start Capture");
return 1;
}
fd_set fds;
FD_ZERO(&fds);
FD_SET(fd, &fds);
struct timeval tv = {0};
tv.tv_sec = 2;
int r = select(fd+1, &fds, NULL, NULL, &tv);
if(-1 == r)
{
perror("Waiting for Frame");
return 1;
}
if(-1 == xioctl(fd, VIDIOC_DQBUF, &buf))
{
perror("Retrieving Frame");
return 1;
}
Step 7: Store data in OpenCV datatype
I wanted to stored the retrieved data in OpenCV image structure. It took me few hours to figure out the perfect way. So here’s how I did it.
CvMat cvmat = cvMat(480, 640, CV_8UC3, (void*)buffer);
IplImage * img;
img = cvDecodeImage(&cvmat, 1);
So this how I captured frames from my webcam and stored in OpenCV Image data structure.
You can find the complete code here on my GitHub
P.S. Coding period for gsoc has started and I have to start working.
Open images from USB camera on linux using V4L2 with OpenCV的更多相关文章
- Jetson TX1使用usb camera采集图像 (2)
该方法只启动usb摄像头 import cv2 import numpy import matplotlib.pyplot as plot class Camera: cap = cv2.VideoC ...
- android4.0 USB Camera实例(三)UVC
前面我写了两篇文章说明了zc301的实现 详细请看 http://blog.csdn.net/hclydao/article/details/21235919 以下顺便把通用的USB也写上 前面的ZC ...
- Android USB Camera(1) : 调试记录【转】
转自:http://blog.csdn.net/eternity9255/article/details/53069037 版权声明:本文为博主原创文章,未经博主允许不得转载. 目录(?)[-] 前言 ...
- I.MX6 USB Camera
/************************************************************************* * I.MX6 USB Camera * 说明: ...
- Android开发之《USB Camera》
SimpleWebCam Source Code:https://bitbucket.org/neuralassembly/simplewebcam/src 1. USB摄像头UVC兼容(如今大部分兼 ...
- ROS_Kinetic_12 ROS程序基础Eclipse_C++(三)usb camera
ROS_Kinetic_12 ROS程序基础Eclipse_C++(三)usb camera 软件包下载地址:https://github.com/bosch-ros-pkg/usb_cam 下载后, ...
- Power OFF and ON USB device in linux (ubuntu)
Power OFF and ON USB device in linux (ubuntu) http://loginroot.com/power-off-and-on-usb-device-in-li ...
- Ffmpeg 获取USB Camera 视频流
本文讲述的案例是如何通过Ffmpeg实现从USB Camera中获取视频流并将视频流保存到MP4文件. 本文亦适用于从USB Camera 获取视频流并将视频流转发到rtmp服务的案例,二者基本的原理 ...
- android4.0 USB Camera示例(四)CMOS
上一页下一页说usb camera uvc标准 顺便说说CMOS一起做 操作基本一至, 前HAL在那里我已经提供了层CMOS相关接口 JNIEXPORT jint JNICALL Java_com_d ...
随机推荐
- 基础篇:6.7)形位公差-检测方法Measurement
本章目的:了解行为公差的检测方法,简单评估公司和制作方的检测能力. 1.形位公差检测规定 形状和位置公差检测规定GB/T 1958 -2004 2.形位公差的种类 3.形位公差的测量仪器 人工测量仪器 ...
- Pycharm+QTDesigner+PyQt5环境配置
python+PyQt5写界面很方便,记录下个人配置环境过程.... 安装软件: pycharm2017 Qt5.9.6 python3.6.6/python2.7.15 配置PyQt5: pytho ...
- 织梦dedecms5.7手机站页面首页正常其他页面显示pc页面解决方法
最近遇到的问题,用的是织梦的dedecms从以前的版本升级上来的最新版5.7sp2,客户需要手机版的,要做一个百度的验证. 这个站首页显示算是基本正常,点开里面随便一个页面会跳转到pc页面上 ...
- 批处理 进行svn代码拉取,vs编译,dotfuscator混淆
Dotfuscator的使用:https://www.cnblogs.com/aitong/p/10684004.html 从拉取代码,编译到最后的混淆步骤很多.这时就可以使用批处理来进行自动化. 用 ...
- 小程序 - 分包加载上限8M(一)
使用分包 配置方法 假设支持分包的小程序目录结构如下 ├── app.js ├── app.json ├── app.wxss ├── packageA │ └── pages │ ├── c ...
- openerp学习笔记 按客户电话、名称模糊查找选择客户(name_search)及客户名称自定义显示(name_get)
#同时按手机.电话.名称模糊查找选择客户 def name_search(self, cr, user, name, args=None, operator='ilike', context=N ...
- Robot Framework自动化测试三(selenium API)
Robot Framework Selenium API 说明: 此文档只是将最常用的UI 操作列出.更多方法请查找selenium2Library 关键字库. 一.浏览器驱动 通过不同的浏览器 ...
- orcale 之 存储过程
之前我们学习过 PL/SQL, 那么当我们的工作中我们通过 PL/SQL 做很多的事情,那么有一个问题,在每次的座同样一件事的时候是不是都需要重新通过 PL/SQL 去完成呢?可不可以只写一次然后,在 ...
- mysql修改表名
mysql修改表名 SQL语句为: alter table table_name rename to new_table_name 参考:http://blog.csdn.net/xrt95050/a ...
- The “SignFile” task was not given a value for the required parameter “CertificateThumbprint”的一个简单的解决方法
这个只是其中一种解决方法,而且不是万能的 1. 由提示内容可以看出,这个一个 sign(认证)的问题, 在出现这个问题的项目上,鼠标右键,选择properties,然后选择signing. 2. 选择 ...