Numpy - 通过测试相邻索引获取索引位置

mik*_*725 2 python numpy image-processing

我正在使用numpy是Python.我有一个图像加载到numpy二维数组中:

[
  [...], # row0
  [...], # row1
  [...], # row2
  ...
]
Run Code Online (Sandbox Code Playgroud)

我需要得到所有像素的所有索引位置,其中任何一个(只有下列之一)北,南,东或西相邻像素具有一定的值.在我的情况下,如果4个相邻像素中的任何一个是0.

wim*_*wim 5

如果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)
Run Code Online (Sandbox Code Playgroud)

采取较小的原因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)
Run Code Online (Sandbox Code Playgroud)