使用python开发3d打印机热床平整度可视化热力图应用(在不会Python的情况下)
通过串口发送G代码,控制3D打印机执行,以获取打印机的热床平台平整度数据,并使用热力图的形式,进行可视化展示,以直观的看到热床平整度情况。
奇葩的是本人的py基础仅限于两节免费教程。所以整个应用的代码没有一句是我自己写的,都是GTP写的。
运行效果如下:

完整代码如下:
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.colors import LinearSegmentedColormap
import serial
import time
from scipy import ndimage
# 尝试连接串口
try:
ser = serial.Serial('COM5', 115200, timeout=1)
except serial.SerialException:
print("串口打开失败,请检查COM口是否存在、是否被占用?")
else:
# 输出串口打开成功提示信息
print("串口打开成功")
# 发送G28代码并等待响应
print("发送G28归零指令")
ser.write(b'G28\r')
while True:
response = ser.readline().decode('utf-8').strip()
if "X:0.00 Y:0.00 Z:0.00 E:0.00 Count X:0 Y:0 Z:0" in response:
# print(response) # 打印响应信息到控制台
break
# 清空串口缓冲区
ser.reset_input_buffer()
# 发送G29代码并等待响应
print("发送G29打印机自动校平指令")
ser.write(b'G29\r')
# 创建空字符串raw_data
raw_data = ''
# 设置数据收集标志
collect_data = False
while True:
response = ser.readline().decode('utf-8')
if 'Bilinear Leveling Grid:' in response:
# 开始收集数据
collect_data = True
elif 'X:' in response:
# 停止收集数据
collect_data = False
break
elif collect_data:
# 添加响应信息到raw_data中
raw_data += response
# 关闭串口
ser.close()
# 解析热力图数据
lines = raw_data.strip().split("\n")
header = lines.pop(0)
col_names = [float(x) for x in header.split()]
data = np.array([[float(x) for x in line.split()[1:]] for line in lines])
data2 = np.copy(data)
#反转y轴
data2 = np.flip(data2, axis=0)
print(data2)
# 定义坐标轴范围
x = col_names
y = [float(line.split()[0]) for line in lines]
X, Y = np.meshgrid(x, y)
# 使用绝对高程
Z = np.abs(data)
# 使用高斯滤波平滑矩阵以获得更好的热力图效果
sigma = 1.0
Z = ndimage.gaussian_filter(Z, sigma)
# 定义渐变色色阶
cmap_colors = [(0, 0, 1), (0, 1, 1), (1, 1, 0), (1, 0, 0)]
cmap_name = 'my_cmap'
my_cmap = LinearSegmentedColormap.from_list(cmap_name, cmap_colors)
# 计算偏移0点的大小,越大越接近红色,越小越接近蓝色
max_offset = np.abs(Z - 0).max()
Z_offset = (Z - 0) / max_offset
# 绘制3D热力图
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.view_init(30, -130) # 设置视角
surf = ax.plot_surface(X, Y, Z_offset, cmap=my_cmap, rstride=1, cstride=1, linewidth=0)
fig.colorbar(surf)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.title('3D Heatmap of Bed Leveling Data')
plt.show()