Mahotas 简明教程

Mahotas - Closing Holes in an Image

闭合图像中的孔洞是指移除图像前景区域中的小间隙或孔洞。在闭合过程中,首先执行膨胀操作,然后是腐蚀操作。

膨胀会扩展前景区域的边界。对于每个像素,膨胀操作会根据结构元素检查其相邻像素。

如果任何相邻像素为白色,中心像素也会变为白色。此过程有助于填补前景区域中的间隙或孔洞。

膨胀之后,腐蚀会收缩前景区域的边界。同样,通过使用结构元素,腐蚀会检查每个像素及其相邻像素。如果任何相邻像素为黑色,中心像素也会变为黑色。

此步骤有助于优化前景区域的轮廓,同时保留主要结构。

Closing Holes in an Image in Mahotas

要执行 Mahotas 中的闭合孔洞过程,我们使用 mahotas.close_holes() 函数。此方法允许顺序执行膨胀和腐蚀操作。

通过首先应用膨胀操作(扩展区域),然后应用腐蚀操作(优化边界),闭合操作可以有效闭合二进制图像中前景区域的小孔洞或间隙。

The mahotas.close_holes() function

Mahotas 中的close_holes() 函数以二进制图像为输入,并返回孔洞闭合后的结果图像。

close_holes() 函数会自动检测并闭合孔洞,而无需显式定义结构元素。

Syntax

以下是 mahotas 中 close_holes() 函数的基本语法 -

mahotas.close_holes(ref, Bc=None)

其中,

  1. ref - 它是输入二进制图像。

  2. Bc - 它指定用于闭合操作的结构元素或内核。如果没有提供(设置为 None),将使用默认结构元素。

Example

在以下示例中,我们正在闭合图像中的孔洞 -

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

Using Random Binary Image

我们还可以通过创建随机二进制图像在图像中执行闭合孔洞过程。

要实现此目的,我们首先使用 NumPy 创建一个随机二进制图像,其中像素为 0(背景)或 1(前景)。

拥有二进制图像后,我们可以使用结构元素执行形态学闭运算。

它将定义膨胀和腐蚀运算的邻域形状和大小。最后,我们在图像中获得了结果闭孔。

Example

在此处,我们正试图通过创建随机二进制图像 − 在图像中执行闭孔过程

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 image1

Closing Holes with Multiple Iterations

对于多重迭代的闭孔,我们旨在逐渐填充较小的孔并重复精炼结果。

我们从创建原始二进制图像的副本开始。此副本将作为孔闭合过程的每个迭代的起点。然后,使用 for 循环,我们指定迭代次数。

在每次迭代中,mahotas.close_holes() 函数应用于图像的当前版本。此函数识别图像中的孔并填充孔,逐步提高了前景区域的连通性和连续性。

Example

现在,我们正使用多次迭代关闭图像中的孔 −

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 image