python实现三维拟合

原文转载于:https://blog.csdn.net/changye777/article/details/78437491

from  matplotlib import pyplot as plt
import  numpy as np
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = Axes3D(fig)

#列出实验数据
point=[[2,3,48],[4,5,50],[5,7,51],[8,9,55],[9,12,56]]
plt.xlabel("X1")
plt.ylabel("X2")

#表示矩阵中的值
ISum = 0.0
X1Sum = 0.0
X2Sum = 0.0
X1_2Sum = 0.0
X1X2Sum = 0.0
X2_2Sum = 0.0
YSum = 0.0
X1YSum = 0.0
X2YSum = 0.0

#在图中显示各点的位置
for i in range(0,len(point)):

    x1i=point[i][0]
    x2i=point[i][1]
    yi=point[i][2]
    ax.scatter(x1i, x2i, yi, color="red")
    show_point = "["+ str(x1i) +","+ str(x2i)+","+str(yi) + "]"
    ax.text(x1i,x2i,yi,show_point)

    ISum = ISum+1
    X1Sum = X1Sum+x1i
    X2Sum = X2Sum+x2i
    X1_2Sum = X1_2Sum+x1i**2
    X1X2Sum = X1X2Sum+x1i*x2i
    X2_2Sum = X2_2Sum+x2i**2
    YSum = YSum+yi
    X1YSum = X1YSum+x1i*yi
    X2YSum = X2YSum+x2i*yi

# 进行矩阵运算
# _mat1 设为 mat1 的逆矩阵
m1=[[ISum,X1Sum,X2Sum],[X1Sum,X1_2Sum,X1X2Sum],[X2Sum,X1X2Sum,X2_2Sum]]
mat1 = np.matrix(m1)
m2=[[YSum],[X1YSum],[X2YSum]]
mat2 = np.matrix(m2)
_mat1 =mat1.getI()
mat3 = _mat1*mat2

# 用list来提取矩阵数据
m3=mat3.tolist()
a0 = m3[0][0]
a1 = m3[1][0]
a2 = m3[2][0]

# 绘制回归线
x1 = np.linspace(0,9)
x2 = np.linspace(0,12)
y = a0+a1*x1+a2*x2
ax.plot(x1,x2,y)
show_line = "y="+str(a0)+"+"+str(a1)+"x1"+"+"+str(a2)+"x2"
plt.title(show_line)
plt.show()

 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Python实现三维点云椭圆拟合可以使用最小二乘法(Levenberg-Marquardt算法)进行拟合。以下是一个简单的实现示例: 1. 导入需要的库: ```python import numpy as np from scipy.optimize import least_squares ``` 2. 定义椭圆方程: ```python def ellipse_func(params, x, y, z): a, b, c, d, f, g, h, i, j = params return (a * x ** 2 + b * y ** 2 + c * z ** 2 + d * y + f * z + g * x * y + h * y * z + i * x * z + j) ``` 3. 定义误差函数: ```python def error_func(params, x, y, z, x_data, y_data, z_data): return ellipse_func(params, x_data, y_data, z_data) - ellipse_func(params, x, y, z) ``` 4. 输入数据点: ```python x = [1, 2, 3, 4, 5] # x坐标 y = [2, 3, 4, 5, 6] # y坐标 z = [3, 4, 5, 6, 7] # z坐标 ``` 5. 设置初始参数和边界条件: ```python initial_params = [1, 1, 1, 1, 1, 1, 1, 1, 1] # 初始参数 lb = [-np.inf, -np.inf, -np.inf, -np.inf, -np.inf, -np.inf, -np.inf, -np.inf, -np.inf] # 参数下界 ub = [np.inf, np.inf, np.inf, np.inf, np.inf, np.inf, np.inf, np.inf, np.inf] # 参数上界 ``` 6. 进行拟合: ```python result = least_squares(error_func, initial_params, bounds=(lb, ub), args=(x, y, z, x, y, z)) params = result.x # 拟合后得到的参数 ``` 7. 输出拟合后的结果: ```python print("拟合后的参数:", params) ``` 以上是一个简单的三维点云椭圆拟合实现示例,根据实际情况,你可能需要根据点云的特点对方程进行调整,并设置合适的初始参数和边界条件。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值