Mahotas - 影像的質心



質心是指物體質量的平均位置。它是一個物體總質量集中的點。簡單來說,它代表物體的平衡點。如果物體是均勻且對稱的,則質心在其幾何中心,否則不是。

Mahotas 中的影像質心

Mahotas 中的質心是透過為物體的每個畫素分配一個質量值,然後計算這些質量值的平均位置來確定的。這將導致質心的座標,指示物體在影像中的質心的位置。

使用 mahotas.center_of_mass() 函式

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]

使用 NumPy 函式計算質心

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' 指的是表示值或強度總和的陣列。

示例

在這裡,我們正在使用建立一個單一的座標陣列。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]

特定區域的質心

特定區域的質心是影像中感興趣的區域(面積)。這可能是特定區域,例如邊界框或選定的區域。

特定區域的質心是透過取 ROI(感興趣區域)中每個畫素的 x 和 y 座標的加權平均值來計算的,其中權重是畫素強度。質心作為兩個值的元組返回,分別表示 x 和 y 座標。

示例

以下是如何計算灰度影像的感興趣區域的質心的示例:

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]
廣告

© . All rights reserved.