Last active
March 27, 2025 21:42
-
-
Save AnthonyZJiang/54cb15255a3ffe2bc9f3edf8dad19dc2 to your computer and use it in GitHub Desktop.
ROS publish local image
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import rospy | |
import cv2 | |
from cv_bridge import CvBridge | |
from sensor_msgs.msg import Image, CompressedImage | |
def image_publisher(): | |
rospy.init_node('local_image', anonymous=True) | |
raw_image_pub = rospy.Publisher('/local_image/raw', Image, queue_size=10, latch=True) | |
compressed_image_pub = rospy.Publisher('/local_image/compressed', CompressedImage, queue_size=10, latch=True) | |
bridge = CvBridge() | |
image_path = "local_image.png" # Replace with the actual path to your image | |
cv_image = cv2.imread(image_path) | |
if cv_image is None: | |
rospy.logerr("Failed to load image from path: {}".format(image_path)) | |
return | |
rospy.loginfo("Image loaded successfully.") | |
ros_image = bridge.cv2_to_imgmsg(cv_image, encoding="bgr8") | |
raw_image_pub.publish(ros_image) | |
_, encoded_image = cv2.imencode('.jpg', cv_image) | |
compressed_image = CompressedImage() | |
compressed_image.header.stamp = rospy.Time.now() | |
compressed_image.format = "jpeg" | |
compressed_image.data = encoded_image.tobytes() | |
compressed_image_pub.publish(compressed_image) | |
rospy.loginfo("Image published successfully.") | |
if __name__ == '__main__': | |
image_publisher() | |
rospy.spin() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment