ROS 发布和订阅opencv调用的usb摄像头图像

新建目录(有必要的话)

mkdir -p catkin_ws/src
cd catkin_ws
catkin_make

新建包 usb_cam,其中附加的依赖有std_msgs(消息传递),roscpp(c++),cv_bridge(ros和opencv图像转换),sensor_msgs(传感器消息),image_transport(图像编码传输)

cd src
catkin_create_pkg usb_cam std_msgs roscpp cv_bridge sensor_msgs image_transport

在usb_cam/src文件夹中添加两个cpp,一个发布图像消息img_publisher.cpp,一个接收并查看图像消息img_viewer.cpp

img_publisher.cpp

#include 
#include 
#include 
#include 
#include 
#include 

int main(int argc, char** argv)
{
  ros::init(argc, argv, "img_publisher");
  ros::NodeHandle nh;
  image_transport::ImageTransport it(nh);
  image_transport::Publisher pub = it.advertise("camera/image", 1);

  cv::VideoCapture cap;
  cv::Mat frame;
  int deviceID=0;
  if(argc>1)
	deviceID=argv[1][0]-'0';
  int apiID=cv::CAP_ANY;
  cap.open(deviceID+apiID);
  if(!cap.isOpened()){
	std::cerr<<"ERROR! Unable to open camera"<

img_viewer.cpp

#include 
#include 
#include 
#include 

void imageCallback(const sensor_msgs::ImageConstPtr& msg)
{
  try
  {
    cv::imshow("view", cv_bridge::toCvShare(msg, "bgr8")->image);
  }
  catch (cv_bridge::Exception& e)
  {
    ROS_ERROR("Could not convert from '%s' to 'bgr8'.", msg->encoding.c_str());
  }
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, "img_viewer");
  ros::NodeHandle nh;
  cv::namedWindow("view");
  cv::startWindowThread();
  image_transport::ImageTransport it(nh);
  image_transport::Subscriber sub = it.subscribe("camera/image", 1, imageCallback);
  ros::spin();
  cv::destroyWindow("view");
  return 0;
}

编辑usb_cam文件夹下的CMakeLists.txt,可以看到前面加的ros的依赖库已经在里面了,这里只需加上opencv的依赖项,然后添加可执行程序并链接相应的库

find_package(catkin REQUIRED COMPONENTS
  cv_bridge
  image_transport
  roscpp
  sensor_msgs
  std_msgs
)
find_package(OpenCV REQUIRED)

include_directories(
  ${catkin_INCLUDE_DIRS}
  ${OpenCV_INCLUDE_DIRS}
)

add_executable(img_publisher src/img_publisher.cpp)
add_executable(img_viewer src/img_viewer.cpp)

target_link_libraries(img_publisher ${catkin_LIBRARIES} ${OpenCV_LIBS})
target_link_libraries(img_viewer ${catkin_LIBRARIES} ${OpenCV_LIBS})

然后在package.xml中添加

opencv2
opencv2
opencv2

然后就可以进行编译

cd ~/catkin_ws
catkin_make

最后进行测试

第一个终端启动

roscore

第二个终端发布消息

source ~/catkin_ws/devel/setup.bash
rosrun usb_cam img_publisher

第三个终端订阅消息

source ~/catkin_ws/devel/setup.bash
rosrun usb_cam img_viewer

完成。

或者使用launch文件同时打开两个节点

在项目目录下新建launch子文件夹,并在其中创立文件openCamera.launch



  

  

然后同样的,在启动roscore后,打开新的终端,

source ~/catkin_ws/devel/setup.bash
roslaunch usb_cam openCamera.launch

按ctrl+c可关闭ros服务。如果没反应,可能是终端的快捷键变动过,可以试下ctrl+shift+c或者重置终端设置。

你可能感兴趣的:(ROS,Opencv,c++,摄像头调用)