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

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

我正在尝试使自己适合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
1个回答
0
投票
x = np.linspace(0, xsz-1, xsz, dtype='int')
y = np.linspace(0, xsz-1, xsz, dtype='int')

这样

z1[x, y] 

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

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