python - 如何使用 Matplotlib 在 Python 中计算轮廓内的面积?

标签 python matplotlib area contour

我想找出一种方法来获得特定轮廓线内的区域?
我使用 matplotlib.pyplot 来创建我的轮廓。
有没有人有经验为此?

非常感谢。

最佳答案

contour 函数返回的轮廓集合的 collections 属性中,您可以获得描述每个轮廓的路径。路径的 vertices 属性包含轮廓的有序顶点。

使用顶点,您可以近似轮廓积分 0.5*(x*dy-y*dx),通过应用 Green's theorem给你封闭区域的面积。

但是,等高线必须完全包含在绘图中,否则等高线会分解成多个不一定连接的路径,并且该方法会失效。

这是用于计算半径函数所包围的面积的方法,即 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()

输出:

r = 1.0: a = 2.83566351207
r = 2.0: a = 11.9922190971
r = 3.0: a = 27.3977413253

关于python - 如何使用 Matplotlib 在 Python 中计算轮廓内的面积?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22678990/

相关文章:

python - 如何以列形式将字典保存在 csv 中,其中第一行是键,下一行是向量?

python - Matplotlib 插值/绘制非结构化数据

python:可以创建 3 个子图(在两个轴上)吗?

python - 如何为从 matplotlib 导出的 PDF 获得正确的图形大小和字体大小?

html - Safari/IE 图像映射自定义光标无法正常工作

matlab - 突出显示部分 matlab 图

python - 如何测试区域是否重叠 (Python)

python - Django Rest 框架基于类的 View 中的 Django 快捷方式 get_object_or_404

python - 我如何对大量列表进行排序以获得 Python 中的前 10 名?

python - 逐行读取文本文件并存储匹配 Python 中特定模式的变量