Python实时绘制ROS d

2024-10-01 07:44:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python绘制实时数据到计算机。数据来自一个ROS主题,我使用“rospy”订阅主题以获取数据。 这是我写的代码

import rospy
from sensor_msgs.msg import ChannelFloat32
import matplotlib.pyplot as plt

N = 200
i = 0

topic = "chatter"

x = range(N)
lmotor = [0]*N
rmotor = [0]*N

plt.ion()

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim([0,N])
ax.set_ylim([-1,1])

line1, = ax.plot(lmotor, 'r-')
line2, = ax.plot(rmotor, 'g')

def plotThrottle(data):
    global x, lmotor, rmotor, i

    [x[i],lmotor[i],rmotor[i], tmp] = data

    line1.set_ydata(lmotor)
    line1.set_xdata(x)
    line2.set_ydata(rmotor)
    line2.set_xdata(x)

    fig.canvas.draw()

def callBack(packet):
    data = list(packet.values)
    plotThrottle(data)


def listner():
    rospy.init_node('listener', anonymous=True)
    rospy.Subscriber(topic, ChannelFloat32, callBack)
    rospy.spin()

if __name__ == '__main__':
    listner()

我的问题是,当我用从rostopic获得的数据调用plotThrottle()时,我得到以下错误。在

^{pr2}$

但是如果我使用相同的函数并传递代码中生成的一些数据(一些随机数据),绘图就可以了。 我绝对是python的初学者。我搜索了一下这个错误,它说这是因为线程问题。但我不知道如何修复这个代码。如果有人能解释这个问题并帮助修复这个代码,我真的很感激。在


Tags: 数据代码importdatadeffigpltax
1条回答
网友
1楼 · 发布于 2024-10-01 07:44:30

这里有两个线程在运行,罗斯比.斯潘()和顶部.mainloop()(来自Tkinter,在您的案例中是matplotlib的后端)。在

来自this answer

The problems stem from the fact that the _tkinter module attempts to gain control of the main thread via a polling technique when processing calls from other threads.

Your Tkinter code in Thread-1 is trying to peek into the main thread to find the main loop, and it's not there.

this answer

If there is another blocking call that keeps your program running, there is no need to call rospy.spin(). Unlike in C++ where spin() is needed to process all the threads, in python all it does is block.

因此,您可以使用plt.show(block=True)来阻止程序关闭,在这种情况下,您将使用Tkinter mainloop,重新绘制画布而不会出现问题。在

侦听器功能应该如下所示:

    def listener():
        rospy.init_node('listener', anonymous=True)
        rospy.Subscriber(topic, ChannelFloat32, callBack)
        # rospy.spin()
        plt.show(block=True)

无论如何,对于其他替代方案来说,这似乎是一个解决办法,请再次参阅this answer或简单地使用单独的节点进行绘图,即ros建议的工具,如rqt_graph。在

相关问题 更多 >