在ROS下使用openCV
1.建立ROS工作环境
mkdir -p ~/catkin_ws/src //建立项目目录,同时生成src文件夹 cd ~/catkin_ws/ //进入项目目录 catkin_make //编译项目,即使什么文件也没有也可以编译
2.建立包
本例中包名为“opencvExercise”
cd ~/catkin_ws/src catkin_create_pkg opencvExercise std_msgs rospy roscpp cv_bridge sensor_msgs image_transport
3.源代码封装
#include <ros/ros.h> #include<image_transport/image_transport.h> #include<cv_bridge/cv_bridge.h> #include<sensor_msgs/image_encodings.h> cv_bridge::CvImagePtr cv_ptr; class ImageConverter { private: ros::NodeHandle nh_; //用于将msg信息转换为openCV中的Mat数据 image_transport::ImageTransport it_; //订阅摄像头发布的信息 image_transport::Subscriber image_sub_; public: ImageConverter() : it_(nh_) { //设置订阅摄像机 image_sub_ = it_.subscribe("/usb_cam/image_raw", 1, &ImageConverter::imageCb, this); } ~ImageConverter(){ cv::destroyWindow(OPENCV_WINDOW); } //收到摄像机后的回调函数 void imageCb(const sensor_msgs::ImageConstPtr& msg){ try{ //将收到的消息使用cv_bridge转移到全局变量图像指针cv_ptr中,其成员变量image就是Mat型的图片 cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8); } catch (cv_bridge::Exception& e){ ROS_ERROR("cv_bridge exception: %s", e.what()); return; } //处理图片信息 myCode(); } //你的代码可以移植在此处 int myCode(){ Mat img=cv_ptr->image; imshow("win",img); return 0; } }; int main(int argc, char** argv) { ros::init(argc, argv, "image_converter"); ImageConverter ic; //循环等待 ros::spin(); return 0; }
需要注意的是ROS中发布的消息是不支持图片的,所以需要image_transport的支持。但是这个包和openCV的格式不兼容,所以需要cv_bridge做格式变换。最后照相机发布的消息类型是sensor_msgs包中的。
4.CMakeLists.txt
添加在文件末尾
AUX_SOURCE_DIRECTORY(src/. DIR_SRCS) ADD_EXECUTABLE(cylinder ${DIR_SRCS} ) target_link_libraries(cylinder ${catkin_LIBRARIES}) add_dependencies(cylinder robot_vision_generate_messages_cpp)
相关推荐
learningCV 2020-11-10
learningCV 2020-08-25
huang00 2020-08-21
wangdaren 2020-08-15
BeanJoy 2020-07-28
csdmeb 2020-06-25
wangdaren 2020-06-14
pythonxuexi 2020-06-13
woniulx0 2020-06-13
greent00 2020-06-10
liangzuojiayi 2020-06-09
greent00 2020-06-09
csdmeb 2020-06-08
BeanJoy 2020-06-06
lihuifei 2020-06-05
wangdaren 2020-06-03
wangdaren 2020-05-31
greent00 2020-05-30