How to extract only the pixels of an image where it is masked? (Python numpy array operation)

Question:

I have an image and its corresponding mask for the cob as numpy arrays:

image

mask

The image numpy array has shape (332, 107, 3).

The mask is Boolean (consists of True/False) and has this shape as binary (332, 107).

 [[False False False ... False False False]
 [False False False ... False False False]
 [False False False ... False False False]
 ...
 [False False False ... False False False]
 [False False False ... False False False]
 [False False False ... False False False]]

How can I get the color pixels of the cob (all pixels in the color image where the mask is)?

Asked By: Olympia

||

Answers:

Thanks to the useful comment of M.Setchell, I was able to find the answer myself.

Basically, I had to expand the dimensions of the mask array (2D) to the same dimension of the image (3D with 3 color channels).

y=np.expand_dims(mask,axis=2)
newmask=np.concatenate((y,y,y),axis=2)

Then I had to simply multiply the new mask with the image to get the colored mask:

cob= img * newmask

And here just for visualization the result:

enter image description here

Answered By: Olympia

If you want to get an array of the pixels, i.e. array with shape (n,3):

#assuming mask.shape = (h,w) , and mask.dtype = bool
pixels = img[[mask]]

and if you want to produce the image in your answer then simply do this:

cop = img.copy()
cop[mask] = 0
Answered By: yazan sayed
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.