Introduction
In this lab, you will learn how to read an MRI image into a NumPy array and display it in grayscale using matplotlib library.
VM Tips
After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.
Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.
If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.
Import required libraries
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cbook as cbook
Load the MRI image data
We will use the get_sample_data function from matplotlib to load the sample MRI image. The image is in 256x256 16-bit integer format.
with cbook.get_sample_data('s1045.ima.gz') as dfile:
im = np.frombuffer(dfile.read(), np.uint16).reshape((256, 256))
Display the MRI image
We will use imshow function from matplotlib to display the MRI image in grayscale.
fig, ax = plt.subplots(num="MRI_demo")
ax.imshow(im, cmap="gray")
ax.axis('off')
plt.show()
Summary
In this lab, you learned how to load an MRI image into a NumPy array and display it in grayscale using matplotlib library. You can use this knowledge to visualize other medical images as well.