Mahotas 简明教程

Mahotas - Euler Number of an Image

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

在数学上,可以将其定义为:

E = C - H

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

Euler Number of an Image in Mahotas

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

Using the mahotas.euler() Function

mahotas.euler() 函数将二值图像作为输入,并返回一个整数作为欧拉示性数。

欧拉示性数是一种拓扑度量,用于描述图像中对象之间的连通性和形状。它被定义为图像中连通部件数量与孔洞数量之间的差值。

Mahotas 中 euler() 函数的基本语法如下:

mahotas.euler(f, n=8)

其中, 'f' 是一个 2D 二值图像, '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 Number with Different Connectivity

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

例如,使用连通性-4 仅考虑直接的水平和垂直相邻像素,而连通性-8 同时也考虑对角相邻像素。

Example

在此,我们使用不同的连通性计算 "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

Euler Number Calculation with Labelled Image

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

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

Example

在这里,我们计算从 "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

Euler Number Calculation with Binary Image

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

Example

在下面给出的示例中,我们使用 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