How to select ‘black’ cells in a 3d numpy array?

I have an NumPy array of shape (512, 512, 3) (i.e. a RGB image). The array is created from a binary mask, which I read into a 3d array with Pillow:

data = np.array(Image.open(mask).convert('RGB'))

I want to change the color of the oject in the mask to a RGB color. To do so, I need to select all the cells in the array which do not have a value of zero in all 3 dimensions (i.e. (0,0,0) = black), because this is the background.

I tried the following - coloring the non-black cells green - without success:

data[data[:,:,:] > 0] = (0, 255, 0)

and

data[data[:,:,:] != (0,0,0)] = (0, 255, 0)

Getting the following error (in both cases):

ValueError: NumPy boolean array indexing assignment cannot assign 3 input values to the 8679 output values where the mask is true

How do I select all the 'black' cells in a 3d numpy array?

It should not be too difficult, but I cannot figure it out and there does not seem to be a similar question on S/O yet (but please let me know if I'm wrong).

This is my desired result: converting the grey mask (left) to a RGB color mask (right).

Grey mask RGB mask



Read more here: https://stackoverflow.com/questions/67018257/how-to-select-black-cells-in-a-3d-numpy-array

Content Attribution

This content was originally published by Sytze at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: