Mahotas 简明教程
Mahotas - Opening Process on Image
开是指图像处理中使用的两步过程。首先,执行腐蚀操作,然后执行膨胀操作。
腐蚀通过检查每个像素及其相邻像素来收缩或去除不需要的细节。如果任何相邻像素是黑色的,则中心像素也会变成黑色。
这一步有助于消除细小的突起和内部噪声。突起是从表面向外延伸的细长结构。
在腐蚀之后,执行膨胀以扩展或加粗图像。它查看每个像素及其邻居,如果任何相邻像素为白色,则中心像素将变为白色。
开有效地去除了小的细节和噪声,同时保留了图像的主要结构。
Opening Process on Image in Mahotas
要在 Mahotas 中执行开过程,我们使用 mahotas.open() 函数。此方法允许顺序应用腐蚀和膨胀操作。
腐蚀通过考虑每个像素的邻域并用最小值替换它来减少噪声并消除小的结构。
随后,膨胀通过用邻域中的最大值替换每个像素来扩展剩余结构,同时保留它们的关键特征。
The mahotas.open() function
Mahotas 中的 open() 函数接受两个主要参数——二值图像和结构元素(内核)。此函数首先对输入二值图像应用腐蚀操作。然后将膨胀操作应用于腐蚀图像。
开操作返回在执行腐蚀和膨胀操作后得到的已打开图像。
Syntax
以下是 mahotas 中 open() 函数的基本语法 −
mahotas.open(f, Bc={3x3 cross}, out={np.empty_like(f)})
其中,
-
f − 这是作为 NumPy 数组表示的输入二值图像。
-
Bc − 这是用于腐蚀和膨胀操作的结构元素。默认为 3x3 十字形结构元素。
-
out − 这是输出数组。结果将以与输入图像 f 相同的形状和数据类型存储在一个新数组中。
Example
在以下示例中,我们对图像执行开运算 −
import mahotas as mh
import numpy as np
import matplotlib.pyplot as plt
image = mh.imread('sun.png')
opened_image = mh.open(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 opened image
axes[1].imshow(opened_image, cmap='gray')
axes[1].set_title('Opened Image')
axes[1].axis('off')
# Adjust the layout and display the plot
plt.tight_layout()
plt.show()
执行上面的代码后,我们得到以下输出: -
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 opening with a 3x3 cross structuring element
result = mh.open(image, Bc, out=np.empty_like(image))
# Show the result
imshow(result)
show()
下面显示了产生的输出:
Using a Grayscale Image
我们还可以在 mahotas 中对灰度图像执行开运算。要实现此目的,我们只需在读取图像时传递 as_grey=True 参数,确保将图像加载为灰度图像。接下来,我们将在灰度图像上执行形态学开运算。
Example
现在,我们正在 mahotas 中对灰度图像执行开运算 −
import mahotas as mh
import numpy as np
from pylab import imshow, show
# Create a grayscale image
image = mh.imread('nature.jpeg', as_grey = True).astype(np.uint8)
Bc=np.ones((20,15))
# Perform morphological opening with a 3x3 cross structuring element
result = mh.open(image, Bc, out=np.empty_like(image))
# Show the result
imshow(result)
show()
以下是上面代码的输出: -