Scikit-image 简明教程

Scikit Image - Using Matplotlib

Matplotlib 是 Python 中一个被广泛使用的绘图库,它提供各种用于创建不同类型的图表和可视化的函数。它是一个功能强大的库,支持使用 Python 编程语言创建静态、动画和交互式可视化。

Scikit Image with Matplotlib

当涉及到在图像处理上下文中将可视化图像时,Matplotlib 可以与 scikit-image 库结合使用,以实现各种可视化任务。通常,Scikit-image 库提供如 io.imshow() 和 io.show() 之类的函数来显示图像,但是我们可以使用 Matplotlib 的 imshow() 函数来显示图像,并使用其它选项,如注释、颜色映射、坐标轴配置等。

此外,它可能有助于在一个图中创建多个图表(即子图),以比较图像的不同版本或显示图像处理流程中的中间步骤。

若要设置用于 scikit-image 的 Matplotlib,你需要确保同时已安装并正确配置这两个库。建议使用 pip 或 conda 等软件包管理器来安装 Matplotlib。pip 是 Python 的默认软件包管理器,而 Conda 是在 Anaconda 环境中管理软件包的常用选择。

Installing Matplotlib using pip

若要使用 pip 安装 Matplotlib,只需在命令提示符中运行以下命令:

pip install Matplotlib

它将下载 Matplotlib 软件包。

Installing Matplotlib using Conda

如果你已在系统中使用了 Anaconda 发行版,那么你可以直接使用 conda 软件包管理器来安装 Matplotlib。以下是命令:

conda install matplotlib

成功安装后,你可以直接导入 matplotlib.pyplot 和 skimage 库,以在 Python 脚本或笔记本中访问所需功能,以便执行图像处理任务。

以下是几个基本的 Python 程序,演示如何将 Matplotlib 库与 scikit-image 一起如何有效执行数据可视化任务。

Example 1

以下示例演示如何使用 Matplotlib 显示由 scikit-image 加载的图像。

from skimage import io
import matplotlib.pyplot as plt

# Read an image
image_data = io.imread('Images/logo-w.png')
# Display the image using Matplotlib
plt.imshow(image_data)
plt.title('Logo', fontsize=18)

执行上述程序时,你将得到以下输出:

matplotlib 1

Example 2

以下示例演示如何使用 scikit-image 将圆形蒙版应用于图像,并使用 Matplotlib 并排显示原始图像和蒙版图像。

import matplotlib.pyplot as plt
from skimage import io
import numpy as np

# Load the image
image_path = 'Images_/Zoo.jpg'
image = io.imread(image_path)
image_copy = np.copy(image)

# Create circular mask
rows, cols, _ = image.shape
row, col = np.ogrid[:rows, :cols]
center_row, center_col = rows / 2, cols / 2
radius = min(rows, cols) / 2
outer_disk_mask = ((row - center_row)**2 + (col - center_col)**2 > radius**2)

# Apply mask to image
image[outer_disk_mask] = 0

# Display the original and masked images using Matplotlib
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(10, 5))
axes[0].imshow(image_copy)
axes[0].set_title('Original Image')
axes[0].axis('off')
axes[1].imshow(image)
axes[1].set_title('Masked Image')
axes[1].axis('off')
plt.tight_layout()
plt.show()

执行上述程序时,你将得到以下输出:

matplotlib 2