ffmpeg opencv 打开视频文件,并且播放

本文介绍了一个使用FFmpeg和OpenCV进行视频文件读取及显示的示例程序。该程序首先通过FFmpeg库打开并解码视频文件,然后利用OpenCV库将解码后的帧显示出来。涉及的主要步骤包括:打开视频文件、获取视频流信息、找到视频编码格式、获取解码器、申请原始数据帧和RGB帧内存、创建格式转换上下文等。

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

// FFMpeg + OpenCV demo  
#include <stdio.h>  
#include <opencv2/core/core.hpp>  
#include <opencv2/highgui/highgui.hpp>  

#ifdef __cplusplus  
extern "C" {
#endif  

#include <libavformat/avformat.h>  
#include <libavcodec/avcodec.h>  
#include <libswscale/swscale.h>  
#include <libavformat/avformat.h>  
#include <libavcodec/avcodec.h>  
#include <libswscale/swscale.h>  
#include <libavutil/opt.h>
#include <libavcodec/avcodec.h>
#include <libavutil/channel_layout.h>
#include <libavutil/common.h>
#include <libavutil/imgutils.h>
#include <libavutil/mathematics.h>
#include <libavutil/samplefmt.h>

#ifdef __cplusplus  
}
#endif  

#include <iostream>

static void CopyDate(AVFrame *pFrame, int width, int height, int time);
static void SaveFrame(AVFrame *pFrame, int width, int height, int iFrame);

using namespace cv;
using namespace std;

int main(int argc, char* argv[])
{
	int result = 0;
	av_register_all(); // 注册所有FFmpeg库所支持的文件格式和codec

	AVFormatContext* pFormatCtx;
	char* filename = "up.mp4"; //输入文件名

	// step1: 打开媒体文件,最后2个参数是用来指定文件格式,buffer大小和格式参数,设置成NULL的话,libavformat库会自动去探测它们
	result = avformat_open_input(&pFormatCtx, filename, NULL, NULL);
	if (result != 0)
	{
		cout << "open file fail" << endl;
		return -1;
	}
	cout << "open file succ" << endl;

	// step2: 查找信息流的信息
	result = avformat_find_stream_info(pFormatCtx, NULL);
	if (result != 0)
	{
		cout << "find stream fail" << endl;
		return -1;
	}
	cout << "find stream succ" << endl;

	// step3: 打印信息
	//av_dump_format(pFormatCtx, 0, filename, 0);

	// step4:找到video流数据
	int i = 0;
	int videoStream = -1;
	AVCodecContext* pCodecCtx = NULL;
	for (i = 0; i < pFormatCtx->nb_streams; i++)
	{
		if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
		{
			videoStream = i;
			break;
		}
	}

	if (videoStream == -1)
	{
		cout << "find stream video fail" << endl;
		return -1;
	}
	cout << "find stream video succ." << endl;

	// 得到video编码格式
	pCodecCtx = pFormatCtx->streams[videoStream]->codec;
	
	// step5: 得到解码器
	AVCodec* pCodec = NULL;
	pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
	if (pCodec == NULL)
	{
		cout << "find decoder fail" << endl;
		return -1;
	}
	cout << "find decoder succ" << endl;

	result = avcodec_open2(pCodecCtx, pCodec, NULL);
	if (result != 0)
	{
		cout << "open codec fail" << endl;
		return -1;
	}
	cout << "open codec succ" << endl;

	// step6: 申请原始数据帧 和 RGB帧内存
	AVFrame* pFrame = NULL;
	AVFrame* pFrameRGB = NULL;
	pFrame = av_frame_alloc();
	pFrameRGB = av_frame_alloc();
	if (pFrame == NULL || pFrameRGB == NULL)
	{
		return -1;
	}

	int numBytes = avpicture_get_size(AV_PIX_FMT_RGB24, pCodecCtx->width, pCodecCtx->height);
	uint8_t* buffer = (uint8_t*)av_malloc(numBytes * sizeof(uint8_t));
	avpicture_fill((AVPicture*)pFrameRGB, buffer, AV_PIX_FMT_RGB24, pCodecCtx->width, pCodecCtx->height);

	int frameFinishsed = 0;
	AVPacket packet;
	i = 0; 

	// step7: 创建格式转化文本
	SwsContext * pSwxCtx = sws_getContext(
		pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt,
		pCodecCtx->width, pCodecCtx->height, AV_PIX_FMT_RGB24,
		SWS_BILINEAR, 0, 0, 0);

	cv::Mat image(pCodecCtx->height, pCodecCtx->width, CV_8UC3);
	int b = 0;
	int g = 1;
	int r = 2;

	while (true)
	{
		// 得到数据包
		result = av_read_frame(pFormatCtx, &packet);
		if (result != 0)
		{
			break;
		}

		if (packet.stream_index == videoStream)
		{
			// 解码
			avcodec_decode_video2(pCodecCtx, pFrame, &frameFinishsed, &packet);

			if (frameFinishsed)
			{
				// 转换
				sws_scale(pSwxCtx, pFrame->data, pFrame->linesize, 0, pCodecCtx->height,
					pFrameRGB->data, pFrameRGB->linesize);

				for (int m = 0; m < pCodecCtx->height; m++)
				{
					for (int n = 0; n < pCodecCtx->width; n++)
					{
						image.at<Vec3b>(m, n)[r] = pFrameRGB->data[0][3 * (m*pCodecCtx->width + n) + 0];
						image.at<Vec3b>(m, n)[g] = pFrameRGB->data[0][3 * (m*pCodecCtx->width + n) + 1];
						image.at<Vec3b>(m, n)[b] = pFrameRGB->data[0][3 * (m*pCodecCtx->width + n) + 2];
					}
				}
				cv::imshow("pic", image);
				cv::waitKey(30);
			}
		}

		av_free_packet(&packet);
	}
	
	avformat_close_input(&pFormatCtx);

	system("pause");
	return 0;
}




### 使用OpenCV打开并读取视频文件 要使用OpenCV打开并读取视频文件,可以利用 `cv2.VideoCapture()` 方法创建一个视频捕获对象。此方法接受一个参数,该参数可以是设备索引(表示摄像头)或者是一个字符串形式的视频文件路径。一旦成功初始化了 `VideoCapture` 对象,就可以通过循环逐帧读取视频中的每一帧。 下面提供了一个完整的 Python 示例代码,展示如何使用 OpenCV 来读取和显示本地存储的一个视频文件: ```python import cv2 # 创建 VideoCapture 对象,传入视频文件路径作为参数 cap = cv2.VideoCapture('example_video.mp4') # 替换为实际存在的视频文件名或路径[^1] if not cap.isOpened(): print("无法打开视频文件") else: while True: ret, frame = cap.read() # 逐帧读取视频 if not ret: # 如果读取失败,则退出循环 break # 显示当前帧 cv2.imshow('Frame', frame) # 按下键盘上的 'q' 键可提前结束播放 if cv2.waitKey(25) & 0xFF == ord('q'): break # 清理资源 cap.release() cv2.destroyAllWindows() ``` 上述脚本中,`cv2.VideoCapture()` 被用来加载指定的视频文件。如果未能正确加载视频文件,程序会打印错误消息;反之则进入无限循环,在每次迭代过程中调用 `.read()` 方法获取下一帧图像,并将其传递给 `cv2.imshow()` 进行可视化呈现。当所有帧都被处理完毕或是用户按下预设按键 ('q') 后终止操作,最后释放掉所占用的相关硬件/软件资源[^2]。 值得注意的是,`VideoCapture` 类实际上是基于 FFmpeg 封装而成的一种高级接口,因此能够支持多种常见格式的音视频流解析工作[^3]。 ####
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值