RK3588板子上利用OpenCV打开摄像头,并用MPP硬件编码后保存视频文件,C++代码示例
时间: 2024-03-26 10:39:24 浏览: 116
RK3588 RK3568 RK3566 Linux QT Opencv NPU YoloV5 摄像头实时检测
4星 · 用户满意度95%
好的,下面是在RK3588板子上利用OpenCV打开摄像头,并用MPP硬件编码后保存视频文件的C++代码示例:
```c++
#include <opencv2/opencv.hpp>
#include <rockchip/rockchip_mpp.h>
int main(int argc, char** argv) {
// 打开摄像头
cv::VideoCapture cap(0);
if (!cap.isOpened()) {
std::cerr << "Failed to open camera!" << std::endl;
return -1;
}
// 创建MPP编码器
MPP_CTX mpp_ctx = mpp_create(MPP_CTX_ENC_VCODEC);
if (!mpp_ctx) {
std::cerr << "Failed to create MPP context!" << std::endl;
return -1;
}
// 配置MPP编码器
MPP_ENC_CONFIG mpp_enc_cfg;
memset(&mpp_enc_cfg, 0, sizeof(mpp_enc_cfg));
mpp_enc_cfg.format = MPP_FMT_YUV420P;
mpp_enc_cfg.width = cap.get(CV_CAP_PROP_FRAME_WIDTH);
mpp_enc_cfg.height = cap.get(CV_CAP_PROP_FRAME_HEIGHT);
mpp_enc_cfg.fps_in = 30;
mpp_enc_cfg.fps_out = 30;
mpp_enc_cfg.bitrate = 5000000;
mpp_enc_cfg.gop = 30;
mpp_enc_cfg.level = MPP_ENC_LEVEL_H264_MAIN;
mpp_enc_cfg.profile = MPP_ENC_PROFILE_H264_MAIN;
mpp_enc_cfg.rc_mode = MPP_ENC_RC_MODE_CBR;
mpp_enc_cfg.qp = 18;
mpp_enc_cfg.bps_target = mpp_enc_cfg.bitrate;
mpp_enc_cfg.bps_max = mpp_enc_cfg.bitrate;
mpp_enc_cfg.bps_min = mpp_enc_cfg.bitrate;
mpp_enc_cfg.qp_max = 50;
mpp_enc_cfg.qp_min = 10;
mpp_enc_cfg.qp_step = 2;
mpp_enc_cfg.vbv_size = mpp_enc_cfg.bitrate / 30;
mpp_enc_cfg.vbv_time = 1;
mpp_enc_cfg.vbv_delay = 0;
int ret = mpp_init(mpp_ctx, MPP_CTX_ENC_VCODEC, &mpp_enc_cfg);
if (ret) {
std::cerr << "Failed to initialize MPP encoder!" << std::endl;
return -1;
}
// 创建视频文件
cv::VideoWriter writer("output.mp4",
cv::VideoWriter::fourcc('a', 'v', 'c', '1'),
cap.get(CV_CAP_PROP_FPS),
cv::Size(cap.get(CV_CAP_PROP_FRAME_WIDTH), cap.get(CV_CAP_PROP_FRAME_HEIGHT)));
if (!writer.isOpened()) {
std::cerr << "Failed to create video file!" << std::endl;
return -1;
}
// 循环读取摄像头帧并进行编码
cv::Mat frame;
MPP_FRAME mpp_frame;
while (cap.read(frame)) {
mpp_frame = mpp_frame_create_from_stdfb(frame.ptr(0), frame.step[0],
frame.ptr(1), frame.step[1],
frame.ptr(2), frame.step[2],
frame.cols, frame.rows);
ret = mpp_encode(mpp_ctx, mpp_frame);
if (ret) {
std::cerr << "Failed to encode frame!" << std::endl;
return -1;
}
MPP_PACKET mpp_packet = mpp_packet_get(mpp_ctx);
if (mpp_packet) {
writer.write(frame);
mpp_packet_put(mpp_packet);
}
mpp_frame_deinit(&mpp_frame);
}
// 释放资源
cv::destroyAllWindows();
mpp_destroy(mpp_ctx);
writer.release();
return 0;
}
```
请注意,这只是一个简单的示例,您可能需要根据实际情况对其进行修改。如果您有任何问题或疑问,请随时问我。
阅读全文