我有一个特定的python问题,迫切需要通过避免使用循环来加快速度,但是,我不知道如何做到这一点。我需要读取适合的图像,将其转换为 numpy 数组(大小约为 2000 x 2000 个元素),然后为每个元素计算其周围元素环的统计信息。正如我现在有我的代码一样,元素周围的环的统计信息是使用使用掩码的函数计算的。这很快,但是,当然,我调用这个函数 2000x2000 次(慢的部分)。我对python比较陌生。我认为使用掩码功能很聪明,但我找不到单独解决每个元素的方法。非常感谢您提供的任何帮助。
# First, the function computing the statistics within a ring
around the central pixel:<br/>
# flux = image intensity at pixel (i,j)<br/>
# rad1, rad2 = inner and outer radii<br/>
# array = image array<br/>_
def snr(flux, i, j, rad1, rad2, array):
a, b = i, j
nx, ny = array.shape
y, x = np.ogrid[-a:nx-a, -b:ny-b]
mask = (x*x + y*y >= rad1*rad1) & (x*x + y*y <= rad2*rad2)
Nmask = np.count_nonzero(mask)
noise = 0.6052697 * abs(Nmask * flux - sum(array[mask]))
return noise
# Now, the call to snr for each pixel in the array data1:<br/>_
frame1 = fits.open(in_frame, mode='readonly') # read in fits file
data1 = frame1[ext].data # convert to np array
ny, nx = data1.shape # array dimensions
noise1 = zeros((ny, nx), float) # empty array
r1 = 5 # inner radius (pixels)
r2 = 7 # outer radius (pixels)
# The function is fast, but calling it 2k x 2k times is not:
for j in range(ny):
for i in range(nx):
noise1[i,j] = der_snr(data1[i,j], i, j, r1, r2, data1)