AVFrame 转 std::vector
时间: 2023-10-20 12:36:44 浏览: 57
你可以使用以下代码将 AVFrame 转换为 std::vector:
```cpp
std::vector<uint8_t> avframeToVector(AVFrame* frame) {
std::vector<uint8_t> data;
int size = avpicture_get_size(frame->format, frame->width, frame->height);
data.resize(size);
AVPicture picture;
avpicture_fill(&picture, data.data(), frame->format, frame->width, frame->height);
for (int i = 0; i < frame->height; i++) {
memcpy(picture.data[0] + i * picture.linesize[0], frame->data[0] + i * frame->linesize[0], frame->width);
}
return data;
}
```
这个函数会将 AVFrame 的数据复制到一个 std::vector,然后返回该向量。请确保你已经包含了必要的头文件,并且在调用此函数之前,已经正确分配了 AVFrame 的数据。
相关问题
AVFrame 转mat
将 AVFrame 转换为 OpenCV 的 Mat,可以使用以下代码:
```c++
#include <opencv2/opencv.hpp>
extern "C" {
#include <libavutil/imgutils.h>
#include <libswscale/swscale.h>
}
cv::Mat avframe_to_mat(AVFrame *frame) {
cv::Mat mat(frame->height, frame->width, CV_8UC3, frame->data[0]);
cv::Mat mat2;
cv::cvtColor(mat, mat2, cv::COLOR_BGR2RGB);
return mat2;
}
```
注意,这里假设输入的 AVFrame 是 YUV 格式的,如果是其他格式,需要进行相应的转换。同时,这里将 BGR 转为了 RGB,如果需要 BGR,可以将 `cv::COLOR_BGR2RGB` 改为 `cv::COLOR_RGB2BGR`。
opencv4 AVframe 转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 对象后释放内存。