BBQuercus
BBQuercus

Reputation: 879

How to apply a mask to a numpy array maintaining shape and retrieving values?

I'm doing a image segmentation where I created a mask (bool array). I now want to extract the imaging data at the mask region while keeping the shape of my image array.

As the image data would be too large, here a shortened form of my problem:

import numpy as np

a = np.array([1, 2, 3, 4])
b = np.array([False, False, True, True])

This is what I essentially want:

c = np.array([False, False, 3, 4])
  = np.array([0, 0, 3, 4])

I tried various slicing methods including:

a[b]
np.extract()
np.choose()
np.take

These, however, either don't return the shape of the array or only return a bool.

Thanks for any help. BBQuercus

Upvotes: 2

Views: 1225

Answers (1)

yatu
yatu

Reputation: 88236

You can use np.where:

np.where(b, a, 0)
# np.array([0, 0, 3, 4])

Upvotes: 1

Related Questions