生成一个基于v4l2的获取USB摄像头图像的C++程序
时间: 2023-06-20 07:04:22 浏览: 180
v4l2下的usb摄像头采集图像详解
4星 · 用户满意度95%
好的,可以参考以下代码:
```c
#include <opencv2/opencv.hpp>
#include <iostream>
#include <linux/videodev2.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
using namespace std;
using namespace cv;
int main(int argc, char* argv[])
{
const char* dev_name = "/dev/video0";
int fd = open(dev_name, O_RDWR | O_NONBLOCK, 0);
if (fd < 0)
{
perror("open");
exit(1);
}
struct v4l2_capability cap;
if (ioctl(fd, VIDIOC_QUERYCAP, &cap) < 0)
{
perror("VIDIOC_QUERYCAP");
exit(1);
}
cout << "Driver Name: " << cap.driver << endl;
cout << "Card Name: " << cap.card << endl;
cout << "Bus info: " << cap.bus_info << endl;
cout << "Version: " << (cap.version >> 16) << "." << ((cap.version >> 8) & 0xff) << "." << (cap.version & 0xff) << endl;
struct v4l2_format fmt;
memset(&fmt, 0, sizeof(fmt));
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
fmt.fmt.pix.width = 640;
fmt.fmt.pix.height = 480;
fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_MJPEG;
fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
if (ioctl(fd, VIDIOC_S_FMT, &fmt) < 0)
{
perror("VIDIOC_S_FMT");
exit(1);
}
struct v4l2_requestbuffers req;
memset(&req, 0, sizeof(req));
req.count = 1;
req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
req.memory = V4L2_MEMORY_MMAP;
if (ioctl(fd, VIDIOC_REQBUFS, &req) < 0)
{
perror("VIDIOC_REQBUFS");
exit(1);
}
struct v4l2_buffer buf;
memset(&buf, 0, sizeof(buf));
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = 0;
if (ioctl(fd, VIDIOC_QUERYBUF, &buf) < 0)
{
perror("VIDIOC_QUERYBUF");
exit(1);
}
void* buffer = mmap(NULL, buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, buf.m.offset);
if (buffer == MAP_FAILED)
{
perror("mmap");
exit(1);
}
memset(buffer, 0, buf.length);
if (ioctl(fd, VIDIOC_QBUF, &buf) < 0)
{
perror("VIDIOC_QBUF");
exit(1);
}
if (ioctl(fd, VIDIOC_STREAMON, &buf.type) < 0)
{
perror("VIDIOC_STREAMON");
exit(1);
}
Mat frame;
for (int i = 0; i < 100; i++)
{
fd_set fds;
FD_ZERO(&fds);
FD_SET(fd, &fds);
struct timeval tv = {0};
tv.tv_sec = 2;
tv.tv_usec = 0;
int r = select(fd+1, &fds, NULL, NULL, &tv);
if (r == -1)
{
perror("select");
exit(1);
}
if (r == 0)
{
fprintf(stderr, "select timeout\n");
exit(1);
}
if (ioctl(fd, VIDIOC_DQBUF, &buf) < 0)
{
perror("VIDIOC_DQBUF");
exit(1);
}
frame = Mat(Size(fmt.fmt.pix.width, fmt.fmt.pix.height), CV_8UC3, (char*)buffer);
if (ioctl(fd, VIDIOC_QBUF, &buf) < 0)
{
perror("VIDIOC_QBUF");
exit(1);
}
imshow("Frame", frame);
waitKey(1);
}
if (ioctl(fd, VIDIOC_STREAMOFF, &buf.type) < 0)
{
perror("VIDIOC_STREAMOFF");
exit(1);
}
close(fd);
return 0;
}
```
这段代码是一个简单的基于v4l2的获取USB摄像头图像的C程序,其中使用了OpenCV库来显示图像。需要注意的是,这段代码只是一个基础示例,读者可以根据自己的需求进行修改和扩展。
阅读全文