RK3288 Debian下OpenCV通过Gstreamer解码RTSP视频流

本文介绍如何在RK3288主板Debian9.13系统上利用Gstreamer进行CPU硬解,实现网络摄像头视频流的高效解码。文章提供了详细的依赖包安装步骤、OpenCV编译配置方法及测试代码,展示了Gstreamer在4K画面解码上的优异性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

在RK3288主板Debian 9.13系统上想调用CPU硬解进行网络摄像头视频流进行解码,本来尝试用FFmpeg+Mpp方式进行,但ffmpeg集成mpp的解码器,解码后的格式为AV_PIX_FMT_DRM_PRIME,也就是 DRM 帧数据,要进行图像识别还得通过CPU转码为RGB或BGR格式。按照这个过程下来,光解码CPU的占用率就很高。。。后来在Rockchip的wiki_Mpp上看到,对Mpp有如下的一段说明:

We offer the Gstreamer Rockchip, it is a standard Gstreamer plugin for the hardware decoder and encoder at Rockchip platform. I would suggest all the user in the Linux don’t develop the MPP directly unless you know what you are doing. Choose Gstreamer rocckchip in you convenience.

简而言之就是建议Linux下的用户不要直接使用MPP进行开发,推荐用标准的Gstreamer插件。了解到,原来OpenCV可以集成Gstreamer进行使用。运行Gstreamer的例子发现,RK3288解码4K画面是很流畅。

  • Debian GNU/Linux 9.13 (stretch) armv7l
  • OpenCV 3.4.11
  • Gstreamer 1.10.4

Gstreamer解码RTSP命令

#!/bin/sh
gst-launch-1.0 rtspsrc location=rtsp://192.168.31.163:8554/ ! \
        ! rtph264depay ! h264parse ! mppvideodec ! rkximagesink sync=false

安装需要的依赖包

apt-get update
apt-get install -y libgstreamer-plugins-base1.0-dev \
		libpng16-16 \
        build-essential \
        cmake \
        git \
        pkg-config \
        libjpeg-dev \
		libgtk2.0-dev \
        libv4l-dev \
        libatlas-base-dev \
        gfortran \
        libhdf5-dev \
        libtiff5-dev \
		libtbb-dev \
		libeigen3-dev

编译OpenCV

cd3.4.11.zip文件目录下,执行如下命令:

unzip 3.4.11.zip # 解压zip压缩包
cd opencv-3.4.11 # 切换到源码包目录
mkdir build && cd build # 创建build目录并切换进去
cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D INSTALL_C_EXAMPLES=OFF -D WITH_GSTREAMER=ON -D WITH_GTK_2_X=ON -D WITH_GTHREAD=ON -D WITH_TBB=ON -D WITH_OPENGL=ON  .. # 配置opencv 此处注意有两个点

如果配置成功的话,应该会有如下输出:

--   OpenCV modules:
--     To be built:                 calib3d core dnn features2d flann highgui imgcodecs imgproc ml objdetect photo shape stitching superres ts video videoio videostab
--     Disabled:                    world
--     Disabled by dependency:      -
--     Unavailable:                 cudaarithm cudabgsegm cudacodec cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev java js python2 python3 viz
--     Applications:                tests perf_tests apps
--     Documentation:               NO
--     Non-free algorithms:         NO
-- 
--   GUI: 
--     GTK+:                        YES (ver 2.24.31) # 识别到GTK+ 2.0 如果没有会无法显示
--       GThread :                  YES (ver 2.50.3)
--       GtkGlExt:                  NO
--     OpenGL support:              NO
--     VTK support:                 NO
-- 
--   Media I/O: 
--     ZLib:                        /usr/lib/arm-linux-gnueabihf/libz.so (ver 1.2.8)
--     JPEG:                        /usr/lib/libjpeg.so (ver 62)
--     WEBP:                        build (ver encoder: 0x020f)
--     PNG:                         /usr/lib/arm-linux-gnueabihf/libpng.so (ver 1.6.28)
--     TIFF:                        /usr/lib/arm-linux-gnueabihf/libtiff.so (ver 42 / 4.0.8)
--     JPEG 2000:                   build (ver 1.900.1)
--     OpenEXR:                     build (ver 2.3.0)
--     HDR:                         YES
--     SUNRASTER:                   YES
--     PXM:                         YES
-- 
--   Video I/O:
--     DC1394:                      NO
--     FFMPEG:                      YES # 系统自带了FFMPEG 所以会开启
--       avcodec:                   YES (ver 58.35.100)
--       avformat:                  YES (ver 58.20.100)
--       avutil:                    YES (ver 56.22.100)
--       swscale:                   YES (ver 5.3.100)
--       avresample:                YES (ver 4.0.0)
--     GStreamer:                   YES # 识别到Gstreamer
--       base:                      YES (ver 1.10.4)
--       video:                     YES (ver 1.10.4)
--       app:                       YES (ver 1.10.4)
--       riff:                      YES (ver 1.10.4)
--       pbutils:                   YES (ver 1.10.4)
--     libv4l/libv4l2:              NO
--     v4l/v4l2:                    linux/videodev2.h
-- 
--   Parallel framework:            TBB (ver 4.3 interface 8006)
-- 
--   Trace:                         YES (with Intel ITT)
-- 
--   Other third-party libraries:
--     Lapack:                      NO
--     Eigen:                       YES (ver 3.3.2)
--     Custom HAL:                  NO
--     Protobuf:                    build (3.5.1)
-- 
--   OpenCL:                        YES (no extra features)
--     Include path:                /opencv-3.4.11/3rdparty/include/opencl/1.2
--     Link libraries:              Dynamic load
-- 
--   Python (for build):            /usr/bin/python2.7
-- 
--   Java:                          
--     ant:                         NO
--     JNI:                         NO
--     Java wrappers:               NO
--     Java tests:                  NO
-- 
--   Install to:                    /usr/local
-- -----------------------------------------------------------------
-- 
-- Configuring done
-- Generating done
-- Build files have been written to: */opencv-3.4.11/build

执行如下命令进行编译安装

make -j4 # 编译
make install # 安装opencv库到/usr/local下

配置OpenCV

cd /etc/ld.so.conf.d/ # 切换目录
touch opencv.conf # 新建opencv配置文件
echo /usr/local/lib/ > opencv.conf # 填写opencv编译后库所在的路径
sudo ldconfig # 使配置文件生效

测试代码

#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/types_c.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/time.h>
#include <iconv.h>
#include <sstream>
#include <string>
#include <string.h>

using namespace std;
using namespace cv;

int main()
{
    string gsurl = "rtspsrc location=rtsp://192.168.31.163:8554/ latency=0 ! rtph264depay ! h264parse ! mppvideodec ! videoconvert ! video/x-raw,format=(string)BGR  ! appsink sync=false";  // 也可以使用 rgaconvert
    VideoCapture cap = VideoCapture(gsurl,cv::CAP_GSTREAMER);
    if(!cap.isOpened())
    {
        std::cout<<"cannot open captrue..."<<std::endl;
        return 0;
    }

    int fps = cap.get(5);
    cout<<"fps:"<<fps<<endl;
    Mat frame;
    bool readreturn = false;
    while(1)
    {  
        readreturn = cap.read(frame);

        imshow("RTSP",frame);
        if (cvWaitKey(30) == 27) 
        {
            cout << "Esc key is pressed by user" << endl;
            break;
        }
    }

    cap.release();
    return 0;
}

使用如下命令进行编译

g++ main.cpp `pkg-config --cflags --libs opencv`
[ WARN:0@6.920] global cap_gstreamer.cpp:2824 cv::handleMessage OpenCV | GStreamer warning: your GStreamer installation is missing a required plugin: Audio Video Interleave (AVI) demuxer [ WARN:0@6.920] global cap_gstreamer.cpp:2840 cv::handleMessage OpenCV | GStreamer warning: Embedded video playback halted; module uridecodebin0 reported: Your GStreamer installation is missing a plug-in. [ WARN:0@6.921] global cap_gstreamer.cpp:1698 cv::GStreamerCapture::open OpenCV | GStreamer warning: unable to start pipeline [ WARN:0@6.921] global cap_gstreamer.cpp:1173 cv::GStreamerCapture::isPipelinePlaying OpenCV | GStreamer warning: GStreamer: pipeline have not been created [ WARN:0@7.073] global cap_msmf.cpp:935 CvCapture_MSMF::initStream Failed to set mediaType (stream 0, (800x600 @ 49.885) MFVideoFormat_RGB32(codec not found) 视频处理完成,每帧已保存到 ./input 文件夹中。 E:\DHP\code\ruanzhu4.py:109: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature. model.load_state_dict(torch.load(args.model)) 0it [00:00, ?it/s] [ WARN:0@7.681] global cap_gstreamer.cpp:2824 cv::handleMessage OpenCV | GStreamer warning: your GStreamer installation is missing a required plugin: Audio Video Interleave
04-02
### 使用 Python 和 GStreamer 播放 RTSP 视频流 为了在 Python 中利用 GStreamer 实现 RTSP 流的播放,需先确认已安装必要的软件包和库。这通常涉及安装 `gstreamer` 及其插件集,以及 Python 的绑定工具如 `PyGObject`。 #### 安装依赖项 可以通过包管理器安装所需的组件,在基于 Debian 或 Ubuntu 的 Linux 发行版上可以执行如下命令: ```bash sudo apt-get install gstreamer1.0-tools gstreamer1.0-plugins-base gstreamer1.0-plugins-good python3-gi gir1.2-gst-1.0 ``` 对于其他操作系统,则应查找对应的安装指南并遵循之[^1]。 #### 创建播放管道 创建一个简单的 Python 脚本来初始化 GStreamer 并设置好用于接收 RTSP 数据源的 pipeline。下面给出了一段示范性的代码片段,它展示了怎样构建这样一个 pipeline 来连接到指定 URL 提供的服务端点,并启动视频渲染流程。 ```python import gi gi.require_version('Gst', '1.0') from gi.repository import Gst, GObject def main(): # 初始化 GStreamer 库 Gst.init(None) # 构建 GSTREAMER PIPELINE 字符串 rtsp_url = "rtsp://admin:12345@172.6.22.234:554/Streaming/Channels/2602" # 这里使用了 playbin 插件简化了整个过程;也可以手动定义更复杂的 pipelines 如果有特殊需求的话。 pipeline_str = f"playbin uri={rtsp_url}" # 解析字符串形式的 pipeline 描述成实际的对象实例 pipeline = Gst.parse_launch(pipeline_str) # 开始运行该 media player instance (pipeline) pipeline.set_state(Gst.State.PLAYING) try: loop = GObject.MainLoop() loop.run() # 阻塞直到遇到错误或者其他终止条件 except KeyboardInterrupt: pass finally: # 清理资源前停止 playback session. pipeline.send_event(Gst.Event.new_eos()) pipeline.get_bus().timed_pop_filtered( Gst.CLOCK_TIME_NONE, Gst.MessageType.EOS | Gst.MessageType.ERROR ) # 设置状态回至 NULL 表明结束会话 pipeline.set_state(Gst.State.NULL) if __name__ == "__main__": main() ``` 这段脚本实现了基本功能——即向给定 IP 地址发送请求获取实时音视频数据并通过图形界面展示出来。注意这里的 RTSP URI 是针对特定品牌型号摄像机配置的例子,请根据实际情况调整路径参数以匹配目标设备的要求[^2]。
评论 20
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值