intersect image with mask in skimage

Viewed 4925

I've loaded an image into the scikit-image library in Python. I've also created a mask of the same dimensions as the image, and now I want to intersect the mask with the image to only show pixels from the image where the mask is non-zero. How can I do that without iterating pixel by pixel?

Do I just apply the mask to the image, like:

new_image = image[mask]

Or can I just multiply the two image arrays together to do bitwise multiplication pixel by pixel?

2 Answers

Element-wise multiplication indeed works perfectly:

from skimage import data
from matplotlib import pyplot as plt

image = data.coins()
mask = image > 128
masked_image = image * mask

fig, (ax0, ax1) = plt.subplots(nrows=1, ncols=2)
ax0.imshow(image, cmap='gray')
ax1.imshow(masked_image, cmap='gray')

enter image description here

Note 1: your code example is not a scikit-image question but a NumPy indexing question, and will not do what you want, but rather return a linear array of all the pixels where mask is True. For more information, see the NumPy documentation on boolean indexing.

Note 2: you can also use scikit-image to save images:

from skimage import io
io.imsave('masked_image.png', masked_image)

You can do it like this:

from skimage import data
import numpy as np
from PIL import Image

# Load coins data-set
im = data.coins()

# Make mask of where image is less than mid-grey
mask = im<128

# Set image black everywhere it was less than mid-grey
im[mask] = 0

# Set image mid-grey everywhere it was mid-grey or brighter
im[~mask] = 128

# Convert to PIL image and save
Image.fromarray(im).save('result.png')

Starting image of coins:

enter image description here

Resulting image:

enter image description here

Related