提取切片

时间:2016-03-07 01:39:50

标签: python arrays numpy data-structures

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

我有一个名为' Z'和一些盒子大小(PSF_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'的方框外的像素索引。或者更好的是,有没有办法直接在切片周围的区域执行某些操作? (与输出不是像素值的像素值相反)

1 个答案:

答案 0 :(得分:1)

我希望这大致代表你想要做的事情,即。在你的2d数据中获取环的元素。如果你喜欢环外的数据只是改变条件。

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