【问题标题】:Numpy - Getting index positions by testing adjacent indexesNumpy - 通过测试相邻索引来获取索引位置
【发布时间】:2011-08-26 12:57:37
【问题描述】:

我使用 numpy 是 Python。我将图像加载到 numpy 二维数组中:

[
  [...], # row0
  [...], # row1
  [...], # row2
  ...
]

我需要获取所有像素的所有索引位置,其中(仅以下之一)北、南、东或西相邻像素具有特定值。在我的情况下,如果 4 个相邻像素中的任何一个为 0。

【问题讨论】:

    标签: python image-processing numpy


    【解决方案1】:

    如果 a 是你的原始数组,定义一堆切片:

    from scipy import *
    
    a = ones((12,22))
    a[5,10] = a[5,12] = 0
    
    a_ = a[1:-1, 1:-1]
    aE = a[1:-1, 0:-2]
    aW = a[1:-1,   2:]
    aN = a[0:-2, 1:-1]
    aS = a[  2:, 1:-1]
    
    a4 = dstack([aE,aW,aN,aS])
    num_adjacent_zeros = sum(a4 == 0, axis=2)
    print num_adjacent_zeros
    
    ys,xs = where(num_adjacent_zeros == 1)
    # account for offset of a_
    xs += 1 
    ys += 1
    
    print '\n hits:'
    for col,row in zip(xs,ys):
      print (col,row)
    

    采用较小的a_ 的原因是我不知道您想对边缘情况做什么,例如北像素可能不存在。

    我构建了一个包含相邻零计数的数组,并使用它来获取恰好与一个零相邻的位置。输出:

    [[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
     [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
     [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
     [0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0]
     [0 0 0 0 0 0 0 0 1 0 2 0 1 0 0 0 0 0 0 0]
     [0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0]
     [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
     [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
     [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
     [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]]
    
     hits:
    (10, 4)
    (12, 4)
    (9, 5)
    (13, 5)
    (10, 6)
    (12, 6)
    

    【讨论】:

    • 逻辑运算是什么意思。对不起。我是 numpy 的新手。
    • 好吧,我会详细说明我的答案
    • 感谢您的详细说明。试图弄清楚你在这里做了什么。所有这些功能对我来说仍然是陌生的。
    【解决方案2】:

    可能最简单的方法是使用以下方法定位所有零:

    import numpy as np
    # a is the image array
    z_indices = np.where(a == 0)
    

    然后只计算零像素的相邻索引(+1,-1 零索引的所有组合)。如果一个点与两个不同的零像素相邻,则必须删除重复项。

    【讨论】:

    • 我现在正在这样做。有没有更好的办法?
    • @miki725:如果您尝试过某事,通常最好在原始问题中说明这一点。
    猜你喜欢
    • 1970-01-01
    • 2021-01-17
    • 2021-03-24
    • 2020-02-28
    • 1970-01-01
    • 2015-05-12
    • 2021-12-01
    • 2018-05-02
    • 2016-03-15
    相关资源
    最近更新 更多