Mahotas 简明教程

Mahotas - Getting Border of Labels

获取标签边界是指提取 labeled image 的边界像素。边界可以定义为一个区域,其像素位于图像的边缘。边界表示图像不同区域之间的过渡。

获取标签边界涉及识别标记图像中的边界区域并将它们与背景分离开来。

由于标记图像仅由前景像素和背景像素组成,因此边界可以很容易地被识别出来,因为它们与背景区域相邻。

Getting Border of labels in Mahotas

在 Mahotas 中,我们可以使用 mahotas.labeled.borders() 函数获取标签边界。它分析标记图像的相邻像素并考虑连接模式以获取边界。

The mahotas.labeled.borders() function

mahotas.labeled.borders() 函数将标记图像作为输入,并返回具有高亮边界的图像。

在结果图像中,边界像素的值为 1,并且是前景的一部分。

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

mahotas.labeled.borders(labeled, Bc={3x3 cross}, out={np.zeros(labeled.shape,
bool)})

其中,

  1. labeled − 这是输入标记图像。

  2. Bc (optional) − 这是用于连接性的结构元素。

  3. out (optional) − 这是输出数组(默认为等于标记形状的新数组)。

在以下示例中,我们使用 mh.labeled.borders() 函数获取标签边界。

import mahotas as mh
import numpy as np
import matplotlib.pyplot as mtplt
# Loading the image
image = mh.imread('nature.jpeg', as_grey=True)
# Applying thresholding
image = image > image.mean()
# Converting it to a labeled image
labeled, num_objects = mh.label(image)
# Geting border of labels
borders = mh.labeled.borders(labeled)
# Creating a figure and axes for subplots
fig, axes = mtplt.subplots(1, 2)
# Displaying the labeled image
axes[0].imshow(labeled)
axes[0].set_title('Labeled Image')
axes[0].set_axis_off()
# Displaying the borders
axes[1].imshow(borders)
axes[1].set_title('Border Labels')
axes[1].set_axis_off()
# Adjusting spacing between subplots
mtplt.tight_layout()
# Showing the figures
mtplt.show()

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

border labels

Getting Borders by using a Custom Structuring Element

我们还可以通过使用自定义结构元素获取标签边界。结构元素是一个仅由 1 和 0 组成的数组。它用于定义相邻像素的连接结构。

包含在连通性分析中的像素具有 1 的值,而被排除的像素具有 0 的值。

在 mahotas 中,我们使用 mh.disk() 函数创建自定义结构元素。然后,我们设置此自定义结构元素作为 borders() 函数中的 Bc 参数,以获取标签边界。

Example

在此处,我们使用自定义结构元素获取标签边界。

import mahotas as mh
import numpy as np
import matplotlib.pyplot as mtplt
# Loading the image
image = mh.imread('sea.bmp', as_grey=True)
# Applying thresholding
image = image > image.mean()
# Converting it to a labeled image
labeled, num_objects = mh.label(image)
# Geting border of labels
borders = mh.labeled.borders(labeled, mh.disk(5))
# Creating a figure and axes for subplots
fig, axes = mtplt.subplots(1, 2)
# Displaying the labeled image
axes[0].imshow(labeled)
axes[0].set_title('Labeled Image')
axes[0].set_axis_off()
# Displaying the borders
axes[1].imshow(borders)
axes[1].set_title('Border Labels')
axes[1].set_axis_off()
# Adjusting spacing between subplots
mtplt.tight_layout()
# Showing the figures
mtplt.show()

上述代码的输出如下:

border labels element