Linux摄像头驱动V4L2

本文深入探讨Linux系统下的Video for Linux Second (V4L2)接口,讲解如何编写和使用V4L2驱动来操作摄像头。通过分析video.h头文件和video.c源代码,阐述V4L2框架的基本概念、核心函数以及设备交互流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

video.h

#ifndef VIDEO_H
#define VIDEO_H

/*¹ý³Ì
cam_open("/dev/video0");
cam_setformat(H, W);
cam_getinfo();
cam_setbuf();
cam_mapbuf();
cam_start();
while(1)
{
cam_getdata(bmp_yuv420,V4L2_PIX_FMT_YUV420);	//YUV420ΪÏñËØ*1.5,ĬÈÏyuv420
YV12ToBGR24_Table(bmp_yuv420,bmp_rgb24,W,H);
}
cam_stop();
cam_unmap();
cam_close();
*/

int cam_open(const char* path);
void cam_getinfo(void);
void cam_close(void);
int cam_setformat(int height, int width, int format);

//»ñÈ¡ÉãÏñͷͼƬ²É¼¯µÄ»º´æbuf
int cam_setbuf(void);

//Ó³Éäbufµ½Óû§¿Õ¼ä
void cam_mapbuf(void);

//¿ªÊ¼²É¼¯
void cam_start();

//»ñÈ¡²É¼¯µ½µÄÊý¾Ý
int cam_getdata(char *buffer);

int cam_stop();

int cam_unmap();

//yuv420--rgb24
bool YV12ToBGR24_Table(unsigned char* pYUV, unsigned char* pBGR24, int width, int height);

#endif // !VIDEO_H

 

video.c

#include "video.h"

#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>

int cam_width;
int cam_height;
int cam_fd;

struct cam_buffer {
	void*   start;
	unsigned  length;
	unsigned  offset;
};
struct cam_buffer *cam_buffers;

//打开摄像头设备
int cam_open(const char* path)
{
    cam_fd=open(path,O_RDWR);
    if (cam_fd < 0) {
        printf("Open camera failed\n");
        return -1;
    }
}

//获取摄像头信息
void cam_getinfo(void)
{
    struct v4l2_format fmt;
    fmt.type=V4L2_BUF_TYPE_VIDEO_CAPTURE;
    ioctl(cam_fd, VIDIOC_G_FMT, &fmt);
    printf("Current data format information:\n\twidth:%d\n\theight:%d\n",fmt.fmt.pix.width,fmt.fmt.pix.height);
    struct v4l2_fmtdesc fmtdesc;
    fmtdesc.index=0;
    fmtdesc.type=V4L2_BUF_TYPE_VIDEO_CAPTURE;
    while(ioctl(cam_fd,VIDIOC_ENUM_FMT,&fmtdesc)!=-1)
    {
        if(fmtdesc.pixelformat & fmt.fmt.pix.pixelformat)
        {
            printf("\tformat:%s\n",fmtdesc.description);
            break;
        }
        fmtdesc.index++;
    }
}

void cam_close(void)
{
    close(cam_fd);
}

int cam_setformat(int heigh
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值