3

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)?

6
  • What have you tried? A simple conditional should do it, test for the colour of the mask if the test passes, add the pixels from the image. Commented Dec 3, 2019 at 15:28
  • img[mask[..., None]]? Commented Dec 3, 2019 at 15:30
  • I am new at programming. I tried setting all pixels of the image which are not in the mask at 0: img[mask==False]=0 but this did not work. You mean I should loop over every element in the array? Commented Dec 3, 2019 at 15:32
  • if I use img[mask[..., None]] I get this error: IndexError: boolean index did not match indexed array along dimension 2; dimension is 3 but corresponding boolean dimension is 1 Commented Dec 3, 2019 at 15:34
  • 2
    I think you want cob = img * mask because False evaluates to zero. Commented Dec 3, 2019 at 15:42

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't actually answer the question of how to extract the pixels...
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.