QT + opencv + mpp硬件编码 保存视频文件 代码demo
时间: 2023-09-04 22:15:15 浏览: 297
以下是一个简单的代码示例,演示如何使用Qt、OpenCV和MPP硬件编码来保存视频文件:
```cpp
#include <QtWidgets/QApplication>
#include <opencv2/opencv.hpp>
#include <rockchip/rockchip_mpp.h>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// 初始化MPP硬件编码器
MPP_RET ret = mpp_env_init();
if (ret != MPP_OK) {
qDebug() << "MPP env init failed";
return -1;
}
mpp_codec_t codec = MPP_VIDEO_CodingAVC;
MppCtx ctx;
MppApi *mpi;
ret = mpp_create(&ctx, &mpi);
if (ret != MPP_OK) {
qDebug() << "MPP create failed";
return -1;
}
MppCodingType type = MPP_VIDEO_CodingAVC;
MppFrameFormat fmt = MPP_FMT_YUV420P;
int width = 640;
int height = 480;
int fps = 30;
int bitrate = 2000 * 1000;
int gop = fps * 2;
MppEncPrepCfg prep_cfg;
prep_cfg.change = MPP_ENC_PREP_CFG_CHANGE_INPUT |
MPP_ENC_PREP_CFG_CHANGE_FORMAT |
MPP_ENC_PREP_CFG_CHANGE_ROTATION;
prep_cfg.width = width;
prep_cfg.height = height;
prep_cfg.format = fmt;
MppEncCodecCfg codec_cfg;
codec_cfg.coding = type;
codec_cfg.width = width;
codec_cfg.height = height;
codec_cfg.fps_in = fps;
codec_cfg.fps_out = fps;
codec_cfg.rc_mode = MPP_ENC_RC_MODE_CBR;
codec_cfg.bps = bitrate;
codec_cfg.gop = gop;
codec_cfg.profile = MPP_PROFILE_AVC_HIGH;
MppEncRcCfg rc_cfg;
rc_cfg.change = MPP_ENC_RC_CFG_CHANGE_ALL;
rc_cfg.bits_per_frame = bitrate / fps;
rc_cfg.frm_rate = fps;
rc_cfg.max_i_prop = 30;
rc_cfg.max_qp = 40;
rc_cfg.min_qp = 20;
ret = mpi->control(ctx, MPP_ENC_SET_PREP_CFG, &prep_cfg);
ret |= mpi->control(ctx, MPP_ENC_SET_CODEC_CFG, &codec_cfg);
ret |= mpi->control(ctx, MPP_ENC_SET_RC_CFG, &rc_cfg);
ret |= mpi->control(ctx, MPP_ENC_GET_EXTRA_INFO, &extra_data);
if (ret != MPP_OK) {
qDebug() << "MPP control failed";
return -1;
}
// 打开摄像头
cv::VideoCapture cap(0);
if (!cap.isOpened()) {
qDebug() << "Failed to open camera";
return -1;
}
// 创建视频输出文件
cv::VideoWriter writer("output.mp4", cv::CAP_FFMPEG, codec, fps, cv::Size(width, height), true);
if (!writer.isOpened()) {
qDebug() << "Failed to create video file";
return -1;
}
// 开始捕获和编码
cv::Mat frame;
while (cap.read(frame)) {
// 将OpenCV的Mat转换为MppFrame
MppFrame mpp_frame;
mpp_frame = cvMatToMppFrame(frame, fmt);
// 编码并将输出写入文件
MppPacket packet;
ret = mpi->encode(ctx, mpp_frame, &packet);
if (ret == MPP_OK) {
writer.write(packet->data, packet->length);
mpi->packet_deinit(&packet);
}
// 释放MppFrame
mpp_frame_deinit(&mpp_frame);
}
// 释放MPP编码器和摄像头
mpp_destroy(ctx);
cap.release();
return a.exec();
}
```
请注意,此代码仅是演示如何使用Qt、OpenCV和MPP硬件编码来保存视频文件的简单示例。要使其在您的环境中正常工作,您可能需要对其进行修改和调整。
阅读全文