Mahotas 简明教程

Mahotas - Loading Image as Grey

灰度图像是一种黑白图像或灰色单色图像,仅由灰色阴影组成。对比度范围从黑色到白色,分别是最低强度到最高强度。

灰度图像仅包含亮度信息,但不包含颜色信息。这是白色表示最高亮度(亮度),而黑色表示零亮度的主要原因,介于两者之间的所有内容都由灰色阴影组成。

Loading Grayscale Images

在 Mahotas 中,加载灰度图像涉及读取一个图像文件,该文件仅包含每个像素的强度值。生成图像表示为一个 2D 数组,其中每个元素表示像素的强度。

以下是 Mahotas 中加载灰度图像的基本语法 −

mahotas.imread('image.file_format', as_grey=True)

其中, 'image.file_format' 是要加载的图像的实际路径和格式, 'as_grey=True' 作为参数传递,表示我们要将图像加载为灰度。

Example

以下是 Mahotas 中加载灰度图像的示例 −

import mahotas as ms
import matplotlib.pyplot as mtplt
# Loading grayscale image
grayscale_image = ms.imread('nature.jpeg', as_grey=True)
# Displaying grayscale image
mtplt.imshow(grayscale_image, cmap='gray')
mtplt.axis('off')
mtplt.show()

执行以上代码后,我们得到如下所示的输出 −

loading grayscale images

Loading Different Image Formats as Grayscale

图像格式是指用于以数字方式存储和编码图像的不同文件格式。每种格式都有自己的规范、特性和压缩方法。

Mahotas 提供了多种图像格式,包括 JPEG、PNG、BMP、TIFF 和 GIF 等常见格式。我们可以将任何这些格式中灰度图像的文件路径传递给 imread() 函数。

Example

在此示例中,我们通过使用 imread() 函数加载不同格式的灰度图像来说明 Mahotas 的多功能性。每张加载的图像都存储在单独的变量中 −

import mahotas as ms
import matplotlib.pyplot as mtplt
# Loading JPEG image
image_jpeg = ms.imread('nature.jpeg', as_grey = True)
# Loading PNG image
image_png = ms.imread('sun.png',as_grey = True)
# Loading BMP image
image_bmp = ms.imread('sea.bmp',as_grey = True)
# Loading TIFF image
image_tiff = ms.imread('tree.tiff',as_grey = True)
# Creating a figure and subplots
fig, axes = mtplt.subplots(2, 2)
# Displaying JPEG image
axes[0, 0].imshow(image_jpeg)
axes[0, 0].axis('off')
axes[0, 0].set_title('JPEG Image')
# Displaying PNG image
axes[0, 1].imshow(image_png)
axes[0, 1].axis('off')
axes[0, 1].set_title('PNG Image')
# Displaying BMP image
axes[1, 0].imshow(image_bmp)
axes[1, 0].axis('off')
axes[1, 0].set_title('BMP Image')
# Displaying TIFF image
axes[1, 1].imshow(image_tiff)
axes[1, 1].axis('off')
axes[1, 1].set_title('TIFF Image')
# Adjusting the spacing and layout
mtplt.tight_layout()
# Showing the figure
mtplt.show()

显示的图像如下 −

different grayscale formats

Using the Color Mode 'L'

“L”颜色模式表示亮度,它是颜色亮度的度量。它源自 RGB(红色、绿色、蓝色)颜色模型,其中红色、绿色和蓝色通道的强度值组合在一起以计算灰度强度。“L”模式舍弃颜色信息并仅使用灰度强度值表示图像。

要通过在 mahotas 中将颜色模式指定为“L”加载图像作为灰色,我们需要将参数 as_grey='L' 传递给 imread() 函数。

Example

在这里,我们正在加载灰度图像并将颜色模式指定为“L” −

import mahotas as ms
import matplotlib.pyplot as mtplt
# Loading grayscale image
image = ms.imread('sun.png')
grayscale_image = ms.imread('sun.png', as_grey = 'L')
# Creating a figure and subplots
fig, axes = mtplt.subplots(1, 2)
# Displaying original image
axes[0].imshow(image)
axes[0].axis('off')
axes[0].set_title('Original Image')
# Displaying grayscale image
axes[1].imshow(grayscale_image, cmap='gray')
axes[1].axis('off')
axes[1].set_title('Grayscaled Image')
# Adjusting the spacing and layout
mtplt.tight_layout()
# Showing the figure
mtplt.show()

以下是上面代码的输出: -

color mode l