首页 > 解决方案 > 使用python 3中的结构元素选择数组中的像素

问题描述

我正在寻找一种使用结构元素在数组中选择“像素”的方法:假设我们有那个数组 a 和那个结构元素 s,

a=np.array([[ 0,  1,  2,  3,  4,  5,  6],
         [ 7,  8,  9, 10, 11, 12, 13],
         [14, 15, 16, 17, 18, 19, 20],
         [21, 22, 23, 24, 25, 26, 27],
         [28, 29, 30, 31, 32, 33, 34],
         [35, 36, 37, 38, 39, 40, 41],
         [42, 43, 44, 45, 46, 47, 48]])
s=np.array([[0,1,0],
         [1,1,1],
         [0,1,0]])

然后我正在寻找一个像

f(a, position=(3,3), structure=s) = [17,23,24,25,31]

看起来 scipy.ndimage 形态函数可以在内部做到这一点。一种解决方法是创建一个与 a 形状相同的 np.zeros 数组,将 1 放在感兴趣的位置并扩大它,但这会非常消耗资源 - 特别是因为我的数组不是 7 * 7。

标签: pythonpython-3.xnumpyscipy

解决方案


这是一个使用view_as_windows(在引擎盖下使用 numpy strides)的答案:

from skimage.util import view_as_windows
def f(a, position, structure):
  return view_as_windows(a,structure.shape)[tuple(np.array(position)-1)][structure.astype(bool)]

输出:

f(a, position=(3,3), structure=s)
#[17 23 24 25 31]

如果您将position作为 numpy 数组而不是 tuple 和structure作为布尔数组而不是 int 提供,则答案甚至会更短,因为您不需要转换:

def f(a, position, structure):
      return view_as_windows(a,structure.shape)[tuple(position-1)][structure]

推荐阅读