Apply a mask
Although masks are binary, they can be applied to images to filter out pixels where the mask is False
.
NumPy's where()
function is a flexible way of applying masks. It takes three arguments:
np.where(condition, x, y)
condition
, x
and y
can be either arrays or single values. This allows you to pass through original image values while setting masked values to 0.
Let's practice applying masks by selecting the bone-like pixels from the hand x-ray (im
).
This is a part of the course
“Biomedical Image Analysis in Python”
Exercise instructions
- Create a Boolean bone mask by selecting pixels greater than or equal to 145.
- Apply the mask to your image using
np.where()
. Values not in the mask should be set to0
. - Create a histogram of the masked image. Use the following arguments to select only non-zero pixels:
min=1
,max=255
,bins=255
. - Plot the masked image and the histogram. This has been done for you.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Import SciPy's "ndimage" module
____
# Screen out non-bone pixels from "im"
mask_bone = ____
im_bone = np.where(____, ____, ____)
# Get the histogram of bone intensities
hist = ____
# Plot masked image and histogram
fig, axes = plt.subplots(2,1)
axes[0].imshow(im_bone)
axes[1].plot(hist)
format_and_render_plot()
This exercise is part of the course
Biomedical Image Analysis in Python
Learn the fundamentals of exploring, manipulating, and measuring biomedical image data.
Cut image processing to the bone by transforming x-ray images. You'll learn how to exploit intensity patterns to select sub-regions of an array, and you'll use convolutional filters to detect interesting features. You'll also use SciPy's ndimage module, which contains a treasure trove of image processing tools.
Exercise 1: Image intensitiesExercise 2: IntensityExercise 3: HistogramsExercise 4: MasksExercise 5: Create a maskExercise 6: Apply a maskExercise 7: Tune a maskExercise 8: FiltersExercise 9: Filter convolutionsExercise 10: Filter functionsExercise 11: SmoothingExercise 12: Feature detectionExercise 13: Detect edges (1)Exercise 14: Detect edges (2)What is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.