前几天弄linux 下的摄像头,主要是用在嵌入式的图像处理上。关于v4l2的资料比较多的,主要是明白各种数据结构的含义,随便一搜就有很多,这里提供一个写好的示例。
对外接口很简单:
1)通过设备文件名打开摄像头。
2)读入帧,读入的格式是opencv格式的BGR排列顺序的24bit图像
3)关闭摄像头函数
为了简洁,所以没有提供设置参数的借口,各种设置已经硬编码在里面了。
还有就是摄像头一开始采集出来的格式是yuyv的,需要自己写一个转换的函数。我下面列出来的那个转换函数是从其他的例程里找的。
下面是头文件
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <malloc.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <linux/videodev2.h>
#include <time.h>
using namespace std;
const int WIDTH = 640;
const int HEIGHT = 480;
struct image_buffer
{
void * start;
size_t length;
};
struct v4l2_camera
{
char * dev_name;
int fd;
int n_buffers;
image_buffer * buffers;
};
/*
*open camera,
*return -1 if faild
*/
int open_camera(v4l2_camera * cam);
/*
*read one frame from the buffer,then convert to the format bgr888 for opencv
*return -1 if faild
*/
int read_frame(v4l2_camera * cam,char * image_bgr888);
int destroy_camera(v4l2_camera * cam);
实现文件
重点关注open_camera文件,基本上就是设置的各个流程。
首先打开设备,这不用说。
初始化设备里包括查询设备的能力,并且输出。
设置格式里包括设置图像的大小,采集格式。
设置缓冲区
关闭摄像头
代码如下
#include <iostream>
#include "V4L2.h"
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <opencv2/opencv.hpp>
using namespace std;
const int BUFFER_SIZE=2;
unsigned char table_cut[1024];
//构造yuyv2bgr的查询表
void init_table_cut()
{
int i;
for(i=0; i<512; i++