ROS教程(五):OpenCV调用USB摄像头并发布topic(详细图文)

目录

前言

一、创建包

二、创建节点

三、修改CMakeLists.txt及package.xml

四、编译运行

总结(最重要的)


​​​​​​​

前言

ros教程:OpenCV调用usb摄像头

创建功能包教程在ROS教程(三):创建程序包及节点(图文)已讲解,本文便不再细讲。


一、创建包

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

cd catkin_ws/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;
}

三、修改CMakeLists.txt及package.xml

打开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

先启动ros

roscore

开两个终端分别启动节点

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

完成!

总结(最重要的)


 

ROS教程(五):OpenCV调用USB摄像头并发布topic(详细图文)_第1张图片

ROS教程(五):OpenCV调用USB摄像头并发布topic(详细图文)_第2张图片

你可能感兴趣的:(ROS,ROS,opencv,usb摄像头)