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:
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)?
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:
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
I have an image and its corresponding mask for the cob as numpy arrays:
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)?
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:
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