Created
August 6, 2021 12:34
-
-
Save ZeronoFreya/188b7fdeea77d5791fc0288046e1485d to your computer and use it in GitHub Desktop.
获取离散点的拟合平面,并以离散点中心(位于拟合平面上)为中心,绘制正三角形,中心到各顶点距离为1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
# 参考 https://blog.csdn.net/qq_45427038/article/details/100139330 | |
# 获取离散点的拟合平面,并以离散点中心(位于拟合平面上)为中心,绘制正三角形,中心到各顶点距离为1 | |
# 最少需要3个顶点 | |
size = 10 | |
# 创建函数,用于生成不同属于一个平面的10个离散点 | |
def not_all_in_plane(a, b, c): | |
x = np.random.uniform(-10, 10, size=size) | |
y = np.random.uniform(-10, 10, size=size) | |
z = (a * x + b * y + c) + np.random.normal(-1, 1, size=size) | |
return x, y, z | |
# 调用函数,生成离散点 | |
x, y, z = not_all_in_plane(2, 5, 6) | |
a = np.ones((size, 3)) | |
for i in range(0, size): | |
a[i, 0] = x[i] | |
a[i, 1] = y[i] | |
b = np.zeros((size, 1)) | |
for i in range(0, size): | |
b[i, 0] = z[i] | |
A_T = a.T | |
A1 = np.dot(A_T, a) | |
A2 = np.linalg.inv(A1) | |
A3 = np.dot(A2, A_T) | |
X = np.dot(A3, b) | |
print('平面拟合结果为:z = %.3f * x + %.3f * y + %.3f'%(X[0,0],X[1,0],X[2,0])) | |
matrix = np.mat([(x[i], y[i], z[i]) for i in range(0, size)]) | |
co = np.mean(matrix, 0) | |
# 获取离散点的中心点 | |
c = (co[0,0], co[0,1], X[0,0] * co[0,0] + X[1,0] * co[0,1] + X[2,0]) | |
# 拟合平面的法向量 | |
n = np.array([X[0,0], X[1,0], -1]) | |
a = np.cross(n, np.array([1,0,0])) | |
b = np.cross(n, a) | |
a = a / np.linalg.norm(a) | |
b = b / np.linalg.norm(b) | |
# 圆半径 | |
r = 1 | |
angle = np.array([0, 240, 120]) * np.pi/180 | |
x = c[0] + r * a[0] * np.cos(angle) + r * b[0] * np.sin(angle) | |
y = c[1] + r * a[1] * np.cos(angle) + r * b[1] * np.sin(angle) | |
z = c[2] + r * a[2] * np.cos(angle) + r * b[2] * np.sin(angle) | |
print([(x[i], y[i], z[i]) for i in range(0, np.size(angle))]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment