Mahotas - RGB 到 LAB 顏色空間轉換



LAB 顏色空間是一個近似人類顏色感知的顏色模型。它將顏色資訊分成三個通道:

  • L(亮度) - L 通道表示感知到的顏色亮度(亮度)。其範圍從 0(最暗黑色)到 100(最亮白色)。

  • A(綠-紅軸) - 表示顏色在綠-紅軸上的位置。負值表示綠色,正值表示紅色。

  • B(藍-黃軸) - 表示顏色在藍-黃軸上的位置。負值表示藍色,正值表示黃色。

在從 RGB 到 LAB 的轉換過程中,每個 RGB 畫素值都被歸一化到 0 到 1 的範圍內。

然後,應用各種數學變換,例如調整亮度,使顏色更準確地符合我們的感知,並將它們轉換為 LAB 值。

這些調整有助於我們以符合人類視覺方式表示顏色。

Mahotas 中的 RGB 到 LAB 轉換

在 Mahotas 中,我們可以使用 colors.rgb2lab() 函式將 RGB 影像轉換為 LAB 影像。

Mahotas 中的 RGB 到 LAB 轉換包括以下步驟:

  • 歸一化 RGB 值 - 首先將每個畫素的 RGB 值調整到 0 到 1 之間的標準化範圍。

  • 伽馬校正 - 對歸一化的 RGB 值應用伽馬校正以調整影像的亮度級別。

  • 線性化 RGB 值 - 將伽馬校正後的 RGB 值轉換為線性 RGB 顏色空間,確保輸入和輸出值之間存線上性關係。

  • 轉換為 XYZ 顏色空間 - 使用變換矩陣將線性 RGB 值轉換為 XYZ 顏色空間,該空間表示影像的顏色資訊。

  • 計算 LAB 值 - 從 XYZ 值中,使用特定公式計算 LAB 值,考慮我們眼睛如何感知顏色。LAB 顏色空間將亮度 (L) 與顏色分量 (A 和 B) 分開。

  • 應用參考白值 - 根據參考白值調整 LAB 值,以確保準確的顏色表示。

  • LAB 表示 - 生成的 LAB 值表示影像的顏色資訊。L 通道表示亮度,而 A 和 B 通道表示沿兩個軸的顏色資訊。

使用 mahotas.colors.rgb2lab() 函式

mahotas.colors.rgb2lab() 函式以 RGB 影像作為輸入,並返回影像的 LAB 顏色空間版本。

生成的 LAB 影像保留了原始 RGB 影像的結構和內容,同時提供了增強的顏色表示。

語法

以下是 mahotas 中 rgb2lab() 函式的基本語法:

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

其中:

  • rgb - 它是 RGB 顏色空間中的輸入影像。

  • dtype (可選) - 它是返回影像的資料型別(預設為浮點數)。

示例

在下面的示例中,我們使用 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 到 LAB 轉換

我們可以透過以下方式將隨機生成的 RGB 影像轉換為 LAB 顏色空間:

  • 首先,定義影像的所需大小,指定其寬度和高度。
  • 我們還確定顏色深度,通常為 8 位,範圍從 0 到 255。
  • 接下來,我們使用 NumPy 的 "random.randint()" 函式為影像中的每個畫素生成隨機 RGB 值。
  • 獲得 RGB 影像後,我們將其轉換為 LAB 顏色空間。

生成的影像將位於 LAB 顏色空間中,其中影像的亮度和顏色資訊被分離到不同的通道中。

示例

以下示例顯示了將隨機生成的 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
廣告