【问题标题】:Select pixels in an array using a structuring element in python 3使用python 3中的结构元素选择数组中的像素
【发布时间】:2020-09-22 11:23:56
【问题描述】:

我正在寻找一种使用结构元素在数组中选择“像素”的方法: 想象一下,我们有那个数组 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。

【问题讨论】:

  • 您可以使用线性索引仅提取感兴趣的子矩阵,然后应用布尔索引。所以像a[2:5,2:5][s != 0]

标签: python python-3.x numpy scipy


【解决方案1】:

这是一个使用 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 作为 boolean 数组而不是 int,则答案会更短,因为您不需要转换:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    相关资源
    最近更新 更多