在2D阵列边缘截断的凹凸圆形掩模切口

时间:2014-12-27 19:18:42

标签: python arrays numpy

我有一个2D numpy数组,我想屏蔽几个特定元素周围的圆形区域。对于不靠近边缘的元素,这很容易。但是当光盘在数组边缘附近的位置被截断时,屏蔽操作会引发异常。

掩盖这些边缘资源的好方法是什么?定期填充..?谢谢!

以下是一些代码:

import numpy as np

x_count = 20000
y_count = 20000

a = np.arange(y_count * x_count).reshape(y_count, x_count) # data
master_mask=np.zeros(a.shape).astype(bool)

coords=([10,50],[500,400])
nsrc=len(coords)
mask_radius=100 # 10, 20, etc.

for isrc in range(nsrc):
    xc=coords[isrc][0]; yc=coords[isrc][1]
    x,y = np.ogrid[-mask_radius:mask_radius+1,-mask_radius:mask_radius+1]
    minimask = x*x + y*y <= mask_radius*mask_radius
    box=master_mask[xc-mask_radius:xc+mask_radius+1,yc-mask_radius:yc+mask_radius+1]
    assert(minimask.shape==box.shape), 'This assertion should fail for discs touching the edge'
    master_mask[xc-mask_radius:xc+mask_radius+1,yc-mask_radius:yc+mask_radius+1] += minimask

print master_mask

1 个答案:

答案 0 :(得分:1)

这是一个可能的(行人)答案,尽管我希望那里有一种更加笨拙的方式。

import numpy as np

x_count = 20000
y_count = 20000

a = np.arange(y_count * x_count).reshape(y_count, x_count) # data
master_mask=np.zeros(a.shape).astype(bool)

coords=([10,50],[500,400])
nsrc=len(coords)
mask_radius=100 # 10, 20, etc.

for isrc in range(nsrc):
    xc=coords[isrc][0]; yc=coords[isrc][1]
    # Truncate the postage-stamp mask here
    xmin=max(xc-mask_radius,0); xmax=min(xc+mask_radius+1,x_count)
    ymin=max(yc-mask_radius,0); ymax=min(yc+mask_radius+1,y_count)
    x,y = np.ogrid[xmin:xmax,ymin:ymax]

    minimask = x*x + y*y <= mask_radius*mask_radius
    box=master_mask[xmin:xmax,ymin:ymax]
    #assert(minimask.shape==box.shape), 'This assertion should fail for discs near the edge'
    master_mask[xmin:xmax,ymin:ymax] += minimask

print master_mask