使用 Matplotlib 进行 MRI 图像可视化

PythonPythonBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本实验中,你将学习如何将 MRI 图像读取到 NumPy 数组中,并使用matplotlib库以灰度显示它。

虚拟机使用提示

虚拟机启动完成后,点击左上角切换到笔记本标签页,以访问 Jupyter Notebook 进行练习。

有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,请随时向 Labby 提问。课程结束后提供反馈,我们将立即为你解决问题。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL matplotlib(("Matplotlib")) -.-> matplotlib/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/ModulesandPackagesGroup(["Modules and Packages"]) python(("Python")) -.-> python/FileHandlingGroup(["File Handling"]) matplotlib(("Matplotlib")) -.-> matplotlib/PlottingDataGroup(["Plotting Data"]) python(("Python")) -.-> python/DataScienceandMachineLearningGroup(["Data Science and Machine Learning"]) matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("Importing Matplotlib") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("Understanding Figures and Axes") matplotlib/PlottingDataGroup -.-> matplotlib/heatmaps("Heatmaps") python/DataStructuresGroup -.-> python/tuples("Tuples") python/ModulesandPackagesGroup -.-> python/importing_modules("Importing Modules") python/FileHandlingGroup -.-> python/file_reading_writing("Reading and Writing Files") python/FileHandlingGroup -.-> python/with_statement("Using with Statement") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("Numerical Computing") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("Data Visualization") subgraph Lab Skills matplotlib/importing_matplotlib -.-> lab-48833{{"使用 Matplotlib 进行 MRI 图像可视化"}} matplotlib/figures_axes -.-> lab-48833{{"使用 Matplotlib 进行 MRI 图像可视化"}} matplotlib/heatmaps -.-> lab-48833{{"使用 Matplotlib 进行 MRI 图像可视化"}} python/tuples -.-> lab-48833{{"使用 Matplotlib 进行 MRI 图像可视化"}} python/importing_modules -.-> lab-48833{{"使用 Matplotlib 进行 MRI 图像可视化"}} python/file_reading_writing -.-> lab-48833{{"使用 Matplotlib 进行 MRI 图像可视化"}} python/with_statement -.-> lab-48833{{"使用 Matplotlib 进行 MRI 图像可视化"}} python/numerical_computing -.-> lab-48833{{"使用 Matplotlib 进行 MRI 图像可视化"}} python/data_visualization -.-> lab-48833{{"使用 Matplotlib 进行 MRI 图像可视化"}} end

导入所需库

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cbook as cbook

加载 MRI 图像数据

我们将使用matplotlib中的get_sample_data函数来加载示例 MRI 图像。该图像为 256x256 的 16 位整数格式。

with cbook.get_sample_data('s1045.ima.gz') as dfile:
    im = np.frombuffer(dfile.read(), np.uint16).reshape((256, 256))

显示 MRI 图像

我们将使用matplotlib中的imshow函数以灰度显示 MRI 图像。

fig, ax = plt.subplots(num="MRI_demo")
ax.imshow(im, cmap="gray")
ax.axis('off')
plt.show()

总结

在本实验中,你学习了如何将 MRI 图像加载到 NumPy 数组中,并使用matplotlib库以灰度显示它。你也可以运用这些知识来可视化其他医学图像。