【发布时间】:2020-12-22 10:11:26
【问题描述】:
我想将压力感应垫(32x32 压力点)中的值实时可视化为带有 MatPlotLib 动画的热图。
mat 输出 1025 个字节(1024 个值 + 'end byte',始终为 255)。我从 animate 函数内部打印出这些,但只有在我注释掉 plt.imshow(np_ints) 时才有效。
使用plt.imshow,MatPlotLib 窗口会弹出,甚至可以读取值...当我按下传感器启动程序时,我在热图中看到它,但当我释放它时,它似乎慢慢通过串行缓冲区中的所有读数,而不是实时读数。不知道是因为我没有正确处理串行还是与 FuncAnimation 的工作方式有关。有人能指出我正确的方向吗?
import numpy as np
import serial
import matplotlib.pyplot as plt
import matplotlib.animation as animation
np.set_printoptions(threshold=1024,linewidth=1500)
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
def animate(i):
# np_ints = np.random.random((200, 200)) # FOR TESTING ONLY
if ser.inWaiting:
ser_bytes = bytearray(ser.read_until(b'\xFF')) # should read 1025 bytes (1024 values + end byte)
if len(ser_bytes) != 1025: return # prevent error from an 'incomplete' serial reading
ser_ints = [int(x) for x in ser_bytes]
np_ints = np.array(ser_ints[:-1]) # drop the end byte
np_ints = np_ints.reshape(32, 32)
print(len(ser_ints))
print(np.matrix(np_ints))
plt.imshow(np_ints) # THIS BRAKES IT
if __name__ == '__main__':
ser = serial.Serial('/dev/tty.usbmodem14101', 11520)
ser.flushInput()
ani = animation.FuncAnimation(fig, animate, interval=10)
plt.show()
【问题讨论】:
-
请提供一个 !MIVE。您的代码与
plt.imshow重叠。看看 blitting。
标签: python-3.x serial-port heatmap pyserial matplotlib-animation