ROS系列——将onvif协议摄像头通过OpenCV读取图像,并转换为ROS Topic发布
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文件
<launch>
<group ns ="first">
<param name="cols" type="int" value="1280" />
<param name="rows" type="int" value="720" />
<param name="FPS" type="int" value="20" />
<param name="rate" type="int" value="200" />
<param name="topic_name" type="string" value="camera/image" />
<param name="rtsp" type="string" value="rtsp://192.168.1.101:554/user=admin_password=tlJwpbo6_channel=1_stream=0" />
<node pkg="trans_mat2topic" type="trans_mat2topic" name="trans_mat2topic_first" output="screen" />
</group >
<group ns ="second">
<param name="cols" type="int" value="1280" />
<param name="rows" type="int" value="720" />
<param name="FPS" type="int" value="20" />
<param name="rate" type="int" value="200" />
<param name="topic_name" type="string" value="camera/image" />
<param name="rtsp" type="string" value="rtsp://192.168.1.121:554/user=admin_password=tlJwpbo6_channel=1_stream=0" />
<node pkg="trans_mat2topic" type="trans_mat2topic" name="trans_mat2topic_second" output="screen" />
</group >
<arg name="rviz" default="true" />
<group if="$(arg rviz)">
<node launch-prefix="nice" pkg="rviz" type="rviz" name="rviz" args="-d $(find trans_mat2topic)/rviz/showImage.rviz" />
</group>
</launch>
5.源代码
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/130117.html