我用的是 numpy 是 Python。我将图像加载到 numpy 二维数组中:
[
[...], # row0
[...], # row1
[...], # row2
...
]
我需要获取所有像素的所有索引位置,其中(仅以下之一)北、南、东或西相邻像素具有特定值。在我的例子中,如果 4 个相邻像素中的任何一个为 0。
最佳答案
如果 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)
关于python - Numpy - 通过测试相邻索引获取索引位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7204946/