wat*_*tao 3 python matplotlib area contour
我想找到一种方法来获得特定轮廓线内的区域?
我matplotlib.pyplot用来创建我的轮廓.
有没有人有这方面的经验?
非常感谢.
从函数collections返回的轮廓集合的属性中contour,您可以获得描述每个轮廓的路径.然后,路径的vertices属性包含轮廓的有序顶点.
使用顶点可以近似轮廓积分0.5*(x*dy-y*dx),通过应用格林定理可以得到封闭区域的面积.
但是,轮廓必须完全包含在图中,否则轮廓会被分解为多个,不一定是连接的路径,并且方法会中断.
这是用于计算半径函数所包围的面积的方法,即r =(x ^ 2 + y ^ 2)^ 0.5,对于r = 1.0,r = 2.0,r = 3.0.
import numpy as np
import matplotlib.pylab as plt
# Use Green's theorem to compute the area
# enclosed by the given contour.
def area(vs):
a = 0
x0,y0 = vs[0]
for [x1,y1] in vs[1:]:
dx = x1-x0
dy = y1-y0
a += 0.5*(y0*dx - x0*dy)
x0 = x1
y0 = y1
return a
# Generate some test data.
delta = 0.01
x = np.arange(-3.1, 3.1, delta)
y = np.arange(-3.1, 3.1, delta)
X, Y = np.meshgrid(x, y)
r = np.sqrt(X**2 + Y**2)
# Plot the data
levels = [1.0,2.0,3.0]
cs = plt.contour(X,Y,r,levels=levels)
plt.clabel(cs, inline=1, fontsize=10)
# Get one of the contours from the plot.
for i in range(len(levels)):
contour = cs.collections[i]
vs = contour.get_paths()[0].vertices
# Compute area enclosed by vertices.
a = area(vs)
print "r = " + str(levels[i]) + ": a =" + str(a)
plt.show()
Run Code Online (Sandbox Code Playgroud)
输出:
r = 1.0: a = 2.83566351207
r = 2.0: a = 11.9922190971
r = 3.0: a = 27.3977413253
Run Code Online (Sandbox Code Playgroud)
@spfrnd 计算面积的答案的矢量化版本:
x=contour.vertices[:,0]
y=contour.vertices[:,1]
area=0.5*np.sum(y[:-1]*np.diff(x) - x[:-1]*np.diff(y))
area=np.abs(area)
Run Code Online (Sandbox Code Playgroud)
请注意,您可能需要取abs面积的 ,因为如果沿轮廓的点指向相反的方向,则结果将为负。
| 归档时间: |
|
| 查看次数: |
5565 次 |
| 最近记录: |