Q:

Applying a 2D numpy mask to grayscale image

I have a 256×256 px 2D mask with pixel values of either 0 or 255, and a matching grayscale image.  Both have shapes (256, 256). 
I'd like to apply the mask on the grayscale image so the resulting image only contains pixels from the original grayscale image, where corresponding mask values are 255 (the original grayscale pixel values should be preserved). 
I'm not being able to do this using
img_clean = img_grayscale[mask]

as it adds a new dimension to the array (as mentioned in numpy's docs). 
How do I resolve this? 

A:

Just to add a 3rd option and modify your gray scale image inplace:
img_grayscale[mask == 255] = 0

PS: you can just create a copy if you don't want in-place modifications. 

A:

I think this should do the job
np.where(mask == 255, img_grayscale, 0)

See https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html for documentation. 

A:

A bitwise AND can be used to in order to set the pixel values to 0 where the mask is 0:
img_clean = img_grayscale & mask

As the mask contains either 0 or 255 values are either kept the same or set to 0 as per your requirements.