Mahotas - 填充影像中的孔洞



填充影像中的孔洞是指去除影像前景區域中的小間隙或孔洞。在閉運算過程中,首先執行膨脹操作,然後執行腐蝕操作。

膨脹擴充套件前景區域的邊界。對於每個畫素,膨脹操作根據結構元素檢查其鄰域。

如果任何鄰域畫素為白色,則中心畫素也變為白色。此過程有助於填充前景區域內的間隙或孔洞。

膨脹後,腐蝕收縮前景區域的邊界。同樣,使用結構元素,腐蝕檢查每個畫素及其鄰域。如果任何鄰域畫素為黑色,則中心畫素變為黑色。

此步驟有助於細化和平滑前景區域的輪廓,同時保留主要結構。

在 Mahotas 中填充影像中的孔洞

要在 Mahotas 中執行填充孔洞的過程,我們使用 mahotas.close_holes() 函式。此方法允許順序應用膨脹和腐蝕操作。

透過首先應用膨脹操作(擴充套件區域),然後應用腐蝕操作(細化邊界),閉運算有效地關閉了二值影像前景區域中的小孔洞或間隙。

mahotas.close_holes() 函式

Mahotas 中的 close_holes() 函式將二值影像作為輸入,並返回具有已填充孔洞的結果影像。

close_holes() 函式會自動檢測並填充孔洞,而無需顯式定義結構元素。

語法

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

mahotas.close_holes(ref, Bc=None)

其中,

  • ref − 輸入的二值影像。

  • Bc − 指定用於閉運算的結構元素或核心。如果未提供(設定為 None),則將使用預設結構元素。

示例

在以下示例中,我們正在填充影像中的孔洞:

import mahotas as mh
import numpy as np
import matplotlib.pyplot as plt
image = mh.imread('pic.jpg',as_grey = True)
closed_holes_image = mh.close_holes(image)
# 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 closed holes image
axes[1].imshow(closed_holes_image, cmap='gray')
axes[1].set_title('Closed Holes Image')
axes[1].axis('off')
# Adjust the layout and display the plot
plt.tight_layout()
plt.show()

輸出

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

Closing Holes Image

使用隨機二值影像

我們還可以透過建立隨機二值影像來執行填充影像孔洞的過程。

為此,我們首先使用 NumPy 建立一個隨機二值影像,其中畫素為 0(背景)或 1(前景)。

獲得二值影像後,我們可以透過使用結構元素執行形態學閉運算。

它將定義膨脹和腐蝕操作的鄰域的形狀和大小。最後,我們得到影像中已填充的孔洞的結果。

示例

在這裡,我們嘗試透過建立隨機二值影像來執行填充影像孔洞的過程:

import mahotas as mh
import numpy as np
from pylab import imshow, show
# Create a random binary image
image = np.random.randint(0, 2, size=(100, 50), dtype=np.bool_)
Bc=np.ones((3,3))
# Perform morphological closing holes with a 3x3 cross structuring element
result = mh.close_holes(image, Bc)
# Show the result
imshow(result)
show()

輸出

產生的輸出如下所示:

Closing Holes Image

多次迭代填充孔洞

對於多次迭代填充孔洞,我們的目標是逐漸填充較小的孔洞並反覆細化結果。

我們首先建立原始二值影像的副本。此副本將作為孔洞填充過程每次迭代的起點。然後,使用 for 迴圈,我們迭代指定的次數。

在每次迭代中,mahotas.close_holes() 函式應用於影像的當前版本。該函式識別影像中的孔洞並填充它們,逐漸改善前景區域的連通性和連續性。

示例

現在,我們正在多次迭代填充影像中的孔洞:

import mahotas
import numpy as np
import matplotlib.pyplot as plt
image = mahotas.imread('pic.jpg', as_grey = True)
# Close the holes in the binary image with multiple iterations
closed_image = image.copy()
for i in range(3):
   closed_image = mahotas.close_holes(closed_image)
# Display the original and closed images
fig, axes = plt.subplots(1, 2, figsize=(10, 5))
axes[0].imshow(image, cmap='gray')
axes[0].set_title('Original Image')
axes[1].imshow(closed_image, cmap='gray')
axes[1].set_title('Closed Image')
plt.tight_layout()
plt.show()

輸出

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

Closing Holes Multiple Images
廣告