1

I am trying to mask a colored image with a 2D mask in python. I have tried the solution given in the answer here Masking BGR image using a 2D mask but it is not displaying the desired result.

I have tried this code from a previous answer:

mask = np.zeros_like(image)

# copy your image_mask to all dimensions (i.e. colors) of your image
for i in range(3):
    mask[:,:,i] = image_mask.copy()

masked_image = image[mask]

where the image has the shape (522, 775, 3) and the image_mask has the shape (522, 775) and 0 or 1 as values.

masked_image.shape 

is outputting this (522, 775, 3, 775, 3) and therefore the image is not displayed.

The expected result would be the masked image with 0s in places where the mask is 0 as well. Instead, I get a strange shape in the resulting masked_image and cannot understand why. Any help would be much appreciated!

DavidG
  • 24,279
  • 14
  • 89
  • 82
  • Note that the answer to the linked question is given in [this comment](https://stackoverflow.com/questions/26821137/masking-bgr-image-using-a-2d-mask#comment42250759_26821137) below it. – ImportanceOfBeingErnest May 09 '19 at 21:09

1 Answers1

0

What happens if you multiply your image with the mask?

mask = np.zeros_like(image)

# copy your image_mask to all dimensions (i.e. colors) of your image
for i in range(3):
    mask[:,:,i] = image_mask.copy()

masked_image = image * mask
Kıvanç Yüksel
  • 701
  • 7
  • 17