要使用 Python 测量图像中分割多边形的质心(或中心点),可以使用 OpenCV 库。以下是基本概要和代码:
将图像转换为灰度图像。
对图像进行阈值处理,得到二值图像。
使用 findContours 函数检测轮廓。
对于检测到的感兴趣的轮廓(例如最大的轮廓),计算质量中心。
import cv2
import numpy as np
# Load the image
image = cv2.imread('path_to_image.jpg')
# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Threshold the image to obtain binary image
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# Find contours
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Assuming we are interested in the largest contour, get it
largest_contour = max(contours, key=cv2.contourArea)
# Calculate the center of mass (centroid)
M = cv2.moments(largest_contour)
cx = int(M['m10'] / M['m00'])
cy = int(M['m01'] / M['m00'])
print(f"Center of Mass (Centroid) is at: ({cx}, {cy})")