Mahotas 简明教程

Mahotas - RGB to LAB Conversion

LAB 颜色空间是一种逼近人类色彩感知的颜色模型。它将颜色信息分成三个通道 −

  1. L (Lightness) − L 通道表示颜色的感知亮度(明暗)。范围从 0(最暗黑色)到 100(最亮白色)。

  2. A (Green-Red axis) − 表示颜色在绿-红轴上的位置。负值表示绿色,正值表示红色。

  3. B (Blue-Yellow axis) − 表示颜色在蓝-黄轴上的位置。负值表示蓝色,正值表示黄色。

在从 RGB 转换为 LAB 的过程中,每个 RGB 像素值都将标准化为 0 和 1 的范围。

然后,应用各种数学变换,例如调整亮度、使色彩更符合我们的感知方式,以及将它们转换为 LAB 值。

这些调整有助于我们以符合人类观察方式的方式呈现色彩。

RGB to LAB Conversion in Mahotas

在 Mahotas 中,我们可以使用 colors.rgb2lab() 函数将 RGB 图像转换为 LAB 图像。

Mahotas 中的 RGB 到 LAB 转换涉及以下步骤 −

  1. Normalize RGB values − 首先将每个像素的 RGB 值调整到 0 和 1 之间的标准化范围。

  2. Gamma correction − 应用伽马校正到标准化 RGB 值以调整图像的亮度级别。

  3. Linearize RGB values − 将伽马校正的 RGB 值转换为线性 RGB 色彩空间,确保输入和输出值之间的线性关系。

  4. Convert to XYZ color space − 使用变换矩阵,将线性 RGB 值转换为 XYZ 色彩空间,它表示图像的色彩信息。

  5. Calculate LAB values − 使用特定公式从 XYZ 值计算 LAB 值,考虑我们的眼睛如何感知色彩。LAB 色彩空间将亮度 (L) 与色彩分量 (A 和 B) 分开。

  6. Apply reference white values − 根据参考白值调整 LAB 值以确保准确的色彩表示。

  7. LAB representation − 结果的 LAB 值表示图像的色彩信息。L 通道表示明度,而 A 和 B 通道表示沿两个轴的色彩信息。

Using the mahotas.colors.rgb2lab() Function

mahotas.colors.rgb2lab() 函数以 RGB 图像作为输入,并返回图像的 LAB 色彩空间版本。

所生成的 LAB 图像保留原始 RGB 图像的结构和内容,同时提供增强的色彩表示。

以下是 mahotas 中 rgb2lab() 函数的基本语法 −

mahotas.colors.rgb2lab(rgb, dtype={float})

其中,

  1. rgb − RGB 颜色空间中的输入图像。

  2. dtype (optional) − 是返回图像的数据类型(默认为 float)。

在以下示例中,我们使用 mh.colors.rgb2lab() 函数将 RGB 图像转换为 LAB 图像 −

import mahotas as mh
import numpy as np
import matplotlib.pyplot as mtplt
# Loading the image
image = mh.imread('sea.bmp')
# Converting it to LAB
lab_image = mh.colors.rgb2lab(image)
# Creating a figure and axes for subplots
fig, axes = mtplt.subplots(1, 2)
# Displaying the original RGB image
axes[0].imshow(image)
axes[0].set_title('RGB Image')
axes[0].set_axis_off()
# Displaying the LAB image
axes[1].imshow(lab_image)
axes[1].set_title('LAB Image')
axes[1].set_axis_off()
# Adjusting spacing between subplots
mtplt.tight_layout()
# Showing the figures
mtplt.show()

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

lab color space

RGB to LAB Conversion of a Random Image

我们可以通过以下方式将随机生成的 RGB 图像转换为 LAB 色彩空间 −

  1. 首先,指定图像的宽度和高度来定义所需的大小。

  2. 我们还确定色深,通常为 8 位,范围从 0 到 255。

  3. 接下来,我们使用 NumPy 的“random.randint()”函数为图像中的每个像素生成随机 RGB 值。

  4. 一旦我们拥有 RGB 图像,我们便继续将其转换到 LAB 颜色空间。

结果图像将位于 LAB 颜色空间中,其中图像的亮度和颜色信息被分离到不同的通道中。

Example

以下示例显示了将随机生成的 RGB 图像转换为 LAB 颜色空间中的图像:

import mahotas as mh
import numpy as np
import matplotlib.pyplot as mtplt
# Creating a random RGB image
image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
# Converting it to LAB
lab_image = mh.colors.rgb2lab(image)
# Creating a figure and axes for subplots
fig, axes = mtplt.subplots(1, 2)
# Displaying the original RGB image
axes[0].imshow(image)
axes[0].set_title('RGB Image')
axes[0].set_axis_off()
# Displaying the LAB image
axes[1].imshow(lab_image)
axes[1].set_title('LAB Image')
axes[1].set_axis_off()
# Adjusting spacing between subplots
mtplt.tight_layout()
# Showing the figures
mtplt.show()

上述代码的输出如下:

rgb lab image