I want to find if a 3D numpy array contains a specific 1D vector along the 3rd dimension. (I need to check if an image contains pixel(s) of a specific color.)
I need to return true if and only if any of the pixels match exactly with the target.
I've tried the following:
import numpy as np
target = np.array([255, 0, 0])
search_area = np.array([[[0,0,0],[1,1,1],[2,2,2]],
[[3,3,3],[4,4,4],[5,5,5]],
[[6,6,6],[7,7,7],[8,8,255]]])
contains_target = np.isin(target, search_area).all(): # Returns True
Which returns True since each element can be found individually somewhere within the entire array.
Next I tried:
target = np.array([255, 0, 0])
search_area = np.array([[[0,0,0],[1,1,1],[2,2,2]],
[[3,3,3],[4,4,4],[5,5,5]],
[[6,6,6],[7,7,7],[8,0,255]]])
contains_target = (target == search.all(2)).any() # Returns True
This works better since it matches the elements of target for each pixel individually, but it still returns True when they aren't in order or in the right numbers.
Lastly, I tried:
def pixel_matches_target(self, pixel_to_match):
return (target == pixel_to_match).all()
contains_target = np.apply_along_axis(self.pixel_matches_target, 2, search_area).any()
But it's too slow to be used (about 1 second per pass).
How can I find if a numpy array contains a vector along a specific axis?
EDIT:
I ended up circumventing the issue by converting the RGB images to binary masks using cv2.inRange() and checking if the resulting 2D array contains True values. This resulted in several orders of magnitude faster execution.