在python中使用2D方程拟合图像

时间:2014-03-08 11:12:36

标签: python numpy matplotlib scipy pyfits

我有一个图像,我想将其与二维方程拟合,以便提取nx和ny参数。首先我从拟合中定义了2D函数和残差然后我读取了图像文件,然后我尝试使用minimalsq方法拟合它,这是我的代码:

#!/usr/bin/python

import pyfits
import numpy as np
import numpy.random as npr
import matplotlib.pyplot as plt
import scipy.optimize


nx=870
ny=901

# define 2D function
def fun(nx,ny):

   n=(1+((nx**2+ny**2)**0.5/150)**2)**-3.7
   return n
vfun=np.vectorize(fun)
nxlist=np.linspace(-nx,nx,870)
nylist=np.linspace(-ny,ny,901)
X,Y=np.meshgrid(nxlist,nylist)
Z=vfun(X,Y)


def residuals(p,y,nx,ny):
    nx,ny = p
    err = y-fun(nx,ny)
    return err

def peval (nx,ny,p):
    nx,ny=p
    return fun(nx,ny)


# read image file

def image():
    h = pyfits.open('image.fits')
    IM = h[0].data      # copy the image data into a numpy (numerical python) array
    return IM
y_true = image()
y_meas = y_true+0.1*np.random.randn(ny,nx)         # add noise
colmap = plt.get_cmap('CMRmap') # load CMRmap colormap
plt.imshow(y_meas, cmap=colmap, origin='lower') # plot image using gray colorbar
plt.show()


# initial values
p0=[300,500]

plsq = scipy.optimize.leastsq(residuals,p0,args=(y_meas,nx,ny))
print plsq

但是,我收到此错误消息

File "image_fit_test.py", line 51, in <module>    
plsq =   scipy.optimize.leastsq(residuals,p0,args=(y_meas,nx,ny))
File "/.../anaconda/lib/python2.7/site-packages/scipy/optimize/minpack.py", line 364,
in leastsq
gtol, maxfev, epsfcn, factor, diag)
minpack.error: Result from function call is not a proper array of floats.

请有人建议任何解决方案,这会出错吗?

提前谢谢。

1 个答案:

答案 0 :(得分:1)

简单地用以下内容替换residuals()可以解决您的问题:

def residuals(p,y,nx,ny):
    nx,ny = p
    err = y-fun(nx,ny)
    return err.flatten()

基本上我怀疑residuals(p0, meas, nx, ny)的函数调用会返回2d array形状的(nx, ny),这会导致minpack.error异常。您需要将1d array(或float)传递给leastsq()