Last active
August 6, 2024 09:11
-
-
Save foowaa/1d296a9dee81c7a2a52f291c95e55680 to your computer and use it in GitHub Desktop.
ffmpeg avframe and opencv mat
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! | |
* \file format_converter.h | |
* | |
* \author cltian | |
* \date 11 2020 | |
* | |
* | |
*/ | |
extern "C" { | |
#include "libavcodec/avcodec.h" | |
#include "libavformat/avformat.h" | |
#include "libavutil/avutil.h" | |
#include "libswscale/swscale.h" | |
#include <libavutil/imgutils.h> | |
} | |
#include <opencv2/core.hpp> | |
//************************************ | |
// Method: avframeToCvmat | |
// Access: public | |
// Returns: cv::Mat | |
// Qualifier: | |
// Parameter: const AVFrame * frame | |
// Description: AVFrame转MAT | |
//************************************ | |
cv::Mat avframeToCvmat(const AVFrame *frame) { | |
int width = frame->width; | |
int height = frame->height; | |
cv::Mat image(height, width, CV_8UC3); | |
int cvLinesizes[1]; | |
cvLinesizes[0] = image.step1(); | |
SwsContext *conversion = sws_getContext( | |
width, height, (AVPixelFormat)frame->format, width, height, | |
AVPixelFormat::AV_PIX_FMT_BGR24, SWS_FAST_BILINEAR, NULL, NULL, NULL); | |
sws_scale(conversion, frame->data, frame->linesize, 0, height, &image.data, | |
cvLinesizes); | |
sws_freeContext(conversion); | |
return image; | |
} | |
//************************************ | |
// Method: cvmatToAvframe | |
// Access: public | |
// Returns: AVFrame * | |
// Qualifier: | |
// Parameter: cv::Mat * image | |
// Parameter: AVFrame * frame | |
// Description: MAT转AVFrame | |
//************************************ | |
AVFrame *cvmatToAvframe(cv::Mat *image, AVFrame *frame) { | |
int width = image->cols; | |
int height = image->rows; | |
int cvLinesizes[1]; | |
cvLinesizes[0] = image->step1(); | |
if (frame == NULL) { | |
frame = av_frame_alloc(); | |
av_image_alloc(frame->data, frame->linesize, width, height, | |
AVPixelFormat::AV_PIX_FMT_YUV420P, 1); | |
} | |
SwsContext *conversion = sws_getContext( | |
width, height, AVPixelFormat::AV_PIX_FMT_BGR24, width, height, | |
(AVPixelFormat)frame->format, SWS_FAST_BILINEAR, NULL, NULL, NULL); | |
sws_scale(conversion, &image->data, cvLinesizes, 0, height, frame->data, | |
frame->linesize); | |
sws_freeContext(conversion); | |
return frame; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment