Mahotas - 載入影像為灰度



灰度影像是黑白影像或灰色單色的一種,僅由灰色陰影組成。對比度範圍從黑色到白色,分別為最弱強度到最強強度。

灰度影像僅包含亮度資訊,不包含顏色資訊。這就是白色是最大亮度(亮度)而黑色是零亮度的原因,介於兩者之間的一切都包含灰色陰影。

載入灰度影像

在 Mahotas 中,載入灰度影像涉及讀取僅包含每個畫素強度值的影像檔案。生成的影像表示為一個二維陣列,其中每個元素表示畫素的強度。

以下是 Mahotas 中載入灰度影像的基本語法:

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

其中,'image.file_format' 是要載入的影像的實際路徑和格式,'as_grey=True' 作為引數傳遞以指示我們要將影像載入為灰度。

示例

以下是 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

載入不同的影像格式為灰度

影像格式是指用於以數字方式儲存和編碼影像的不同檔案格式。每種格式都有其自身的規範、特性和壓縮方法。

Mahotas 提供了廣泛的影像格式,包括 JPEG、PNG、BMP、TIFF 和 GIF 等常用格式。我們可以將任何這些格式的灰度影像的檔案路徑傳遞給 imread() 函式。

示例

在此示例中,我們透過使用 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

使用顏色模式“L”

“L”顏色模式表示亮度,它是顏色亮度的度量。它源自 RGB(紅、綠、藍)顏色模型,其中紅色、綠色和藍色通道的強度值組合在一起以計算灰度強度。“L”模式丟棄顏色資訊,並僅使用灰度強度值表示影像。

要在 mahotas 中透過將顏色模式指定為“L”來載入影像為灰度,我們需要將引數 as_grey='L' 傳遞給 imread() 函式。

示例

在這裡,我們正在載入灰度影像並將顏色模式指定為“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
廣告