Mahotas 简明教程

Mahotas - Centre of Mass of an Image

质心是指物体的质量的平均位置。它是物体总质量集中的一个点。简单地说,它表示物体的平衡点。如果物体是均匀且对称的,则质心将在其几何中心,否则不在。

Center of Mass of an Image in Mahotas

Mahotas 中的质心是通过为对象的每个像素分配一个质量值,然后计算这些质量值的平均位置来确定的。这产生了质心的坐标,它指示了对象质心在图像内的位置。

Using mahotas.center_of_mass() Function

mahotas.center_of_mass() 函数用于查找图像的质心。它计算图像中像素强度的平均位置(作为坐标组),提供图像“中心”所在位置的度量。

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

mahotas.center_of_mass(image)

其中, image 指示您要查找其质心的输入图像。

在以下示例中,我们正在计算图像 'nature.jpeg' 的质心 −

import mahotas as ms
import numpy as np
# Loading the image
image = ms.imread('nature.jpeg')
# Calculating the center of mass
com = ms.center_of_mass(image)
# Printing the center of mass
print("Center of mass of the image is:", com)

质心以 3D 坐标的形式表示为 [x, y, z],如下面输出所示 −

Center of mass of the image is: [474.10456551 290.26772015 0.93327202]

Center of Mass Using Numpy Functions

NumPy 函数是 NumPy 库中内置的工具,可让您轻松地执行数组操作和 Python 中的数学计算。

要使用 Mahotas 中的 NumPy 函数计算质心,我们需要确定图像“权重”的平均位置。这是通过将每个像素的 x 和 y 坐标与其强度值相乘,对这些加权坐标求和,然后将结果除以强度总和来完成的。

以下是使用 numpy 函数计算图像质心的基本语法 −

com = np.array([np.sum(X * Y), np.sum(A * B)]) / np.sum(C)

其中 'X''Y' 表示坐标数组, 'A''B' 表示与坐标相关的值或强度的数组, 'C' 表示数组表示的值或强度的总和。

Example

在这里,我们使用创建单个坐标数组。coords 的第一维表示 y 坐标,第二维表示 x 坐标。然后我们在计算加权和时访问 coords[1] 获取 x 坐标,访问 coords[0] 获取 y 坐标 −

import mahotas as mh
import numpy as np
# Loading the image
image = mh.imread('tree.tiff')
# Creating a single coordinate array
coords = np.indices(image.shape)
# Calculating the weighted sum of x and y coordinates
com = np.array([np.sum(coords[1] * image), np.sum(coords[0] * image)]) /
np.sum(image)
# Printing the center of mass
print("Center of mass:", com)

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

Center of mass: [ 7.35650493 -3.83720823]

Center of Mass of a Specific Region

特定区域的质心是图像中感兴趣的区域(面积)。这可以是特定区域,例如边框框或所选区域。

特定区域的质心是通过计算感兴趣区域 (ROI) 中每个像素的 x 和 y 坐标的加权平均值来计算的,其中权重是像素强度。质心作为两个值的对返回,分别表示 x 和 y 坐标。

Example

以下是计算灰度图像感兴趣区域的质心的示例 −

import mahotas as mh
import numpy as np
# Load a grayscale image
image = mh.imread('nature.jpeg', as_grey=True)
# Defining a region of interest
roi = image[30:90, 40:85]
# Calculating the center of mass of the ROI
center = mh.center_of_mass(roi)
print(center)

上述代码的输出如下:

[29.50213372 22.13203391]