rospy节点接收数据matplotlib绘图并发布到rostopic

在python实际应用中经常需要matplotlib进行实时绘图,并更新数据,在这里我们也需要与ros进行通讯。

首先,matplotlib.pyplot进行绘图并更新,ax.spines可以将坐标轴置中对零。

#!/usr/bin/env python
import rospy
import numpy as np
import PIL.Image
import matplotlib.pyplot as plt
from math import *
import cv2
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
if __name__ == '__main__':
    rospy.init_node('TransformMaptoImage', anonymous=True)
    bridge = CvBridge()
    plt.ion()
    figure, ax = plt.subplots(figsize=(8,8))
    exp_map = np.array([[0., 0.]])
    real_map = np.array([[0., 0.]])
    line1, = ax.plot(exp_map[0,0], exp_map[0,1],linewidth=1, color='green', label='exp_map')
    line2, = ax.plot(real_map[0,0], real_map[0,1],linewidth=1, color='blue', label='real_map')
    plt.title("exp_map vs real_map",fontsize=10)
    plt.xlabel("X")
    plt.ylabel("Y")
    ax.grid()
    ax.legend()
    ax.spines['left'].set_position(('data', 0.0))
    ax.spines['bottom'].set_position(('data', 0.0))
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')

 publish和subscribe订阅相关话题,在回调函数中更新全局变量并在主循环中定时更新图片并发布;

 line1 line2进行plot数据更新,autoscale,刷新flush;

从pyplot中将figure转换成rgb字符串,通过cvbridge转换成image发布,因为本人平台限制只能使用rgb8格式,也可以通过cv2转换成bgr。

    pub_image = rospy.Publisher('/Image', Image, queue_size=1)
    rospy.Subscriber("/Map", ComparisonMap, com_map_callback,queue_size=1)
    rate = rospy.Rate(10) # 10hz 
    while not rospy.is_shutdown():
        line1.set_xdata(exp_map[:,0])
        line1.set_ydata(exp_map[:,1])
        line2.set_xdata(real_map[:,0])
        line2.set_ydata(real_map[:,1])
        ax.relim()
        ax.autoscale_view()
        figure.canvas.draw()
        figure.canvas.flush_events()
        //发布图片主题
        # convert canvas to image
        img = np.fromstring(figure.canvas.tostring_rgb(), dtype=np.uint8, sep='')
        img  = img.reshape(figure.canvas.get_width_height()[::-1] + (3,))
        # img is rgb, convert to opencv's default bgr
        #img = cv2.cvtColor(img,cv2.COLOR_RGB2BGR)
        pub_image.publish(bridge.cv2_to_imgmsg(img,'rgb8'))
        rate.sleep()

 注:本代码并不完全,仅供学习参考。

猜你喜欢

转载自blog.csdn.net/li4692625/article/details/114110993