Skip to main content
 首页 » 编程设计

python之从一组 x、y 坐标计算表面的质心

2025年01月19日9shangdawei

我正在尝试确定由一组随机非等距 x、y 点确定的表面的质心。 这是一个快速测试集来说明我的意思。

from scipy.spatial import ConvexHull 
import numpy as np 
import matplotlib.pyplot as plt 
 
def PolyArea(x, y): 
    return 0.5*np.abs(np.dot(x, np.roll(y,1))-np.dot(y, np.roll(x,1))) 
 
points = np.random.rand(30, 2)   # 30 random points in 2-D 
hull = ConvexHull(points) 
 
plt.plot(points[:,0], points[:,1]) 
for simplex in hull.simplices: 
    plt.plot(points[simplex, 0], points[simplex, 1]) 
 
plt.plot(points[hull.vertices, 0], points[hull.vertices, 1], 'r--', lw=2) 
plt.show() 

从这里我们得到:

x = points[hull.vertices, 0] 
y = points[hull.vertices, 1] 
 
surface_size = PolyArea(x, y) 

我希望根据点集 (x, y) 确定区域的质心,而不是点的平均值。我知道这是通过表面的二重积分来计算的(参见:http://tutorial.math.lamar.edu/Classes/CalcII/CenterOfMass.aspx),但我不知道如何在 Python 中实现它。

提前致谢。

请您参考如下方法:

肯定有一个更优雅的解决方案,但这里有一个快速但肮脏、可能缓慢且矫枉过正的基于图像的解决方案。

import skimage.measure 
import skimage.draw 
 
GRIDW = 1000 
GRIDH = 1000 
 
img = np.zeros((GRIDW, GRIDH)) 
 
rr, cc = skimage.draw.polygon(x*GRIDW,y*GRIDH) 
img[rr,cc] = 1 
 
label = skimage.measure.label(img) 
rprops = skimage.measure.regionprops(label) 
 
print rprops[0].centroid / np.asarray([GRIDW, GRIDH])