There's a simpler way to create the empty image using numpy.zeros_like
:
empty_img = numpy.zeros_like(img)
As Austin Hastings correctly pointed out, the trick is to use vectorized operations provided by numpy:
RED, GREEN, BLUE = (2, 1, 0)
reds = img[:, :, RED]
greens = img[:, :, GREEN]
blues = img[:, :, BLUE]
mask = (greens < 35) | (reds > greens) | (blues > greens)
or, using numpy.amax
mask = (greens < 35) | (numpy.amax(img, axis=2) != greens)
Now, one option is to use conditional indexing to modify empty_img
. Since it's a 3 channel image (represented as 3 dimensional array), and our mask is only 1 channel (represented as 2 dimensional array) there are two possibilities:
- assign 3-tuples:
empty_img[mask] = (255,0,0)
- provide the 3rd index:
empty_img[mask,0] = 255
If all you care about is just a single channel mask, then numpy.where
is a possibility.
result = numpy.where(mask, 255, 0)