ROS 节点:使用 YOLOv8 进行目标检测并计算距离和角度
import rospy
from darknet_ros_msgs.msg import BoundingBoxes
import numpy as np
class ObjectDetection:
def __init__(self):
rospy.init_node('object_detection_node', anonymous=True)
self.bounding_box_sub = rospy.Subscriber('/yolov8/BoundingBoxes', BoundingBoxes, self.on_bounding_boxes,
queue_size=1)
def on_bounding_boxes(self, message):
'''回调函数:处理收到的边框消息'''
# 存储边框消息
self.bounding_boxes = message
# 解析目标检测结果
num_boxes = len(message.bounding_boxes)
object_detected = False
for i in range(num_boxes):
if message.bounding_boxes[i].Class == '1':
object_detected = True
x_min = message.bounding_boxes[i].xmin
x_max = message.bounding_boxes[i].xmax
y_min = message.bounding_boxes[i].ymin
y_max = message.bounding_boxes[i].ymax
break
if object_detected:
x_center = (x_min + x_max) / 2
y_center = (y_min + y_max) / 2
self.dist_1 = 1 / (x_center + 1e-6) # 与目标距离的倒数作为距离信息
self.beta3 = -np.arctan((y_center - 240) / x_center) # 与目标中心点连线与车辆前进方向的夹角
alpha = 0.2 # 平滑参数
self.dist_1 = alpha * x_center + (1 - alpha) * self.dist_1 # 距离指数移动平均
self.beta3 = alpha * self.beta3 + (1 - alpha) * self.beta3 # 角度指数移动平均
else:
self.dist_1 = 0
self.beta3 = 0
if __name__ == '__main__':
detection = ObjectDetection()
rospy.spin()
该代码创建了一个名为 object_detection_node 的 ROS 节点,订阅 /yolov8/BoundingBoxes 主题以获取目标检测结果。回调函数 on_bounding_boxes 会处理接收到的消息,解析目标检测结果,并计算目标的距离和与车辆前进方向的夹角。该代码还实现了距离和角度的指数移动平均,以平滑结果。
原文地址: https://www.cveoy.top/t/topic/oSI6 著作权归作者所有。请勿转载和采集!