使用ffmpeg获取一帧摄像头数据
linux-dash
 A beautiful web dashboard for Linux
 项目地址:https://gitcode.com/gh_mirrors/li/linux-dash
  免费下载资源
免费下载资源
       ·  
 最近在研究FFmpeg,比较惊讶的是网上一大堆资料都是在说如何从已有的视频中截取一帧图像,却很少说到如何直接从摄像头中捕获一帧图像,其实我一直有个疑问,就是在Linux下,大家是用什么库来采集摄像头的(opencv?)?还是自己写v4l2的代码来实现?我之前一直都是用v4l2来采集摄像头的。经过一些时间的研究,最后成功地用FFmpeg实现了从摄像头采集一帧图像,实现代码也非常简单。不多说,上代码。 
 
 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <stdlib.h>
 4 #include <fcntl.h>
 5 #include <unistd.h>
 6 
 7 #include <libavformat/avformat.h>
 8 #include <libavcodec/avcodec.h>
 9 #include <libavdevice/avdevice.h>
10 
11 
12 void captureOneFrame()
13 {
14     AVFormatContext *fmtCtx = NULL;
15     AVFormatParameters inputFmtParameter;
16     AVPacket *pcaket;
17         
18     //输入格式(V4L2)
19     AVInputFormat *inputFmt = av_find_input_format ("video4linux2"); 
20     if (inputFmt == NULL) 
21     {
22         printf("can not find_input_format\n");
23         return;
24     }
25 
26     memset (&inputFmtParameter, 0, sizeof(inputFmtParameter));
27     //采集图像的高度
28     inputFmtParameter.height = 240;
29     //采集图像的宽度
30     inputFmtParameter.width  = 320;
31 
32     //打开摄像头设备
33     if (av_open_input_file ( &fmtCtx, "/dev/video0", inputFmt,
34                sizeof(inputFmtParameter),&inputFmtParameter) < 0)
35     {
36         printf("can not open_input_file\n");
37          return;
38     }
39     //从摄像头获取一帧图像
40     av_read_frame(fmtCtx, pcaket);
41     //输出图像的大小
42     printf("data length = %d\n",pcaket->size);
43     
44     FILE *fp;
45     //打开(新建)文件
46     fp = fopen("out.yuv", "wb");
47     if (fp < 0)
48     {
49         printf("open frame data file failed\n");
50         return ;
51     }
52     //将数据写入文件
53     fwrite(pcaket->data, 1, pcaket->size, fp);
54     //关闭文件
55     fclose(fp);
56 
57     //关闭设备文件
58     av_close_input_file(fmtCtx);
59 }
60 
61 
62 int main()
63 {
64     avcodec_init();    
65     avcodec_register_all();
66     avdevice_register_all();
67 
68     captureOneFrame();
69 
70     return 0;
71 }
     注意:采集出来的图像的是YV12格式的。用YUV格式查看软件看下效果:

 GitHub 加速计划 / li / linux-dash
 GitHub 加速计划 / li / linux-dash 10
10
             2
2
             下载
下载
            
          A beautiful web dashboard for Linux
        
 
          最近提交(Master分支:1 个月前 )
 186a802e 
added ecosystem file for PM2 5 年前 
5def40a3 
Add host customization support for the NodeJS version 5 年前 
 
 新一代开源开发者平台 GitCode,通过集成代码托管服务、代码仓库以及可信赖的开源组件库,让开发者可以在云端进行代码托管和开发。旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。
更多推荐



所有评论(0)