ROS系列——将onvif协议摄像头通过OpenCV读取图像,并转换为ROS Topic发布,附带源代码

ROS系列——将onvif协议摄像头通过OpenCV读取图像,并转换为ROS Topic发布

  • 1.说明
  • 2.部分依赖
  • 3.关键代码
  • 4.launch文件
  • 5.源代码

1.说明

通过OpenCV库打开网络摄像头,获取图像,并将其转换为指定Topic的话题发布,项目实现了两台网络摄像头的启动以及话题发布。
注:如需要获取程序中需要的rtsp,即std::string rtsp = “rtsp://192.168.1.101:554/user=admin_password=tlJwpbo6_channel=1_stream=0”; 可参见另一篇文章 文章链接

2.部分依赖

1)Ubuntu 18.04
2)ROS版本为melodic
3)OpenCV库版本为 4.5.3

3.关键代码

忽略头文件,主函数只展示关键代码

std::mutex mymutex;
std::atomic_bool isOpen;
cv::VideoCapture capture;

int openCamera(std::string camId, int FPS)
{
	capture.open(camId);
    capture.set(cv::CAP_PROP_FPS, FPS);
	isOpen = capture.isOpened();
    if (isOpen == false)
	{
        std::cout << "Failed to open camera with index " << camId << std::endl;
        return -1;
    }
    std::cout << "Successed open camera with index " << camId << std::endl;
    return 1;
}

int getAndPubImage(int rows, int clos, ros::NodeHandle nh, image_transport::Publisher image_pub, std::string mytopic_name, ros::Rate loop_rate)
{
    cv::Mat frame_image(rows, clos, CV_8UC3);
    image_transport::ImageTransport it(nh);
    image_pub = it.advertise(mytopic_name, 1);
    while (nh.ok())
    {
        capture >> frame_image;
        if (mymutex.try_lock()) 
        {
            sensor_msgs::ImagePtr image_msg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", frame_image).toImageMsg();
            mymutex.unlock();
            image_pub.publish(image_msg);
            loop_rate.sleep();
        }
    }  
}

int main(int argc, char **argv)
{
    // ...................省略部分代码
    //关键代码
	std::string rtsp = "rtsp://192.168.1.101:554/user=admin_password=tlJwpbo6_channel=1_stream=0";
	//  ...................省略部分代码
    ret = openCamera(rtsp, FPS);
    if(ret ==1)
    {
        getAndPubImage(rows, clos, nh, image_pub, topic_name, loop_rate);
    }
    else if(ret == -1)
    {
        return -1;
    }
    capture.release();
    return 0;
}

4.launch文件

 
    
        
        
        
        
        
        

         
    

    
        
        
        
        
        
        

         
    

    
    
        
    

5.源代码

源代码下载链接

你可能感兴趣的:(ROS,OpenCV,opencv,人工智能,计算机视觉)