[ros] demo

 

介绍

创建一个接受图片数据,发布数值数据的rospy程序。

项目结构

└── src/
    ├── CMakeLists.txt -> /opt/ros/melodic/share/catkin/cmake/toplevel.cmake
    └── demo_detect_image/
        ├── CMakeLists.txt
        ├── msg/
        │   └── Detection.msg
        ├── package.xml
        ├── scripts/
        │   └── detect.py*
        └── src/

步骤

创建项目

mkdir -p catkin_ws/src
cd catkin_ws
catkin_make
. devel/setup.bash
cd src
catkin_create_pkg demo rospy std_msgs message_generation
cd demo

使用python3:catkin_make -DPYTHON_EXECUTABLE=/usr/bin/python3

message_generation:用于msg文件生成代码,以便用于后续直接导入。(可以在devel/lib/python2.7/dist-packages/demo/msg/_Detection.pydevel/include/demo/Detection.h看到生成的代码文件。)

添加msg文件

mkdir -p msg/
vim msg/Detection.msg
float32[] pos
uint32 classes
float32 scores

修改CMakeLists.txt

vim CMakeLists.txt
## Generate messages in the 'msg' folder
add_message_files(
  FILES
  Detection.msg
#   Message1.msg
#   Message2.msg
)
## Generate added messages and services with any dependencies listed here
generate_messages(
  DEPENDENCIES
  std_msgs
)

代码

mkdir scripts/
vim scripts/detect.py
#!/usr/bin/env python3
#coding=utf-8

import rospy
from sensor_msgs.msg import Image
from demo.msg import Detection  # generate_messages的作用

import numpy as np


class Detect:
    
    def __init__(self):
        rospy.init_node('image_detect_node')
        rospy.Subscriber('/image_raw', Image, self.callback)
        # rospy.Subscriber('/camera/color/image_raw', Image, self.callback)
        self.pub = rospy.Publisher('image_detection', Detection , queue_size=10)

    def callback(self, image):
        img = np.frombuffer(image.data, dtype=np.uint8).reshape((480, 640, 3))
        # rospy.loginfo(img)
        self.pub.publish(Detection([1., 2.], 10, 2.))

    def start(self):
        rospy.spin()


if __name__ == "__main__":
    Detect().start()

test

需要为python文件添加可执行权限:

chmod +x detect.py

编译:

catkin_make all clean
catkin_make

执行:

rosrun demo detect.py

查看返回数据:

rostopic echo /image_detection