opencv4 AVframe 转mat
时间: 2024-02-27 15:55:15 浏览: 87
OpenCV中的Mat详解
可以使用以下代码将 AVFrame 转换为 OpenCV 的 Mat 对象:
```c++
#include <opencv2/opencv.hpp>
extern "C" {
#include <libavutil/imgutils.h>
#include <libswscale/swscale.h>
#include <libavcodec/avcodec.h>
}
cv::Mat avframe_to_mat(const AVFrame* frame) {
cv::Mat mat;
int width = frame->width;
int height = frame->height;
AVPixelFormat pFormat = static_cast<AVPixelFormat>(frame->format);
// 分配 AVFrame 中数据所需的内存
av_image_alloc(frame->data, frame->linesize, width, height, pFormat, 1);
// 将 AVFrame 转换为 BGR 格式的 Mat 对象
SwsContext* sws_ctx = sws_getContext(width, height, pFormat, width, height, AV_PIX_FMT_BGR24, SWS_BILINEAR, NULL, NULL, NULL);
if (sws_ctx == NULL) {
return mat;
}
int size = av_image_get_buffer_size(AV_PIX_FMT_BGR24, width, height, 1);
uint8_t* buffer = (uint8_t*)av_malloc(size * sizeof(uint8_t));
if (buffer == NULL) {
sws_freeContext(sws_ctx);
return mat;
}
AVFrame* pFrame = av_frame_alloc();
av_image_fill_arrays(pFrame->data, pFrame->linesize, buffer, AV_PIX_FMT_BGR24, width, height, 1);
sws_scale(sws_ctx, frame->data, frame->linesize, 0, height, pFrame->data, pFrame->linesize);
mat = cv::Mat(height, width, CV_8UC3, buffer);
sws_freeContext(sws_ctx);
av_frame_free(&pFrame);
return mat;
}
```
其中,AVFrame 为要转换的帧,返回值为转换后的 Mat 对象。注意,需要在使用完 Mat 对象后释放内存。
阅读全文