之前网络上找到的v4l2读取图片的代码基本可以用,但是代码冗余,这个代码在树莓派上测试通过,其它系统上未测试
代码中使用的库:
libjpeg实现rgb图像存储成图片
libudev实现了自动查找视频设备的功能
说明:
VIDIOC_S_FMT设置要读取的格式后要用VIDIOC_G_FMT再获取下,查检是否设置成功了,比如设置的图片太大,fmt.fmt.pix.pixelformat不支持等问题
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <linux/types.h>
#include <linux/videodev2.h>
#include <setjmp.h>
#include <libudev.h>
#include <stdint.h>
#include "jpeglib.h"
#define JPEG_QUALITY 100
#define IMAGEWIDTH 352
#define IMAGEHEIGHT 288
static char dev_path[128];
static int fd;
static struct v4l2_capability cap;
struct v4l2_fmtdesc fmtdesc;
struct v4l2_format fmt, fmtack;
struct v4l2_requestbuffers req;
struct v4l2_buffer buf;
enum v4l2_buf_type type;
unsigned char frame_buffer[IMAGEWIDTH * IMAGEHEIGHT * 3];
struct buffer {
void *start;
unsigned int length;
} *buffers;
int device_find()
{
struct udev *udev;
struct udev_enumerate *enumerate;
struct udev_list_entry *devices, *dev_list_entry;
struct udev_device *dev;
udev = udev_new();
if (!udev) {
printf("Can't create udev\n");
return -1;
}
enumerate = udev_enumerate_new(udev);
udev_enumerate_add_match_subsystem(enumerate, "video4linux");
udev_enumerate_scan_devices(enumerate);
devices = udev_enumerate_get_list_entry(enumerate);
udev_list_entry_foreach(dev_list_entry, devices) {
const char *path;
path = udev_list_entry_get_name(dev_list_entry);
dev = udev_device_new_from_syspath(udev, path);
sprintf(dev_path, "%s", udev_devi