用python写一个ros发布图片话题
时间: 2024-09-25 11:20:57 浏览: 72
abseil-py_ratez3j_pythonabseil-py_pythonabseil-py_ROS_ROS发布话题_
在Python中,使用ROS (Robot Operating System) 发布图像话题,你需要首先安装ros_comm相关的包,并且需要熟悉rospy和sensor_msgs库。下面是一个简单的示例,展示如何创建一个发布BGR8编码的图像的主题:
```python
import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
# 初始化节点
def image_publisher():
rospy.init_node('image_topic_publisher')
# 创建消息发布者,主题名称为/image_color
img_pub = rospy.Publisher('/image_color', Image, queue_size=10)
# 设置相机的参数,例如使用本地摄像头
cap = cv2.VideoCapture(0)
bridge = CvBridge()
try:
rate = rospy.Rate(10) # 10Hz publishing rate
while not rospy.is_shutdown():
ret, frame = cap.read() # 读取一帧图像
if not ret:
continue
# 将cv2的BGR图像转换为sensor_msgs.Image格式
msg = bridge.cv2_to_imgmsg(frame, "bgr8")
# 发布图像消息
img_pub.publish(msg)
rate.sleep()
except CvBridgeError as e:
print(e)
finally:
cap.release()
rospy.signal_shutdown("Shutting down the node.")
if __name__ == '__main__':
try:
image_publisher()
except rospy.ROSInterruptException:
pass
阅读全文