找到轮廓的中心

时间:2018-01-09 13:06:17

标签: python matplotlib

我有一个代码可以为图像生成一些轮廓。什么是计算最后轮廓的中心像素的最佳方法。

import numpy as np
import matplotlib.pyplot as plt
levels = []
for i in np.arange(0.1,0.9, 0.1):
    levels.append(i*40)
s = plt.contour(Y, X, twhole, levels, linewidths=1, colors=('k','#0000ff', '#0033ff', '#0066ff', '#0099ff','#00ccff','#00ffff', '#660000' ))#'k','0.5','0.75','0.8','0.9', 'g','c','b','m','y','r', '0.2', '0.3', '0.4', ))#colors='k')
plt.show()

1 个答案:

答案 0 :(得分:0)

如果s = ax.contour(...),则获得最后一个轮廓线的点数 s.allsegs[-1][0]

您可以使用它们以通常的方式计算点的质心,例如,维基百科Centroid of a polygon

  

enter image description here

一些例子:

import numpy as np
import matplotlib.pyplot as plt

def center_of_mass(X):
    # calculate center of mass of a closed polygon
    x = X[:,0]
    y = X[:,1]
    g = (x[:-1]*y[1:] - x[1:]*y[:-1])
    A = 0.5*g.sum()
    cx = ((x[:-1] + x[1:])*g).sum()
    cy = ((y[:-1] + y[1:])*g).sum()
    return 1./(6*A)*np.array([cx,cy])


X,Y = np.meshgrid(np.linspace(-2,2),np.linspace(-1,4))
f = lambda x,y: np.exp(-x**2-y**2)+np.sin(np.arctan2(y,x))
Z = f(X,Y)


fig, ax = plt.subplots()
ax.pcolormesh(X,Y,Z, cmap="Reds", vmax=10)

contour = ax.contour(X,Y,Z,levels=[1.01,1.1,1.2], colors="k")

c =  center_of_mass(contour.allsegs[-1][0])
ax.plot(c[0],c[1], marker="o", markersize=12, color="red")
plt.show()

enter image description here

相关问题