(七)ROS使用OpenCV讀取影象併發布影象訊息在rviz中顯示
阿新 • • 發佈:2019-01-29
思路:
(1)使用opencv讀取本地影象
(2)呼叫cv_bridge::CvImage().toImageMsg()將本地影象傳送給rviz顯示
1.使用opencv讀取本地影象併發布影象訊息
(1)利用catkin新建一個工程叫rosopencv,並進行初始化
mkdir -p rosopencv/src
cd rosopencv/src
catkin_create_pkg rosopencv sensor_msgs cv_bridge roscpp std_msgs image_transport
cd ..
catkin_make
source ./devel/setup.bash
(2)編輯主函式程式碼
主函式rosopencv.cpp內容如下
#include <ros/ros.h>
#include <image_transport/image_transport.h>
#include <opencv2/highgui/highgui.hpp>
#include <cv_bridge/cv_bridge.h>
#include <stdio.h>
int main(int argc, char** argv)
{
ros::init(argc, argv, "image_publisher");
ros: :NodeHandle nh;
image_transport::ImageTransport it(nh);
image_transport::Publisher pub = it.advertise("camera/image", 1);
cv::Mat image = cv::imread("/home/topeet/test.jpg", CV_LOAD_IMAGE_COLOR);
if(image.empty()){
printf("open error\n");
}
sensor_msgs::ImagePtr msg = cv_bridge::CvImage (std_msgs::Header(), "bgr8", image).toImageMsg();
ros::Rate loop_rate(5);
while (nh.ok()) {
pub.publish(msg);
ros::spinOnce();
loop_rate.sleep();
}
}
我的opencv2.4.11安裝路徑在/usr/local目錄下
(3)編輯CmakeLists.txt
在工程目錄下的/src/rosopencv/src/CmakeLists.txt中加入如下內容
add_executable(rosopencv src/rosopencv.cpp)
INCLUDE_DIRECTORIES(/usr/local/include)
link_directories(/usr/local/lib)
TARGET_LINK_LIBRARIES(rosopencv libopencv_calib3d.so libopencv_core.so
libopencv_features2d.so libopencv_flann.so libopencv_highgui.so libopencv_imgproc.so libopencv_ml.so libopencv_objdetect.so libopencv_photo.so libopencv_video.so libopencv_videostab.so)
target_link_libraries(rosopencv ${catkin_LIBRARIES})
告訴Cmake 庫函式標頭檔案,庫函式路徑,庫函式名字,由於我安裝了很多個版本的opencv,因此直接用暴力方法指導庫函式名稱。其實有一種方法可以很簡單的設定呼叫哪種版本的opencv庫,參考
http://blog.csdn.net/u012816621/article/details/51732932
方法是在CMakeLists.txt中用set語句設定OpenCV_DIR的值。這個路徑是指定opencv版本的安裝路徑下的share/OpenCV(安裝opencv 時會自動生成4個資料夾bin include lib share,share資料夾的作用原來是這樣的!)
因此,簡單版的CmakeLists.txt如下。
set(OpenCV_DIR /usr/local/share/OpenCV)
message(STATUS " version: ${OpenCV_VERSION}")
find_package(OpenCV REQUIRED)
add_executable(rosopencv src/rosopencv.cpp)
include_directories(${OpenCV_INCLUDE_DIRS})
target_link_libraries(cmaketest ${OpenCV_LIBS})
2編譯和執行
編譯
cd ~/dev/workspace/rosopencv
catkin_make
執行
rosrun rosopencv rosopencv
輸入
rostopic echo /camera/image
全是數字。
3.在rviz 中顯示
rosrun rviz rviz
左邊點選add
選中image
在image的topic選項中選
/camera/image