Python 3D多项式曲面拟合,取决于顺序 [英] Python 3D polynomial surface fit, order dependent

查看:835
本文介绍了Python 3D多项式曲面拟合,取决于顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用天文数据,其中有彗星图像.由于拍摄时间(暮色),我想删除这些图像中的背景天空渐变.我开发的第一个程序是从Matplotlib的"ginput"(x,y)中选择用户选择的点,提取每个坐标(z)的数据,然后将数据与SciPy的"griddata"网格化为新数组.

I am currently working with astronomical data among which I have comet images. I would like to remove the background sky gradient in these images due to the time of capture (twilight). The first program I developed to do so took user selected points from Matplotlib's "ginput" (x,y) pulled the data for each coordinate (z) and then gridded the data in a new array with SciPy's "griddata."

由于假定背景仅略有变化,所以我想将3d低阶多项式拟合到这组(x,y,z)点.但是,"griddata"不允许输入顺序:

Since the background is assumed to vary only slightly, I would like to fit a 3d low order polynomial to this set of (x,y,z) points. However, the "griddata" does not allow for an input order:

griddata(points,values, (dimension_x,dimension_y), method='nearest/linear/cubic')

关于可以使用的其他函数的任何想法,或者开发出可以使我控制顺序的最小二乘拟合的方法?

Any ideas on another function that may be used or a method for developing a leas-squares fit that will allow me to control the order?

推荐答案

Griddata使用样条拟合.三阶样条曲线与三阶多项式是不同的(相反,它在每个点都是不同的三阶多项式).

Griddata uses a spline fitting. A 3rd order spline is not the same thing as a 3rd order polynomial (instead, it's a different 3rd order polynomial at every point).

如果您只是想将2D,3阶多项式拟合到数据中,请执行以下操作,使用数据点的 all 估算16个系数.

If you just want to fit a 2D, 3rd order polynomial to your data, then do something like the following to estimate the 16 coefficients using all of your data points.

import itertools
import numpy as np
import matplotlib.pyplot as plt

def main():
    # Generate Data...
    numdata = 100
    x = np.random.random(numdata)
    y = np.random.random(numdata)
    z = x**2 + y**2 + 3*x**3 + y + np.random.random(numdata)

    # Fit a 3rd order, 2d polynomial
    m = polyfit2d(x,y,z)

    # Evaluate it on a grid...
    nx, ny = 20, 20
    xx, yy = np.meshgrid(np.linspace(x.min(), x.max(), nx), 
                         np.linspace(y.min(), y.max(), ny))
    zz = polyval2d(xx, yy, m)

    # Plot
    plt.imshow(zz, extent=(x.min(), y.max(), x.max(), y.min()))
    plt.scatter(x, y, c=z)
    plt.show()

def polyfit2d(x, y, z, order=3):
    ncols = (order + 1)**2
    G = np.zeros((x.size, ncols))
    ij = itertools.product(range(order+1), range(order+1))
    for k, (i,j) in enumerate(ij):
        G[:,k] = x**i * y**j
    m, _, _, _ = np.linalg.lstsq(G, z)
    return m

def polyval2d(x, y, m):
    order = int(np.sqrt(len(m))) - 1
    ij = itertools.product(range(order+1), range(order+1))
    z = np.zeros_like(x)
    for a, (i,j) in zip(m, ij):
        z += a * x**i * y**j
    return z

main()

这篇关于Python 3D多项式曲面拟合,取决于顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆