I\'m trying to mask a 3D array (RGB image) with numpy.
However, my current approach is reshaping the masked array (output below). I have tried to follow the approach
After finding the following post on loss of dimensions HERE, I have found a solution using numpy.where:
masked_array = np.where(mask==1, a , 0)
This appears to work well.
NumPy broadcasting allows you to use a mask with a different shape than the image. E.g.,
import numpy as np
import matplotlib.pyplot as plt
# Construct a random 50x50 RGB image
image = np.random.random((50, 50, 3))
# Construct mask according to some condition;
# in this case, select all pixels with a red value > 0.3
mask = image[..., 0] > 0.3
# Set all masked pixels to zero
masked = image.copy()
masked[mask] = 0
# Display original and masked images side-by-side
f, (ax0, ax1) = plt.subplots(1, 2)
ax0.imshow(image)
ax1.imshow(masked)
plt.show()