【发布时间】:2011-08-26 12:57:37
【问题描述】:
我使用 numpy 是 Python。我将图像加载到 numpy 二维数组中:
[
[...], # row0
[...], # row1
[...], # row2
...
]
我需要获取所有像素的所有索引位置,其中(仅以下之一)北、南、东或西相邻像素具有特定值。在我的情况下,如果 4 个相邻像素中的任何一个为 0。
【问题讨论】:
标签: python image-processing numpy
我使用 numpy 是 Python。我将图像加载到 numpy 二维数组中:
[
[...], # row0
[...], # row1
[...], # row2
...
]
我需要获取所有像素的所有索引位置,其中(仅以下之一)北、南、东或西相邻像素具有特定值。在我的情况下,如果 4 个相邻像素中的任何一个为 0。
【问题讨论】:
标签: python image-processing numpy
如果 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)
【讨论】:
可能最简单的方法是使用以下方法定位所有零:
import numpy as np
# a is the image array
z_indices = np.where(a == 0)
然后只计算零像素的相邻索引(+1,-1 零索引的所有组合)。如果一个点与两个不同的零像素相邻,则必须删除重复项。
【讨论】: