ubuntu ffmpeg 摄像头采集 位图 代码
时间: 2023-07-25 18:18:01 浏览: 135
以下是基于 Ubuntu 系统的使用 FFmpeg 进行摄像头采集并保存位图的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <linux/videodev2.h>
#define DEVICE "/dev/video0"
#define IMAGE_WIDTH 640
#define IMAGE_HEIGHT 480
int main(int argc, char **argv) {
int fd = 0;
struct v4l2_capability cap;
struct v4l2_format fmt;
struct v4l2_requestbuffers req;
struct v4l2_buffer buf;
void *buffer_start = NULL;
FILE *fp = NULL;
char filename[32] = {0};
int n_buffers = 0;
int ret = 0;
// 打开视频设备
fd = open(DEVICE, O_RDWR);
if (-1 == fd) {
perror("open");
return errno;
}
// 查询设备能力
ret = ioctl(fd, VIDIOC_QUERYCAP, &cap);
if (-1 == ret) {
perror("ioctl(VIDIOC_QUERYCAP)");
return errno;
}
// 设置视频格式
memset(&fmt, 0, sizeof(fmt));
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
fmt.fmt.pix.width = IMAGE_WIDTH;
fmt.fmt.pix.height = IMAGE_HEIGHT;
fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
ret = ioctl(fd, VIDIOC_S_FMT, &fmt);
if (-1 == ret) {
perror("ioctl(VIDIOC_S_FMT)");
return errno;
}
// 请求分配内存
memset(&req, 0, sizeof(req));
req.count = 4;
req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
req.memory = V4L2_MEMORY_MMAP;
ret = ioctl(fd, VIDIOC_REQBUFS, &req);
if (-1 == ret) {
perror("ioctl(VIDIOC_REQBUFS)");
return errno;
}
// 映射缓冲区
buffer_start = mmap(NULL, req.count * fmt.fmt.pix.sizeimage,
PROT_READ | PROT_WRITE, MAP_SHARED,
fd, 0);
if (MAP_FAILED == buffer_start) {
perror("mmap");
return errno;
}
// 缓存入队
for (n_buffers = 0; n_buffers < req.count; ++n_buffers) {
memset(&buf, 0, sizeof(buf));
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = n_buffers;
ret = ioctl(fd, VIDIOC_QBUF, &buf);
if (-1 == ret) {
perror("ioctl(VIDIOC_QBUF)");
return errno;
}
}
// 开始采集
enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
ret = ioctl(fd, VIDIOC_STREAMON, &type);
if (-1 == ret) {
perror("ioctl(VIDIOC_STREAMON)");
return errno;
}
// 采集图像
for (int i = 0; i < 10; ++i) {
memset(&buf, 0, sizeof(buf));
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
ret = ioctl(fd, VIDIOC_DQBUF, &buf);
if (-1 == ret) {
perror("ioctl(VIDIOC_DQBUF)");
return errno;
}
// 保存位图
sprintf(filename, "image%d.bmp", i);
fp = fopen(filename, "wb");
fwrite(buffer_start, fmt.fmt.pix.sizeimage, 1, fp);
fclose(fp);
// 重新入队
ret = ioctl(fd, VIDIOC_QBUF, &buf);
if (-1 == ret) {
perror("ioctl(VIDIOC_QBUF)");
return errno;
}
}
// 停止采集
ret = ioctl(fd, VIDIOC_STREAMOFF, &type);
if (-1 == ret) {
perror("ioctl(VIDIOC_STREAMOFF)");
return errno;
}
// 取消映射
munmap(buffer_start, req.count * fmt.fmt.pix.sizeimage);
// 关闭设备
close(fd);
return 0;
}
```
注意:在运行该代码之前,需要先安装 FFmpeg 和视频设备的驱动。
阅读全文