//cut a picture
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <getopt.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <malloc.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <asm/types.h>
#include <linux/videodev2.h>
#define CLEAR(x) memset (&(x), 0, sizeof (x))
struct buffer {
void * start;
size_t length;
};
static char * dev_name = "/dev/video2";//摄像头设备名
static int fd = -1;
struct buffer * buffers = NULL;
static unsigned int n_buffers = 0;
#define VIDEO_WIDTH 640
#define VIDEO_HEIGHT 480
#define VIDEO_FORMAT V4L2_PIX_FMT_MJPEG
//V4L2_PIX_FMT_JPEG
//V4L2_PIX_FMT_YUYV
//V4L2_PIX_FMT_YVU420
//V4L2_PIX_FMT_RGB32
FILE *file_fd;
#define CAPTURE_FILE "test.jpg"
static unsigned long file_length;
//////////////////////////////////////////////////////
//获取一帧数据
//从视频缓冲区的输出队列中取得一个已经保存有一帧视频数据的视频缓冲区
//////////////////////////////////////////////////////
static int read_frame (void)
{
struct v4l2_buffer buf;
CLEAR (buf);
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
if(ioctl (fd, VIDIOC_DQBUF, &buf) == -1)
{
printf("VIDIOC_DQBUF failture\n"); //出列采集的帧缓冲
exit(1);
}
assert (buf.index < n_buffers);
// printf ("buf.index dq is %d,\n",buf.index);
//将其写入文件中
fwrite(buffers[buf.index].start, buffers[buf.index].length, 1, file_fd);
printf("Capture one frame saved in %s\n", CAPTURE_FILE);
//再将其入列
if(ioctl (fd, VIDIOC_QBUF, &buf)<0)
printf("failture VIDIOC_QBUF\n");
return 1;
}
int main (int argc,char ** argv)
{
file_fd = fopen(CAPTURE_FILE, "w");//图片文件名
//打开设备
fd = open (dev_name, O_RDWR | O_NONBLOCK, 0);
if(fd < 0)
{
printf("open %s failed\n",dev_name);
exit(1);
}
//获取驱动信息//获取摄像头参数//查询驱动功能并打印
struct v4l2_capability cap;
if(ioctl (fd, VIDIOC_QUERYCAP, &cap) < 0)
{
printf("get vidieo capability error,error code: %d \n", errno);
exit(1);
}
// Print capability infomations
printf("\nCapability Informations:\n");
printf("Driver Name:%s\nCard Name:%s\nBus info:%s\nDriver Version:%u.%u.%u\nCapabilities: X\n",
cap.driver,cap.card,cap.bus_info,
(cap.version>>16)&0XFF, (cap.version>>8)&0XFF,cap.version&0XFF,
cap.capabilities );
//获取设备支持的视频格式
struct v4l2_fmtdesc fmtdesc;
CLEAR (fmtdesc);
fmtdesc.index = 0;
fmtdesc.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
printf("\nSupport format:\n");
while ((ioctl(fd, VIDIOC_ENUM_FMT, &fmtdesc)) == 0)
{
printf("/t%d.\n{\npixelformat = '%c%c%c%c',\ndescription = '%s'\n }\n",
fmtdesc.index+1,