Mahotas - 影像膨脹



在影像處理中,影像膨脹是指擴充套件影像的畫素。

膨脹過程會在影像邊緣新增畫素。這是因為演算法檢視影像中的每個畫素並檢查其相鄰畫素。

如果任何相鄰畫素是物體的一部分,它會將這些畫素新增到物體的邊界。

在 Mahotas 中膨脹影像

在 Mahotas 中膨脹影像是指向影像中區域的邊界新增畫素數。此操作通常用於增強或修改影像中的形狀和結構。

我們可以使用dilate()函式在 mahotas 中膨脹影像。它用於使用結構元素 B 擴充套件元素 A。

結構元素是一個小的矩陣或形狀,定義每個畫素周圍的鄰域。它用於確定在膨脹過程中應考慮哪些畫素。

mahotas.dilate() 函式

mahotas.dilate() 函式將輸入影像和結構元素作為引數,並返回一個新的 NumPy 陣列。

輸出畫素的值由鄰域中所有畫素的最大值確定。如果任何相鄰畫素的值為 1,則輸出畫素設定為 1。

dilate() 函式逐畫素掃描影像,並檢查由結構元素定義的鄰域。

如果任何相鄰畫素是物體的一部分,膨脹操作會將這些畫素新增到物體的邊界,使其變大。

語法

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

mahotas.dilate(A, Bc=None, out=None, output=None)

其中,

  • A − 它是將對其執行膨脹的輸入影像。它可以是表示灰度或二值影像資料的二維或三維 NumPy 陣列。

  • Bc (可選) − 它是用於膨脹的結構元素。預設為 None。

  • out (已棄用) / output (可選) − 它指定用於儲存結果的輸出陣列。如果未提供,則建立一個新陣列並將其作為輸出返回。

示例

以下是使用 dilate() 函式在 mahotas 中膨脹影像的基本示例:

import mahotas as mh
import matplotlib.pyplot as plt
import numpy as np
image = mh.imread('nature.jpeg', as_grey=True).astype(np.uint8)
# Performing dilation with a square kernel of size 3x3
dilated_image = mh.dilate(image, Bc=mh.disk(3))
# Create a figure with subplots
fig, axes = plt.subplots(1, 2, figsize=(7,5 ))
# Display the original image
axes[0].imshow(image)
axes[0].set_title('Original Image')
axes[0].axis('off')
# Display the dilated image
axes[1].imshow(dilated_image, cmap='gray')
axes[1].set_title('Dilated Image')
axes[1].axis('off')
# Adjust the layout and display the plot
plt.tight_layout()
plt.show()

輸出

執行上述程式碼後,我們將獲得如下輸出:

Dilating Image

使用不同的結構元素大小進行膨脹

我們還可以使用不同的結構元素大小來膨脹影像,以增強影像的不同方面。這些元素使用 Mahotas disk() 函式建立不同的大小。

透過為結構元素選擇不同的半徑或大小,我們可以獲得不同的效果。首先,我們使用最大的結構元素進行膨脹。然後,我們繼續使用較小的結構元素進行額外的膨脹。

這種方法允許我們以多種方式修改影像,增強特定特徵並獲得所需的視覺效果。

示例

在這裡,我們嘗試使用不同的結構元素大小來膨脹影像:

import mahotas as mh
import numpy as np
from pylab import imshow, show
image = mh.imread('nature.jpeg', as_grey=True).astype(np.uint8)
# Performing dilation with the largest structuring element
largest_se = mh.disk(8)
dilated_image = mh.dilate(image, Bc=largest_se)
# Performing additional dilations with smaller structuring elements
smaller_se_1 = mh.disk(2)
smaller_se_2 = mh.disk(5)
dilated_image = mh.dilate(dilated_image, Bc=smaller_se_1)
dilated_image = mh.dilate(dilated_image, Bc=smaller_se_2)
# Displaying the dilated image
imshow(dilated_image)
show()

輸出

獲得的輸出如下所示:

Structuring Element Sizes

使用圓形核心進行膨脹

要建立圓形核心,我們可以使用 Mahotas 的 disk() 函式。透過指定所需的半徑,此函式會生成一個表示圓形核心的 NumPy 陣列。

準備好影像和圓形核心後,我們可以進行膨脹。此操作將圓形核心應用於影像的每個畫素,相應地擴充套件白色區域。

簡單來說,它增強了影像中的明亮區域,使其更大。

示例

現在,我們正在使用圓形核心膨脹影像:

import mahotas as mh
import numpy as np
from pylab import imshow, show
# Load image
image = mh.imread('sun.png', as_grey=True).astype(np.uint8)
# Circular kernel with radius 5
radius = 5
kernel = mh.disk(radius)
dilated_image = mh.dilate(image, kernel)
# Display the dilated image
imshow(dilated_image)
show()

輸出

以下是上述程式碼的輸出:

Circular-shaped Kernel
廣告