import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
import cv2
import os
import numpy as np
from ultralytics import YOLO # Import YOLO class from ultralytics
# Define a class called Node
class Node(object):
def __init__(self):
# Initialize variables
self.image = None # Variable to store the image received from the camera
self.br = CvBridge() # Initialize a CvBridge object for converting between ROS Image messages and OpenCV images
self.loop_rate = rospy.Rate(1) # Define the node cycle rate (1 Hz)
# Publishers
self.pub = rospy.Publisher('imagetimer', Image, queue_size=10) # Define a publisher to publish the processed image
# Subscribers
rospy.Subscriber("/camera/color/image_raw", Image, self.callback) # Subscribe to the "/camera/color/image_raw" topic
# Initialize YOLO model
self.yolo_model = YOLO('best.pt')
# Callback function for processing the received image
def callback(self, msg):
rospy.loginfo('Image received...') # Log a message indicating that an image has been received
self.image = self.br.imgmsg_to_cv2(msg) # Convert the received ROS Image message to an OpenCV image
if self.image is not None: # Check if an image has been received
# Perform object detection
results = self.yolo_model(self.image, show=False, conf=0.4, save=False)
# Display the processed image on the screen
cv2.imshow("Processed Image", results.img)
cv2.waitKey(1) # Keep the image window open
# Convert the processed image back to a ROS Image message and publish it
self.pub.publish(self.br.cv2_to_imgmsg(results.img))
# Method to start the node
def start(self):
rospy.loginfo("Timing images") # Log a message indicating that the image timing process has started
while not rospy.is_shutdown(): # Continue looping until ROS shutdown is requested
self.loop_rate.sleep() # Sleep to maintain the node cycle rate
# Entry point of the script
if __name__ == '__main__':
rospy.init_node("imagetimer111", anonymous=True) # Initialize a ROS node with the name "imagetimer111"
my_node = Node() # Create an instance of the Node class
my_node.start() # Start the node
# Ensure the OpenCV window closes properly when the script ends
cv2.destroyAllWindows()
how do i extract the x and y coordinates of the bounding box