【发布时间】: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