本文是利用Visp_ros中的一个例程 tutorial-ros-grabber来实现图像的获取,这个例程的使用需要先手动完成visp、visp_ros、vision_visp的安装,安装方法可参考这篇博文。完成基础功能包的安装之后,就可以尝试实现该例程了。
  首先,需要有一个USB摄像头并与电脑相连(笔记本电脑自带摄像头应该也可以),并安装ROS环境下的usb_cam功能包,安装过程如下
cd catkin_ws/src
git clone https://github.com/bosch-ros-pkg/usb_cam.git  
cd ..  
catkin_make

然后source一下

source ~/catkin_ws/devel/setup.bash
source ~/catkin_ws/install/setup.bash

接下来,编译例程源码

cd ~/catkin_ws/src/visp_ros/tutorial/grabber/ros
cmake .
make

 编译完成后,运行launch文件

roslaunch camera-usb.launch 

 此时摄像头已经被调用起来了,但是还没有显示。打开另一个终端,执行以下指令

cd ~/catkin_ws/src/visp_ros/tutorial/grabber/ros
./tutorial-ros-grabber  --use-camera-info

运行结果如下图所示

在这里插入图片描述

点击一下鼠标,例程就会自动退出。例程的代码如下

//! \example tutorial-ros-grabber.cpp
#include <visp/vpDisplayX.h>
#include <visp/vpImage.h>
#include <visp_ros/vpROSGrabber.h>

int main(int argc, const char** argv)
{
  try {
    bool opt_use_camera_info = false;//初始化opt_use_camera_info为false
    for (int i=0; i<argc; i++) {
      if (std::string(argv[i]) == "--use-camera-info")
        //如果在运行./tutorial-ros-grabber时后面带有--use-camera-info,opt_use_camera_info就会置为True
        opt_use_camera_info = true; 
      else if (std::string(argv[i]) == "--help") {
        std::cout << "Usage: " << argv[0]
                  << " [--use-camera-info] [--help]"
                  << std::endl;
        return 0;
      }
    }
    //输出opt_use_camera_info信息
    std::cout << "Use camera info: " << ((opt_use_camera_info == true) ? "yes" : "no") << std::endl;
    //vpImage<unsigned char> I; // Create a gray level image container
    vpImage<vpRGBa> I; // 创建一个RGB图像容器
    //! [Construction]
    vpROSGrabber g; // 创建一个基于ROS的捕捉器
    //! [Construction]

    //! [Setting camera topic]
    g.setImageTopic("/camera/image_raw");//获取摄像头图像话题
    //! [Setting camera topic]
    //! [Setting camera info]
    if (opt_use_camera_info) {
      g.setCameraInfoTopic("/camera/camera_info");//获取相机信息话题
      g.setRectify(true);
    }
    //! [Setting camera info]

    //! [Opening]
    g.open(I);
    //! [Opening]
    //输出图像尺寸
    std::cout << "Image size: " << I.getWidth() << " " << I.getHeight() << std::endl;

#ifdef VISP_HAVE_X11
    vpDisplayX d(I);
#else
    std::cout << "No image viewer is available..." << std::endl;
#endif

    while(1) {
      //! [Acquisition]
      g.acquire(I);//获取到图像
      //! [Acquisition]
      vpDisplay::display(I);//显示图像
      vpDisplay::displayText(I, 20, 20, "A click to quit...", vpColor::red);//在图像左上角显示一句话"A click to quit..."
      vpDisplay::flush(I);
      if (vpDisplay::getClick(I, false))
        break;//如果得到鼠标的点击指令,就退出循环,结束程序
    }
  }
  catch(vpException e) {
    std::cout << "Catch an exception: " << e << std::endl;
  }
}