Python返回错误“用作索引的数组必须为整数(或布尔)类型”

问题描述 投票:0回答:3

我正在尝试使自己适合2d高斯。主要目标是提取高斯参数。这是我的代码。

import matplotlib.pyplot as plt
import numpy as np
import random
from scipy.optimize import curve_fit,fmin

def Gauss2(x,y, amplitude, xo, yo, sigma_x, sigma_y, theta, bgr):
      xo = float(xo)
      yo = float(yo)    
      a = (np.cos(theta)**2)/(2*sigma_x**2) + (np.sin(theta)**2)/(2*sigma_y**2)
      b = -(np.sin(2*theta))/(4*sigma_x**2) + (np.sin(2*theta))/(4*sigma_y**2)
      c = (np.sin(theta)**2)/(2*sigma_x**2) + (np.cos(theta)**2)/(2*sigma_y**2)
      g = bgr + amplitude*np.exp( - (a*((x-xo)**2) + 2*b*(x-xo)*(y-yo) 
                        + c*((y-yo)**2)))
      return g

xsz = 40
ysz = 40

x0=xsz/2
y0=ysz/2

MInt1=200
bgr=10
noise=5

sigma_x = 5.
sigma_y = 4.

### create random Gaussian 2d
x = np.linspace(0, xsz-1, xsz)
y = np.linspace(0, xsz-1, xsz)
xx1, yy1 = np.meshgrid(x, y)
ex1=np.exp(-(((xx1-x0)**2)/(2*sigma_x**2) + ((yy1-y0)**2)/(2*sigma_y**2)))
z1 = MInt1* random.uniform(0, 1)*noise* ex1

theta=0
#aa=Gauss2(xx1,yy1, MInt1,x0,y0,sigma_x,sigma_y,theta,bgr)

poptX, pcovX = curve_fit(Gauss2, z1[x,y], p0=[x,y, MInt1,x0,y0,sigma_x,sigma_y,theta,bgr])

img = z1.reshape((xsz,xsz))
plt.imshow(img); plt.colorbar();plt.show()

我收到此消息:

IndexError:用作索引的数组必须是整数(或布尔值)类型

python numpy numpy-ndarray
3个回答
0
投票
x = np.linspace(0, xsz-1, xsz, dtype='int')
y = np.linspace(0, xsz-1, xsz, dtype='int')

这样

z1[x, y] 

将正常工作(只要z1正确大小)


0
投票

您会遇到一些问题。首先:

x = np.linspace(0, xsz-1, xsz, dtype=np.int)
y = np.linspace(0, xsz-1, xsz, dtype=np.int)

xy强制转换为整数类型,以便您可以索引到z1并摆脱当前遇到的错误。

此外,您对curve_fit的呼叫也会遇到一些问题。该呼叫应类似于:

poptX, pcovX = curve_fit(f, xdata, ydata, p0=[p1, ..., pn])

如果我正在解释您要完成的工作,这似乎与2D高斯曲线内的一维曲线拟合,则必须执行以下操作:

 poptX, pcovX = curve_fit(Gauss2, (x, y), z1[x, y], p0=[MInt1,x0,y0,sigma_x,sigma_y,theta,bgr])

这需要您对Gauss2的定义做一些非常小的修改,因为scipy希望将数据作为第一个位置参数传递进来:

def Gauss2(X, amplitude, xo, yo, sigma_x, sigma_y, theta, bgr):
      x, y = X # Pack x, y params into X
      xo = float(xo)
      yo = float(yo)    
      a = (np.cos(theta)**2)/(2*sigma_x**2) + (np.sin(theta)**2)/(2*sigma_y**2)
      b = -(np.sin(2*theta))/(4*sigma_x**2) + (np.sin(2*theta))/(4*sigma_y**2)
      c = (np.sin(theta)**2)/(2*sigma_x**2) + (np.cos(theta)**2)/(2*sigma_y**2)
      g = bgr + amplitude*np.exp( - (a*((x-xo)**2) + 2*b*(x-xo)*(y-yo) 
                        + c*((y-yo)**2)))
      return g

0
投票

非常感谢您的讨论。下一个问题解决了。

IndexError: arrays used as indices must be of integer (or boolean) type

但是在拟合curve_fit时仍然存在问题!

谁可以帮助我提供任何想法?

© www.soinside.com 2019 - 2024. All rights reserved.