如何在回调函数ROS中包含fig.canvas.draw()?

时间:2018-11-27 19:44:32

标签: python matplotlib ros

我正在尝试在ros中可视化消息,但是无法将fig.canvas.draw()放在回调中。我的目标是不断更新图表。但是每次尝试时,都会出现错误“主线程不在主循环中”。我该如何解决?

#! /usr/bin/env python
import rospy
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import random



from sensor_msgs.msg import LaserScan

x = np.linspace(0, 2* np.pi, 100)
y=np.random.random_integers(1, 100, 100)

plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111)
line1, = ax.plot(x, y, 'b-')

def callback(scan):
    distance_list = scan.ranges
    print(distance_list)
    print("scan angle min", scan.angle_min)
    print("scan angle incr", scan.angle_increment)
    print("scan angle max", scan.angle_max)
    line1.set_ydata(distance_list)
    fig.canvas.draw()

rospy.init_node('lidar_visual_node')
sub = rospy.Subscriber('\scan', LaserScan, callback)

rospy.spin()

1 个答案:

答案 0 :(得分:0)

这里的问题是回调正在单独的线程中运行,并且无法访问主线程中的fig。包含回调和必需变量的对象可以通过引入持久性来解决此问题。

class Visualiser:
 def __init__(self):
    x = np.linspace(0, 2* np.pi, 100)
    y = np.random.random_integers(1, 100, 100)
    plt.ion()
    self.fig = plt.figure()
    ax = self.fig.add_subplot(111)
    self.line1, = ax.plot(x, y, 'b-')

 def scanner_callback(self, scan):
    distance_list = scan.ranges
    print(distance_list)
    print("scan angle min", scan.angle_min)
    print("scan angle incr", scan.angle_increment)
    print("scan angle max", scan.angle_max)
    self.line1.set_ydata(distance_list)
    self.fig.canvas.draw()


rospy.init_node('lidar_visual_node')
vis = Visualiser()
sub = rospy.Subscriber('\scan', LaserScan, vis.scanner_callback)
rospy.spin()