一、前提条件
1.ubuntu ros2 humble
2.sudo apt-get install ffmpeg libavformat-dev libavcodec-dev libavutil-dev libswscale-dev
二、简单代码
rtmp_player_node.cpp
#include <chrono>
#include <cstdio>
#include <rclcpp/rclcpp.hpp>
#include <opencv2/opencv.hpp>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/msg/image.hpp>
#include <std_msgs/msg/string.hpp>
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
extern "C" {
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libavutil/avutil.h"
#include "libswscale/swscale.h"
}
using namespace std::chrono_literals;
class VideoGrab : public rclcpp::Node
{
public:
VideoGrab() : Node("video_grab")
{
image_publisher_ = this->create_publisher<sensor_msgs::msg::Image>("/video_stream", 5);
avformat_network_init();
if (avformat_open_input(&formatContext_, "rtsp://user:pass@ip:port", NULL, NULL) != 0)
{
std::cout << "Unable to open RTSP stream" << std::endl;
return;
}
if (avformat_find_stream_info(formatContext_, NULL) < 0)
{
std::cout << "Unable to retrieve stream information" << std::endl;
return;
}
cv::Mat image_;
rtsp_th_ = std::make_shared<std::thread>(std::bind(&VideoGrab::run, this));
rtsp_th_->detach();
pub_th_ = std::make_shared<std::thread>(std::bind(&VideoGrab::publish, this));