import cv2 import numpy as np from sensor_msgs.msg import Image from cv_bridge import CvBridge bridge = CvBridge() # OpenCV code to read an image file img = cv2.imread('test_image.jpg') # Convert OpenCV image to ROS image message img_msg = bridge.cv_to_imgmsg(img, encoding="bgr8") # Display image message in ROS rospy.loginfo(img_msg)
import rospy from sensor_msgs.msg import Image from cv_bridge import CvBridge bridge = CvBridge() def image_callback(ros_image): # Convert ROS image message to OpenCV image cv_image = bridge.imgmsg_to_cv2(ros_image, desired_encoding="bgr8") # Modify OpenCV image cv_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2GRAY) # Convert OpenCV image back to ROS image message ros_image = bridge.cv2_to_imgmsg(cv_image, encoding="mono8") # Publish ROS image message image_pub.publish(ros_image) # Connect to ROS image topic image_sub = rospy.Subscriber("camera/image", Image, image_callback) image_pub = rospy.Publisher("camera/image_processed", Image, queue_size=1) rospy.spin()In this example, we use the cv_bridge package to subscribe to a ROS image topic 'camera/image'. The image_callback function is called whenever a new image is received. We use the imgmsg_to_cv2 function to convert the ROS image message to OpenCV image format. We modify the OpenCV image by applying a grayscale color mask. We then use the cv2_to_imgmsg function to convert the modified OpenCV image back to a ROS image message and publish it on the 'camera/image_processed' topic.