有时候需要把目标检测输出的boundingbox发送到其他结点(比如跟踪结点)执行下游任务,因此需要在结点见发送消息,ros自带的消息类型不能满足我们的需求(有一个3d的boundingbox),需要我们自己定义消息类型。本帖是一个简单的例子,同时也是一个错误记录贴。
1. 自定义消息
#Bbox.msg
int16 x1
int16 y1
int16 x2
int16 y2
float32 conf
int8 clss
#Bboxes.msg
Header header
Bbox[] bboxes
2. 一个例子
import rospy
import ros_numpy
import numpy as np
from sensor_msgs.msg import Image
from camera.msg import Bbox
from camera.msg import Bboxes
def callback_image(msg):
frame_img = ros_numpy.numpify(msg)
frame_img = np.ascontiguousarray(frame_img[:,:,:3])
# 从目标检测模型生成boundingbox,格式为(x1,y,,x2,y2,conf,class)
det_bboxes = det.detect(frame_img)
boxes_temp = []
for det_box in det_bboxes:
# 这里必须在循环里实例化消息,否则有问题,后面会提到
bbox = Bbox()
bbox.x1,bbox.y1,bbox.x2,bbox.y2,bbox.conf,bbox.clss = det_box
boxes_temp.append(bbox)
temp_msg.header = msg.header
temp_msg.bboxes = boxes_temp
# 发布器发布消息
boxes_pub.publish(temp_msg)
rate.sleep()
def main():
rospy.init_node('detection', anonymous=True)
global rate
global det
global temp_msg
global boxes_pub
rate = rospy.Rate(20)
# 实例化目标检测器
det = Detector()
# 实例化消息
temp_msg = Bboxes()
# 定义发布器
boxes_pub = rospy.Publisher('/temp_msg', Bboxes, queue_size=1)
# 订阅 image
image_sub = rospy.Subscriber('/neuvition_image', Image, callback_image, queue_size=1, buff_size=1960*1080*3)
rospy.spin()
3. 错误记录
开始我是这么写的,把实例化Bbox消息放在循环外面
bbox = Bbox()
for det_box in det_bboxes:
bbox.x1,bbox.y1,bbox.x2,bbox.y2,bbox.conf,bbox.clss = det_box
boxes_temp.append(bbox)
但是在查看输出消息的时候发现Bboxes里是一个消息,并且是最后一个det_box的循环。
来做一个例子,我们自己定义一个det_bboxes,如下:
for i in range(3):
det_bboxes.append((i,i,i,i,0.01*i,i))
消息结果如下:
---
-
x1: 2
y1: 2
x2: 2
y2: 2
conf: 0.019999999552965164
clss: 2
-
x1: 2
y1: 2
x2: 2
y2: 2
conf: 0.019999999552965164
clss: 2
-
x1: 2
y1: 2
x2: 2
y2: 2
conf: 0.019999999552965164
clss: 2
---
根据这个结果我们可以分析出,如果实例化Bbox消息在循环外面,每次循环都会把上次的消息覆盖,并且加到list里。如果是在循环中定义bbox,输出的结果如下:
---
-
x1: 0
y1: 0
x2: 0
y2: 0
conf: 0.0
clss: 0
-
x1: 1
y1: 1
x2: 1
y2: 1
conf: 0.009999999776482582
clss: 1
-
x1: 2
y1: 2
x2: 2
y2: 2
conf: 0.019999999552965164
clss: 2
---
4. 结论
bbox消息应该是一个类似变量,而不是一个类似类的东西。比如令a=0,再令a=1就会覆盖之前的值。给bbox赋值也会覆盖上一个值,因此需要每次都重新声明一次。
5. 其他
Image <–> msg 转换使用ros_numpy来代替cv_bridge,可以参考我的上一篇博客https://blog.csdn.net/LoveJSH/article/details/126942789.