I am using numpy is Python. I have an image loaded up into numpy 2-dimensional array as:
[
[...开发者_StackOverflow社区], # row0
[...], # row1
[...], # row2
...
]
I need to get all the index positions of all pixels where either (only one of the following) north, south, east, or west adjacent pixels are of certain value. In my case if any of the 4 adjacent pixels is 0.
If a is your original array, define a bunch of slices:
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)
The reason for taking the smaller a_
is that I don't know what you want to do with the edge cases, where e.g. the North pixel might not exist.
I build an array of the count of adjacent zeros, and use that to get the positions which are adjacent to exactly one zero. Output:
[[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 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)
Probably the simplest way to do this is to locate all of the zeros using something like:
import numpy as np
# a is the image array
z_indices = np.where(a == 0)
And then just calculate the adjacent indices to the pixels that are zero (all combinations of +1,-1 the zero indices). You will then have to remove duplicates if a point is adjacent to two different zero pixels.
精彩评论