Mahotas 简明教程

Mahotas - Eroding Image

在图像处理中侵蚀图像指的是收缩图像的像素。

侵蚀过程将移除图像边缘周围的像素。此操作会扫描图像并检查某个像素邻域内的所有像素是否都是前景像素。如果是,则像素被侵蚀或移除。

Eroding an Image in Mahotas

通过在 Mahotas 中侵蚀图像,我们指的是移除图像中对象的边界或区域的像素数量。此操作通常用于修改图像中的形状和结构。

我们可以在 mahotas 中使用 erode() 函数侵蚀图像。它用于通过使用结构元素 B 来收缩元素 A。

结构元素是一种小矩阵或形状,它定义了每个像素周围的邻域。它用于确定在侵蚀过程中应该考哪些像素。

The mahotas.erode() function

mahotas.erode() 函数获取输入图像和结构元素作为参数,并返回一个新的 Numpy 数组。

输出像素的值由邻域中所有像素的最小值确定。像素被设置为 0,如果任何邻域像素的值为 0。

erode() 函数按像素扫描图像,并检查由结构元素定义的邻域。

如果有任何相邻像素属于对象,侵蚀操作会将这些像素移除到对象的边界,使其变小。

Syntax

以下是在 mahotas 中 erode() 函数的基本语法 −

mahotas.erode(A, Bc={3x3 cross}, out={np.empty_as(A)})

其中,

  1. A − 这是将对其执行侵蚀的输入图像。它应该是一个表示灰度图像的 NumPy 数组。

  2. Bc (optional) − 这是用于侵蚀的结构元素。默认情况下,它设置为一个 3x3 十字形的结构元素。

  3. out (optional) − 它指定输出数组以存储结果。

Example

以下是用 erode() 函数在 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 erosion with a square kernel of size 3x3
eroded_image = mh.erode(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 eroded image
axes[1].imshow(eroded_image, cmap='gray')
axes[1].set_title('Eroded Image')
axes[1].axis('off')
# Adjust the layout and display the plot
plt.tight_layout()
plt.show()

在执行上述代码后,我们如下获得输出 −

eroding image

Erosion with Varying Structuring Element Sizes

我们还可以使用不同结构元素尺寸来侵蚀图像,以修改图像的不同方面。这些元素使用 Mahotas disk() 函数以不同的尺寸创建。

通过为结构元素选择不同的半径或尺寸,我们可以获得不同的效果。首先,我们使用最大的结构元素执行侵蚀。然后,我们继续使用较小的结构元素进行额外的扩张。

每次侵蚀操作都会通过从其边界中移除像素进一步缩小图像中的对象。

Example

在这里,我们尝试使用不同结构元素尺寸侵蚀图像 −

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 erosion with the largest structuring element
largest_se = mh.disk(8)
eroded_image = mh.erode(image, Bc=largest_se)
# Performing additional erosions with smaller structuring elements
smaller_se_1 = mh.disk(2)
smaller_se_2 = mh.disk(5)
eroded_image = mh.erode(eroded_image, Bc=smaller_se_1)
eroded_image = mh.erode(eroded_image, Bc=smaller_se_2)
# Displaying the eroded image
imshow(eroded_image)
show()

获得的输出如下所示 −

erosion structuring element

Erosion with a Circular-shaped Kernel

若要创建圆形内核,我们可以使用 Mahotas 中的 disk() 函数。通过指定所需的半径,此函数会生成表示圆形内核的 NumPy 数组。

一旦我们准备好图像和圆形内核,我们就可以进行侵蚀。此操作会将圆形内核应用到图像的每个像素,从而相应地缩小前景像素。

简单来说,它会根据圆形内核定义的连接性缩小区域。

Example

现在,我们正在使用圆形内核扩张图像 −

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 10
radius = 10
kernel = mh.disk(radius)
eroded_image = mh.erode(image, kernel)
# Display the eroded image
imshow(eroded_image)
show()

以下是上面代码的输出: -

erosion circular shaped kernel