numpy element-wise comparison in image

Viewed 1200

There are many answers related to avoid brute force RGB opencv image loop in python by using numpy. I checked many of them but none seems to answer completely my needs:

Given a image, I need to compare pixel-wise and create a mask based in the result. Is something like:

# image contains a jpg regular image
data = np.asarray(image)

# Separate each channel
blue, green, red = data.T

print(blue.shape)
#(1024, 1024)

So far so good.

I need a "white" mask of this image like the following:

->A pixel is white if its red_value > 80 AND red_value-green_value > 20 AND red_value-blue_value > 20

So after research I came to this:

white = ((red > 80).all and (red-green > 20).all and (red-blue > 20).all)

But after this operation I can´t read white values.

I tried many things like:

print(white.shape)

Gets: AttributeError: 'builtin_function_or_method' object has no attribute 'shape'

w = np.asarray(white)

Gets: array ( "<" built-in method all of numpy.ndarray object at 0x0408ED68">", dtype=object)

Any suggestions? Thanks.

1 Answers

You have a couple of problem in your rgb expression which should be cleared up by this example:

import numpy as np
r, g, b = [np.random.rand(5,5) for i in range(3)]

w = (r>.5) & (b>.5) & (g>.5)  # change your "white = ..." to look similar to this

To be more explicit: 1) don't use all when you want to do an element-wise comparison; 2) and doesn't usually do what you want with numpy arrays, instead use &; 3) you need to use the parens for this expression to work right.

Related