意见箱
恒创运营部门将仔细参阅您的意见和建议,必要时将通过预留邮箱与您保持联络。感谢您的支持!
意见/建议
提交建议

opencv 摄像头视频 ffmpeg保存H264

来源:恒创科技 编辑:恒创科技编辑部
2024-01-28 09:51:59


opencv无法使用Tcp实时传输摄像头视频,而UDP容易引起丢帧卡顿现象,所以,必须借助ffmpeg来缓存摄像头视频


opencv 摄像头视频 ffmpeg保存H264

#ifndef INT64_C 
#define INT64_C(c) (c ## LL)
#define UINT64_C(c) (c ## ULL)
#endif extern "C" {
/*Include ffmpeg header file*/
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libswscale/swscale.h> #include <libavutil/imgutils.h>
#include <libavutil/opt.h>
#include <libavutil/mathematics.h>
#include <libavutil/samplefmt.h>
}int main()
{
//变量
AVFormatContext *pFormatCtx;
char filepath[] = "rtsp://admin:admin@192.168.1.13:554/video2";
AVPacket *packet;
//初始化
av_register_all();
avformat_network_init();
pFormatCtx = avformat_alloc_context();
AVDictionary* options = NULL;
av_dict_set(&options, "buffer_size", "102400", 0); //设置缓存大小,1080p可将值调大
av_dict_set(&options, "rtsp_transport", "tcp", 0); //以udp方式打开,如果以tcp方式打开将udp替换为tcp
av_dict_set(&options, "stimeout", "2000000", 0); //设置超时断开连接时间,单位微秒
av_dict_set(&options, "max_delay", "500000", 0); //设置最大时延
packet = (AVPacket *)av_malloc(sizeof(AVPacket));
//打开网络流或文件流
if (avformat_open_input(&pFormatCtx, filepath, NULL, &options) != 0)
{
printf("Couldn't open input stream.\n");
return -1;
}
//查找码流信息
//设置查找时间以避免耗时过长
pFormatCtx->probesize = 1000;
pFormatCtx->max_analyze_duration = AV_TIME_BASE;
if (avformat_find_stream_info(pFormatCtx, NULL)<0)
{
printf("Couldn't find stream information.\n");
return -1;
}
//查找码流中是否有视频流
int videoindex = -1;
for (int i = 0; i<pFormatCtx->nb_streams; i++)
if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
{
videoindex = i;
break;
}
if (videoindex == -1)
{
printf("Didn't find a video stream.\n");
return -1;
}
//保存一段时间的视频流,写入文件中
FILE *fpSave;
fpSave=fopen("geth264.h264", "wb");
for (int i = 0; i < 1000; i++)
{
if (av_read_frame(pFormatCtx, packet) >= 0)
{
if (packet->stream_index == videoindex)
{
fwrite(packet->data, 1, packet->size, fpSave);//写数据到文件中
}
av_packet_unref(packet);
}
}
//释放内存
fclose(fpSave);
av_free(pFormatCtx);
av_free(packet);
return 0;
}


需安装ffmpeg 之后,再编译

-I/monchickey/ffmpeg/include -L/monchickey/ffmpeg/lib -lavformat -lavcodec -lavutil

具体安装的库路径自己判断哦

上一篇: LLRP基础知识介绍 下一篇: 手机怎么远程登录云服务器?