【问题标题】:How to plot and view a live animation with Python on a remote Raspberry Pi?如何在远程 Raspberry Pi 上使用 Python 绘制和查看实时动画?
【发布时间】:2022-09-30 17:48:34
【问题描述】:

背景

我已经在 Raspberry Pi 4(具有 1 GB RAM 的 B 型)上安装了 Raspberry Pi OS Lite。我正在通过我的桌面上的sshing(例如ssh user@raspberrypi.local)在 Pi 上开发 Python。我正在使用 Pi 作为硬件在环 (HIL) 模拟器。我正在将数据从 HIL 发送到嵌入式控制器以测试软件。

在远程设备上运行时不显示动画

在将数据从 HIL 发送到控制器后,我还想使用 matplotlib 在动画中绘制该数据。下面的 matplotlib example 动画程序可以在任何桌面上运行。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], \'ro\')

def init():
    ax.set_xlim(0, 2*np.pi)
    ax.set_ylim(-1, 1)
    return ln,

def update(frame):
    xdata.append(frame)
    ydata.append(np.sin(frame))
    ln.set_data(xdata, ydata)
    return ln,

ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
                    init_func=init, blit=True)
plt.show()

但是,在远程连接内部时,不显示动画(即在 Pi 上运行时不显示动画)。

静态图可以显示在烧瓶网络服务器中

下面的代码是 matplotlib example 关于如何在网络服务器中显示绘图的代码。在 Pi 上运行以下脚本时,我可以通过转到 http://raspberrypi.local:5000 从我的桌面上看到该图。

import base64
from io import BytesIO

from flask import Flask
from matplotlib.figure import Figure

app = Flask(__name__)


@app.route(\"/\")
def hello():
    # Generate the figure **without using pyplot**.
    fig = Figure()
    ax = fig.subplots()
    ax.plot([1, 2])
    # Save it to a temporary buffer.
    buf = BytesIO()
    fig.savefig(buf, format=\"png\")
    # Embed the result in the html output.
    data = base64.b64encode(buf.getbuffer()).decode(\"ascii\")
    return f\"<img src=\'data:image/png;base64,{data}\'/>\"

if __name__ == \'__main__\':
    app.run(debug=True, threaded=True, host=\'0.0.0.0\')

问题

目标是从 Raspberry Pi 绘制动画并远程查看动画。有没有办法将这两个动作结合起来?

    标签: python matplotlib flask raspberry-pi remote-access


    【解决方案1】:

    好吧,我知道这已经很晚了,但对于那些后来面临这个问题的人来说。我在这里发布我的解决方案。

    1. 首先将 pi sshd_config 编辑到其 X11 转发上,如下所示:

      X11转发是 2.我在做follow config时使用的是Windows笔记本电脑。我认为MacOS是一样的。

      在我的 PowerShell 配置文件中,我通过在 shell 中键入“code $PROFILE”来添加以下句子:$env:DISPLAY='localhost:0.0'

      1. 保存以上文件并重新打开 powershell。使用ssh -Y pi@yourip连接 pi 并输入 >回声 $DISPLAY在 pi shell 中确认设置是否有效。例如:

      本地主机:11.0

      然后你可以运行你的代码,你会看到一个弹出的绘图窗口~

    【讨论】:

      猜你喜欢
      • 2020-11-13
      • 2020-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多