提取sli外部数组的索引

2024-10-04 01:33:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我想对二维阵列中心部分周围的环形空间进行统计(例如,对图像中恒星周围的背景进行统计)。我知道如何获取数组内部某个区域的2D切片并返回该切片的索引,但是有没有方法获取切片外部值的索引?你知道吗

我有一个名为“Z”的二维数组和一些框大小(PSF d box),我想围绕它执行一些统计。到目前为止我得到的是:

center = np.ceil(np.shape(Z)[0]/2.0) # center of the array
# Make a 2d slice of the star, and convert those pixels to nan
annulus[center-ceil(PSF_size/2.0):center+ceil(PSF_size/2.0)-1,\
center-ceil(PSF_size/2.0):center+ceil(PSF_size/2.0)-1] = np.nan
np.savetxt('annulus.dat',annulus,fmt='%s')

我将这个框切片内的像素转换为nan,但是我不知道如何输出框外不是“nan”的像素的索引。或者更好的是,有没有一种方法可以直接对切片周围的区域执行一些操作?(与输出非nan的像素值相反)


Tags: ofthe方法区域sizenp切片像素
1条回答
网友
1楼 · 发布于 2024-10-04 01:33:24

我希望这大致代表了你想要做的,即在你的二维数据中得到环空的元素。如果你喜欢环空以外的数据,只要改变条件。你知道吗

import numpy as np

#construct a grid
x= np.linspace(0,1,5)
y= np.linspace(0,1,5)
xv,yv = np.meshgrid(x, y, sparse=False, indexing='ij')


# a gaussian function
x0,y0=0.5,0.5
zz= np.exp(- (xv-x0)**2 - (yv-y0)**2)  # a function over the grid

print 'function\n', zz
# a distance metric on the grid
distance =  np.sqrt(   (xv-x0)**2+ (yv-y0)**2) 

print 'distance from center\n', distance

# make a condition and apply it to the array
cond= (distance>0.3) & (distance<0.7)
print  'selection\n',zz[cond]


# if you care about the locations of the annulus   
print xv[cond]
print yv[cond]

输出:

function
[[ 0.60653066  0.73161563  0.77880078  0.73161563  0.60653066]
 [ 0.73161563  0.8824969   0.93941306  0.8824969   0.73161563]
 [ 0.77880078  0.93941306  1.          0.93941306  0.77880078]
 [ 0.73161563  0.8824969   0.93941306  0.8824969   0.73161563]
 [ 0.60653066  0.73161563  0.77880078  0.73161563  0.60653066]]
distance from center
[[ 0.70710678  0.55901699  0.5         0.55901699  0.70710678]
 [ 0.55901699  0.35355339  0.25        0.35355339  0.55901699]
 [ 0.5         0.25        0.          0.25        0.5       ]
 [ 0.55901699  0.35355339  0.25        0.35355339  0.55901699]
 [ 0.70710678  0.55901699  0.5         0.55901699  0.70710678]]
selection
[ 0.73161563  0.77880078  0.73161563  0.73161563  0.8824969   0.8824969
  0.73161563  0.77880078  0.77880078  0.73161563  0.8824969   0.8824969
  0.73161563  0.73161563  0.77880078  0.73161563]
[ 0.    0.    0.    0.25  0.25  0.25  0.25  0.5   0.5   0.75  0.75  0.75
  0.75  1.    1.    1.  ]
[ 0.25  0.5   0.75  0.    0.25  0.75  1.    0.    1.    0.    0.25  0.75
  1.    0.25  0.5   0.75]

也可以看到这个伟大的答案:Numpy where function multiple conditions

相关问题 更多 >