编写图像发布、订阅的python脚本
1. talker.py
#!/usr/bin/env python
# license removed for brevity
import rospy
from sensor_msgs.msg import Image
import cv2
from cv_bridge import CvBridge
def talker():
pub = rospy.Publisher('/tutorial/image', Image, queue_size=1)
rospy.init_node('talker', anonymous=True)
rate = rospy.Rate(30)
bridge = CvBridge()
Video = cv2.VideoCapture(0)
while not rospy.is_shutdown():
ret, img = Video.read()
cv2.imshow("talker", img)
cv2.waitKey(3)
pub.publish(bridge.cv2_to_imgmsg(img, "bgr8"))
rate.sleep()
if __name__ == '__main__':
try:
talker()
except rospy.ROSInterruptException:
pass
2. listener.py
#!/usr/bin/python
import rospy
from sensor_msgs.msg import Image
import cv2
from cv_bridge import CvBridge
def callback(imgmsg):
bridge = CvBridge()
img = bridge.imgmsg_to_cv2(imgmsg, "bgr8")
cv2.imshow("listener", img)
cv2.waitKey(3)
def listener():
# In ROS, nodes are uniquely named. If two nodes with the same
# node are launched, the previous one is kicked off. The
# anonymous=True flag means that rospy will choose a unique
# name for our 'listener' node so that multiple listeners can
# run simultaneously.
rospy.init_node('listener', anonymous=True)
rospy.Subscriber("/tutorial/image", Image, callback)
# spin() simply keeps python from exiting until this node is stopped
rospy.spin()
if __name__ == '__main__':
listener()
3.运行
- 启动roscore
- 运行 talker.py
python3 talker.py
这时,我们会发现如下错误

这个错误是因为ros 自带的 cv_bridge 默认是使用python2环境的,所以我们需要使用python3重新编译这个cv_bridge,具体可以参考我的下一篇博客。

本文介绍如何使用Python在ROS环境中实现图像数据的发布与订阅功能。通过两个脚本:talker.py用于从摄像头捕获图像并发布,listener.py用于接收图像并在窗口中显示。文章还提到了使用cv_bridge进行图像消息转换的方法,并指出了在不同Python版本间可能遇到的兼容性问题。
2877

被折叠的 条评论
为什么被折叠?



