Reputation: 122
The problem is relatively simple.
I have an image and I know a background color of the image. Given that I want to create foreground mask of the image.
I tried this:
background_color = np.array([255, 255, 255], dtype=np.uint8)
foreground = image != background_color
What I expect is a boolean matrix with the shape of HxWx1 with True where colors are matching and False where they are not matching.
But this operation compare not the color, but all three color components and I'm getting HxWx3 sized matrix with True where color components matching and False where they're not matching.
I created a temporary solution with for loop:
foreground = np.zeros(shape=(height, width, 1), dtype=np.bool)
for y in range(height):
for x in range(width):
if not np.array_equal(image[y, x], background_color):
foreground[y, x] = True
But that, of course, works slowly. My question is the following: Is there a proper way of doing such kind of comparison with the help of numpy or OpenCV methods?
Upvotes: 1
Views: 2880
Reputation: 13641
I don't know any numpy function for that, but you could chain a np.any()
call:
foreground = np.any(image != background_color, axis=-1)
The shape of foreground
will be equal to image.shape[:-1]
. If you want the extra dimension back, you could use:
foreground = np.any(image != background_color, axis=-1)[..., np.newaxis]
I kinda feel like there may exist a better (more numpy-like) way to do this...
Upvotes: 2