我的代码定义了一个 ROS 节点,用于使用 YOLO 算法在图像中进行对象检测,特别是从指定文件路径加载的 YOLO 模型。该节点订阅了广播图像的 ROS 主题 (/camera/color/image_raw)。收到图像后,会触发回调函数,使用 CvBridge 将 ROS 图像消息转换为 OpenCV 图像格式。然后该图像由 YOLO 模型处理以检测对象。结果(包括检测到的对象框)将打印到控制台。为了防止连续处理和重新处理图像,在处理第一个图像后设置一个标志(image_processed)。此外,处理后的图像将保存到指定的文件夹(临时)。该节点保持活动状态,侦听新图像,直到手动关闭。
#!/usr/bin/python3
import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
import cv2
import os
from ultralytics import YOLO
class Node(object):
def __init__(self):
self.yolo_model = YOLO('/home/user/catkin_ws/src/run_folder/content/runs/obb/train/weights/best.pt')
self.br = CvBridge()
self.image_processed = False # Flag to indicate if the image has been processed
# Subscribe to the ROS topic that publishes images
rospy.Subscriber("/camera/color/image_raw", Image, self.callback)
def callback(self, msg):
if not self.image_processed: # Process only if no image has been processed yet
image = self.br.imgmsg_to_cv2(msg) # Convert ROS Image message to OpenCV image
# Perform object detection with YOLO
results = self.yolo_model.predict(image, show=True)
for r in results[0]:
print("---------------------------")
print(r.boxes)
# Save the image after processing it for the first time
self.save_image(image, 'temporary')
self.image_processed = True # Set the flag to True to avoid re-processing
def save_image(self, image, folder_name):
if not os.path.exists(folder_name):
os.makedirs(folder_name)
file_path = os.path.join(folder_name, 'image.jpg')
cv2.imwrite(file_path, image)
print(f"Image saved at {file_path}")
if __name__ == '__main__':
rospy.init_node("image_processor_with_yolo", anonymous=True)
node = Node()
rospy.spin() # Keep the node running until shutdown
当我尝试提取边界框时,我在输出中得到“无”。
与Yolo8:
for r in results:
box = result.boxes.xyxy
x1 = round(box[0][0].item())
y1 = round(box[0][1].item())
x2 = round(box[0][2].item())
y2 = round(box[0][3].item())