Apply A Mask | Python - DataCamp

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 exercise is part of the course

Biomedical Image Analysis in Python

View Course

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 to 0.
  • 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()Edit and Run Code

This exercise is part of the course

Biomedical Image Analysis in Python

IntermediateSkill Level4.8+134 reviewsStart Course for Free

Chapter 1: Exploration

Prepare to conquer the Nth dimension! To begin the course, you'll learn how to load, build and navigate N-dimensional images using a CT image of the human chest. You'll also leverage the useful ImageIO package and hone your NumPy and matplotlib skills.

Exercise 1: Image dataExercise 2: Load imagesExercise 3: MetadataExercise 4: Plot imagesExercise 5: N-dimensional imagesExercise 6: Stack imagesExercise 7: Load volumesExercise 8: Field of viewExercise 9: Advanced plottingExercise 10: Generate subplotsExercise 11: Slice 3D imagesExercise 12: Plot other views

Chapter 2: Masks and Filters

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 mask

Current Exercise

Exercise 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)

Chapter 3: Measurement

In this chapter, you'll get to the heart of image analysis: object measurement. Using a 4D cardiac time series, you'll determine if a patient is likely to have heart disease. Along the way, you'll learn the fundamentals of image segmentation, object labeling, and morphological measurement.

Exercise 1: Objects and labelsExercise 2: Segment the heartExercise 3: Select objectsExercise 4: Extract objectsExercise 5: Measuring intensityExercise 6: Measure varianceExercise 7: Separate histogramsExercise 8: Measuring morphologyExercise 9: Calculate volumeExercise 10: Calculate distanceExercise 11: Pinpoint center of massExercise 12: Measuring in timeExercise 13: Summarize the time seriesExercise 14: Measure ejection fraction

Chapter 4: Image Comparison

For the final chapter, you'll need to use your brain... and hundreds of others! Drawing data from more than 400 open-access MR images, you'll learn the basics of registration, resampling, and image comparison. Then, you'll use the extracted measurements to evaluate the effect of Alzheimer's Disease on brain structure.

Exercise 1: Spatial transformationsExercise 2: TranslationsExercise 3: RotationsExercise 4: Affine transformExercise 5: Resampling and interpolationExercise 6: ResamplingExercise 7: InterpolationExercise 8: Comparing imagesExercise 9: Mean absolute errorExercise 10: Intersection of the unionExercise 11: Normalizing measurementsExercise 12: Identifying potential confoundsExercise 13: Testing group differencesExercise 14: Normalizing metrics

Tag » How To Mask In Python