matplotlib 3D API绘制点云三坐标面投影等值线的异常问题
3D投影等值线渲染异常的根因与修正方案
核心问题来源
- 重采样逻辑错位:
resample()生成的规则网格中,zr是标量场f的插值结果,并非3D点云曲面真实的z坐标值。仅当zdir="z"时,投影平面的坐标轴为x、y,和传入的xr/yr维度匹配,加上offset设置为真实z轴范围的最小值,等值线刚好落在显示范围内,因此可正常渲染。 - 坐标范围错配:切换到
zdir="x"或zdir="y"时,matplotlib会自动将传入数组的维度映射到投影平面的对应坐标轴,此时映射得到的z轴坐标是zr(f值,数值范围通常在-0.5~0.5之间),但代码手动将z轴范围固定为点云真实的z坐标范围(经过旋转、平移后通常达到数百量级),导致等值线的所有z坐标完全落在显示范围外,计算阶段被全部裁剪,生成空线段列表,最终触发matplotlib内部的ValueError: not enough values to unpack (expected 3, got 0)报错;若裁剪不完全,就会因为数值差几个数量级出现等值线被压缩为细条的异常渲染。 - 三角剖分基准错误:
mkTris()直接使用旋转、平移后的全局x、y坐标做Delaunay三角剖分,但斜置的点云投影到全局xy平面时,三角邻接关系和曲面真实的邻接关系存在偏差,进一步降低插值精度。
修正实现
修改核心逻辑为:基于点云平面的局部坐标完成三角剖分与重采样,生成对应全局坐标系下的真实3D坐标网格,配合matplotlib自动的投影轴映射逻辑,完成三个坐标平面的等值线投影:
- 在数据生成阶段保留旋转矩阵、平移向量与局部平面坐标,作为三角剖分的基准。
- 重采样阶段基于局部平面坐标生成规则网格,通过坐标变换得到全局坐标系下的真实x、y、z值,同时插值得到对应位置的标量场f值。
- 等值线调用阶段传入统一的全局3D坐标网格,让matplotlib自动处理不同zdir下的轴映射,避免手动准备错配的网格维度。
- 基于真实的全局坐标范围固定坐标轴限值,保证所有投影等值线都在显示范围内。
修正后可运行代码
import math import sys import matplotlib as mpl import matplotlib.pyplot as plt import mpl_toolkits.mplot3d import numpy as np np.random.seed(4) numPts = 1000 scatter = False def main(): (pts, f, rot_mat, trans_vec, local_uv) = mkData() tris = mkTris(local_uv) plot(pts, tris, f, rot_mat, trans_vec) def plot(pts, tris, f, rot_mat, trans_vec): fig = plt.figure() ax = fig.add_subplot(111, projection="3d") cmap = plt.get_cmap("coolwarm") # 绘制三角曲面 collec = ax.plot_trisurf(pts[:,0], pts[:,1], pts[:,2], triangles=tris.triangles, cmap=cmap) colors = np.mean(f[tris.triangles], axis=1) collec.set_array(colors) collec.autoscale() # 重采样得到全局坐标网格与标量场 (xr, yr, zr, fr, xMin, yMin, zMin) = resample(tris, f, rot_mat, trans_vec, ax) ax.set_xlim(xMin, xMin + 2*abs(xMin)) ax.set_ylim(yMin, yMin + 2*abs(yMin)) ax.set_zlim(zMin, zMin + 2*abs(zMin)) # 三个方向的投影等值线 ax.contour(xr, yr, zr, fr, 10, zdir="z", cmap=cmap, offset=zMin) ax.contour(xr, yr, zr, fr, 10, zdir="x", cmap=cmap, offset=xMin) ax.contour(xr, yr, zr, fr, 10, zdir="y", cmap=cmap, offset=yMin) if scatter: ax.scatter(pts[:, 0], pts[:, 1], pts[:, 2], alpha=0.1) ax.set_xlabel("x") ax.set_ylabel("y") ax.set_zlabel("z") fig.colorbar(collec, shrink=0.5, aspect=5) plt.show() def mkData(): offset = 1 local_uv = 2 * np.random.rand(numPts, 2) - 1 local_z = offset * (2 * np.random.rand(numPts) - 1) local_pts = np.hstack([local_uv, local_z.reshape(-1,1)]) x = local_uv[:,0] y = local_uv[:,1] f = x * np.exp(-x**2 - y**2) width = 100 height = 20 local_pts[:,0] *= width local_pts[:,1] *= height (e1, e2, e3) =[2 * np.pi * np.random.rand() for _ in range(3)] (c1, s1) = (math.cos(e1), math.sin(e1)) (c2, s2) = (math.cos(e2), math.sin(e2)) (c3, s3) = (math.cos(e3), math.sin(e3)) Ta2b = np.array(( [ c1 *c2, s2, -s1 * c2], [s1 * s3 - c1 * s2 * c3, c2 * c3, c1 *s3 + s1 * s2 * c3], [s1 * c3 + c1 * s2 * s3, -c2 * s3, c1 *c3 - s1 * s2 * s3])) global_pts = (Ta2b @ local_pts.T).T dist = 500 Ra2bNb = dist * (2 * np.random.rand(3, 1) - 1) global_pts += Ra2bNb.T return (global_pts, f, Ta2b, Ra2bNb.T, local_uv) def mkTris(local_uv): u = np.ravel(local_uv[:,0]) v = np.ravel(local_uv[:,1]) try: return mpl.tri.Triangulation(u, v) except (ValueError, RuntimeError) as ex: sys.exit(f"Unable to compute triangulation: {ex}.") def resample(tris, f, rot_mat, trans_vec, ax): u_grid = np.linspace(-1, 1, 30) v_grid = np.linspace(-1, 1, 30) um, vm = np.meshgrid(u_grid, v_grid) # 计算全局坐标 local_grid_pts = np.vstack([um.ravel()*100, vm.ravel()*20, np.zeros(um.size)]) global_grid_pts = rot_mat @ local_grid_pts + trans_vec.T xr = global_grid_pts[0,:].reshape(um.shape) yr = global_grid_pts[1,:].reshape(um.shape) zr = global_grid_pts[2,:].reshape(um.shape) # 插值标量场 interp = mpl.tri.triinterpolate.LinearTriInterpolator(tris, f) fr = interp(um, vm) xMin = ax.get_xlim()[0] yMin = ax.get_ylim()[0] zMin = ax.get_zlim()[0] return (xr, yr, zr, fr, xMin, yMin, zMin) if __name__ == "__main__": main()
内容的提问来源于stack exchange,提问作者Jim
相关产品推荐
相关产品推荐

