I am looking for a way in numpy to find the indices of outer specific rows in a 3d array. One example would be to find all occurrences of a given set of colours in a RBG image, and fetch the pixel coordinates.
This question shows that the in
operator can behave weirdly with arrays, and this one lead closer but works for 2D arrays.
Let's say we have the 3d array Z
with dimensions (x,y,z)
, and [s0, s1]
the 3rd dimension rows we want to match.
Z = np.zeros((10,20,3), dtype=int)
s0 = np.array([1,2,3])
s1 = np.array([4,5,6])
Z[1,2] = s0
Z[4,5] = s1
I want all (x,y)
where z
is equal to either s0
or s1
.
So far,
argwhere
return every match where one element from s0
is in Z
:
> np.argwhere(s0 == Z)
array([[1, 2, 0],
[1, 2, 1],
[1, 2, 2]])
in1d
return a boolean 1D array with True where element in s0 or s1 match:
> np.in1d(Z, [s0,s1])
and if I try the raveled way:
> Zravel = np.ascontiguousarray(a).view([('', a.dtype)] * a.shape[-1]).ravel()
> np.all(np.in1d(Zravel, [s0, s1]) == False)
all element are False
.
Any ideas?