Mahotas - 欧拉数



想象一下,你有一幅画,上面有不同的形状。欧拉数允许我们计算这些形状中有多少个孔,以及它们可以分成多少个独立的部分(连通分量)。这有助于分析和表征图像的结构。

数学上,它可以定义为:

E = C - H

其中,E 是欧拉数,C 是连通分量的数量,H 是图像中孔的数量。

Mahotas 中的图像欧拉数

在 Mahotas 中,可以使用 mahotas.euler() 函数计算欧拉数。此函数以二值图像作为输入,其中感兴趣的对象由白色像素表示,背景由黑色像素表示。然后,它根据图像中存在的对象的连通性和孔来计算欧拉数。

使用 mahotas.euler() 函数

mahotas.euler() 函数以二值图像作为输入,并返回欧拉特征值(整数)。

欧拉特征是一种拓扑度量,用于描述图像中对象的连通性和形状。它定义为图像中连通分量数量与孔的数量之差。

以下是 mahotas 中 euler() 函数的基本语法:

mahotas.euler(f, n=8)

其中,'f' 是一个二维二值图像,'n' 是连通分量(整数),值为 4 或 8(默认为 8)。

示例

在下面的示例中,我们通过将“nature.jpeg”加载为灰度图像,然后对其进行阈值处理以创建二值图像,来计算二值图像的欧拉数:

import mahotas as mh
import numpy as np
# Load binary image as a NumPy array
binary_image = mh.imread('nature.jpeg', as_grey=True) > 0
# Compute Euler number
euler_number = mh.euler(binary_image)
# Print result
print("Eu
ler Number:", euler_number)
输出

以下是上述代码的输出:

Euler Number: -2.75

不同连通性的欧拉数

我们还可以使用 euler() 函数在 Mahotas 中计算不同连通性的欧拉数。连通性参数决定计算中考虑哪些相邻像素。

例如,使用连通性-4 只考虑直接的水平和垂直邻居,而连通性-8 还包括对角邻居。

示例

在这里,我们正在计算“nature.jpeg”图像的不同连通性的欧拉数:

import mahotas as mh
import numpy as np
# Load the image as a grayscale image
image = mh.imread('sun.png', as_grey=True)
# Threshold the image to create a binary image
thresholded_image = image > 0
# Compute the Euler number with 4-connectivity
euler_number_4conn = mh.euler(thresholded_image, 4)
# Compute the Euler number with 8-connectivity
euler_number_8conn = mh.euler(thresholded_image, 8)
# Print the results
print("Euler Number (4-connectivity):", euler_number_4conn)
print("Euler Number (8-connectivity):", euler_number_8conn)

输出

上述代码的输出如下:

Euler Number (4-connectivity): -4.75
Euler Number (8-connectivity): -4.75

使用标记图像计算欧拉数

标记图像将唯一的整数标签分配给二值图像中的连通分量。

在 Mahotas 中,euler 函数将标记图像作为输入,并返回整个图像的欧拉数。计算考虑了对象的数量、孔的数量以及对象之间的通道数量。

示例

在这里,我们正在计算从“sea.bmp”图像派生的标记图像的欧拉数:

import mahotas as mh
import numpy as np
# Load the image as a grayscale image
image = mh.imread('sea.bmp', as_grey=True)
# Threshold the image to create a binary image
thresholded_image = image > 0
# Label the connected components in the binary image
labeled_image, num_labels = mh.label(thresholded_image)
# Compute the Euler number of the labeled image
euler_number = mh.euler(labeled_image)
# Print the result
print("Euler Number:", euler_number)

输出

执行上述代码后,我们将得到以下输出:

Euler Number: -44.75

使用二值图像计算欧拉数

在 Mahotas 中,可以使用 euler() 函数计算二值图像的欧拉数。通过加载二值图像并将其转换为布尔格式,euler 函数将图像作为输入,并返回欧拉数(整数)。

示例

在下面给出的示例中,我们使用 Mahotas 计算从“nature.jpeg”图像创建的二值图像的欧拉数:

import mahotas as mh
# load binary image and convert to boolean format
image = mh.imread('sun.png', as_grey= True)
image = image.astype(bool)
# calculate the Euler number
euler_number = mh.euler(image)
# print the result
print("Euler number of the binary image is:", euler_number)

输出

获得的结果如下:

Euler number of the binary image is: -4.75
广告
© . All rights reserved.