Scikit-image 简明教程

Scikit Image - Reading Images

在使用图像处理工具执行裁剪、调整大小、旋转或应用滤镜等操作时,读取图像是一项基本步骤。读取图像的过程涉及获取图像文件中的像素值和元数据,并将它们表示为合适的数据结构,例如 NumPy 数组或矩阵。

在 Scikit-image 库中,io 模块提供了一个 imread() 函数,用于将图像文件作为 NumPy 数组加载到内存中。一旦将图像作为一个 NumPy 数组加载到内存中,我们就可以访问 Scikit-image 中提供的各种图像处理函数,以执行过滤、分割、特征提取等任务。

The imread() method

Scikit-image 中的 io.imread() 方法能够读取各种格式的图像,包括 JPEG、PNG、TIFF、BMP 等。此函数在内部根据特定图像格式(如 imageio、PIL 或 tifffile)使用不同的库。

Syntax

以下是这种方法的语法和参数−

skimage.io.imread(fname, as_gray=False, plugin=None, **plugin_args)
  1. Fname −表示图像文件名称或路径或 URL 的字符串。

  2. as_gray (optional) −如果设置为 True,则将彩色图像转换为表示为 64 位浮点数的灰度图像。不转换已经是灰度格式的图像。

  3. plugin (optional) −指定用于读取图像的插件的字符串。如果未提供 plugin 参数,该函数将自动尝试从 imageio 开始使用不同的插件,直到找到合适的插件。但是,如果文件名 (fname) 具有 ".tiff" 扩展名,则默认使用 tifffile 插件。

  4. **plugin_args (optional) − 传递给指定插件的其他关键字参数。

Return Value

该方法返回一个表示图像的 NumPy 数组。该数组包含像素值,其形状对应于图像的尺寸。图像的颜色波段或通道存储在数组的第三维中。

例如,灰度图像的尺寸为 MxN, ,RGB 图像的尺寸为 MxNx3, ,RGBA 图像的尺寸为 MxNx4.

Example 1

以下示例演示了如何使用文件名加载图像。

import skimage
from skimage import io

# Read an image
image = io.imread('Images/logo.png')

# Display image properties from the image array
print('The following are the properties of the loaded image:')
print("Image shape:", image.shape)
print("Image data type:", image.dtype)
print("Number of color channels:", image.shape[2])
logos
The following are the properties of the loaded image:
Image shape: (225, 225, 4)
Image data type: uint8
Number of color channels: 4

Example 2

以下示例演示了如何使用图像 URL 加载图像。

import skimage
from skimage import io

# Read an image
image = io.imread('https://www.tutorialspoint.com/images/logo.png')

# Display image properties from the image array
print('The following are the properties of the loaded image:')
print("Image shape:", image.shape)
print("Image data type:", image.dtype)
print("Number of color channels:", image.shape[2])
logos
The following are the properties of the loaded image:
Image shape: (140, 568, 3)
Image data type: uint8
Number of color channels: 3

Example 3

以下示例演示了如何使用 imread() 方法的 as_gray 参数将彩色图像转换为灰度。

import skimage
from skimage import io

# Read an image
image = io.imread('https://www.tutorialspoint.com/images/logo.png', as_gray=True)

# Display image properties from the image array
print('The following are the properties of the loaded image:')
print("Image shape:", image.shape)
print("Image data type:", image.dtype)
The following are the properties of the loaded image:
Image shape: (140, 568)
Image data type: float64