python - 3D 空间中最佳拟合平面的方向

标签 python numpy matplotlib scipy geometry

我正在尝试使用 python 3.4.3 和 Matplotlib 获取在 3D 散点图中绘制为最佳拟合线的平面的方向。我目前将数据绘制在 3D 图表中,其中有一个平面穿过这些点,并且需要一种方法来获取平面的方向。 查看它从 Z 轴倾斜的角度。有没有我错过的快捷方式,可以简单地“打印”方向角。或者是否可以创建从盒子顶部到平面的三角特征来获取角度。另外,我对 mathplotlib 知之甚少,因此任何帮助将不胜感激。

def plane(x, y, params):
    a = params[0]
    b = params[1]
    c = params[2]
    z = a*x + b*y + c
    return z

def error(params, points):
    result = 0
    for (x,y,z) in points:
        plane_z = plane(x, y, params)
        diff = abs(plane_z - z)
        result += diff**2
    return result

def cross(a, b):
    return [a[1]*b[2] - a[2]*b[1],
            a[2]*b[0] - a[0]*b[2],
            a[0]*b[1] - a[1]*b[0]]

points = [(1.1,2.1,8.1),
          (3.2,4.2,8.0),
          (5.3,1.3,8.2),
          (3.4,2.4,8.3),
          (1.5,4.5,5.0)]

fun = functools.partial(error, points=points)
params0 = [0, 0, 0]
res = scipy.optimize.minimize(fun, params0)

a = res.x[0]
b = res.x[1]
c = res.x[2]

xs, ys, zs = zip(*points)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

ax.scatter(xs, ys, zs)

point  = np.array([0.0, 0.0, c])
normal = np.array(cross([1,0,a], [0,1,b]))
d = -point.dot(normal)
xx, yy = np.meshgrid([-5,10], [-5,10])
z = (-normal[0] * xx - normal[1] * yy - d) * 1. /normal[2]
ax.plot_surface(xx, yy, z, alpha=0.6, color=[1,1,0])

ax.set_xlim(0,10)
ax.set_ylim(0,10)
ax.set_zlim(0,10)

plt.show()

最佳答案

如果我没记错的话,我的几何知识你只能通过相加来计算与 z 轴的角度。

from math import acos, sqrt
cos_theta=1./sqrt(a*a+b*b+1)
theta=acos(cos_theta)

theta 是垂直于平面的向量与 z 轴之间的角度(以弧度表示)。例如,XY 平面的 theta 为 0,ZY 平面的 theta 为 pi/2

关于python - 3D 空间中最佳拟合平面的方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33589018/

相关文章:

python - 如何在 Python 中打开 AIFC 文件以将标记数据附加到该文件?

python - Linux Python Pygame 无法访问/etc/alsa/alsa.conf

python pyplot : colorbar on contourf and scatter in same plot

python - Crontab 作业没有启动...想法?

python - 无法使用 Windows Ubuntu 应用程序连接到 Docker

python - 平均分组 2D numpy 数组

python - 在redis中存储numpy数组的最快方法

python - 初学者问题: Python scatter plot with normal distribution not plotting

python - 具有数字独立数据的 seaborn 中的水平条形图

python - 计算并在图表上放置点之间的天数