本文的主要内容:演示如何通过编程采集摄像头的视频数据。
整体的流程跟《音频录制02_编程》类似。
依赖库
需要依赖4个库。
| extern "C" { |
| #include <libavdevice/avdevice.h> |
| #include <libavformat/avformat.h> |
| #include <libavutil/avutil.h> |
| #include <libavutil/imgutils.h> |
| #include <libavcodec/avcodec.h> |
| } |
宏定义
| #ifdef Q_OS_WIN |
| |
| #define FMT_NAME "dshow" |
| |
| #define DEVICE_NAME "video=Integrated Camera" |
| |
| #define FILENAME "F:/out.yuv" |
| #else |
| #define FMT_NAME "avfoundation" |
| #define DEVICE_NAME "0" |
| #define FILENAME "/Users/mj/Desktop/out.yuv" |
| #endif |
| |
| #define ERROR_BUF(ret) \ |
| char errbuf[1024]; \ |
| av_strerror(ret, errbuf, sizeof (errbuf)); |
权限申请
在Mac平台,有2个注意点:
- 需要在Info.plist中添加摄像头的使用说明,申请摄像头的使用权限
- 使用Debug模式运行程序
- 不然会出现闪退的情况
| <?xml version="1.0" encoding="UTF-8"?> |
| <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> |
| <plist version="1.0"> |
| <dict> |
| <key>NSCameraUsageDescription</key> |
| <string>使用摄像头采集您的靓照</string> |
| </dict> |
| </plist> |
注册设备
在整个程序的运行过程中,只需要执行1次注册设备的代码。
获取输入格式对象
| |
| AVInputFormat *fmt = av_find_input_format(FMT_NAME); |
| if (!fmt) { |
| qDebug() << "av_find_input_format error" << FMT_NAME; |
| return; |
| } |
打开输入设备
| |
| AVFormatContext *ctx = nullptr; |
| |
| |
| AVDictionary *options = nullptr; |
| av_dict_set(&options, "video_size", "640x480", 0); |
| av_dict_set(&options, "pixel_format", "yuyv422", 0); |
| av_dict_set(&options, "framerate", "30", 0); |
| |
| |
| int ret = avformat_open_input(&ctx, DEVICE_NAME, fmt, &options); |
| if (ret < 0) { |
| ERROR_BUF(ret); |
| qDebug() << "avformat_open_input error" << errbuf; |
| return; |
| } |
打开输出文件
| |
| QFile file(FILENAME); |
| if (!file.open(QFile::WriteOnly)) { |
| qDebug() << "file open error" << FILENAME; |
| |
| |
| avformat_close_input(&ctx); |
| return; |
| } |
采集视频数据
| |
| AVCodecParameters *params = ctx->streams[0]->codecpar; |
| int imageSize = av_image_get_buffer_size( |
| (AVPixelFormat) params->format, |
| params->width, params->height, |
| 1); |
| |
| |
| AVPacket *pkt = av_packet_alloc(); |
| while (!isInterruptionRequested()) { |
| |
| ret = av_read_frame(ctx, pkt); |
| |
| if (ret == 0) { |
| |
| file.write((const char *) pkt->data, imageSize); |
| |
| |
| |
| |
| |
| |
| |
| |
| av_packet_unref(pkt); |
| } else if (ret == AVERROR(EAGAIN)) { |
| continue; |
| } else { |
| ERROR_BUF(ret); |
| qDebug() << "av_read_frame error" << errbuf; |
| break; |
| } |
| } |
释放资源
| |
| av_packet_free(&pkt); |
| |
| |
| file.close(); |
| |
| |
| avformat_close_input(&ctx); |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?