You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用matplotlib时如何计算图像高于指定等高线层级的区域总面积

等高线包围面积计算实现方法

方法一:直接基于原始二维数组统计(推荐)

这是最简单、误差最小的实现方式,不需要处理轮廓拟合、嵌套等复杂逻辑,直接统计符合阈值要求的像素总量,乘以单像素对应的实际面积即可:

import numpy as np

# 从你定义的extent参数计算单个像素对应的实际尺寸
pixel_width = (ext[1] - ext[0]) / im.shape[1]
pixel_height = (ext[3] - ext[2]) / im.shape[0]
pixel_area = pixel_width * pixel_height

# 统计所有高于指定等高线层级的像素数量,这里以第一个层级1e-3为例
threshold = mylevels[0]
valid_pixel_count = np.sum(im > threshold)

# 计算总面积
total_area = valid_pixel_count * pixel_area
print(f"高于阈值{threshold}的区域总面积为:{total_area}")

方法二:从contour返回的轮廓对象计算

如果你需要基于生成的等高线轮廓本身计算面积(比如做了轮廓平滑、没有原始数组的场景),可以通过ContourSet对象的路径结合shapely库处理多边形面积,注意需要提前安装shapely:pip install shapely

from shapely.geometry import Polygon

# 选择要计算的等高线索引,0对应第一个层级1e-3
level_idx = 0
# 取出对应层级的所有轮廓线段
contour_segs = cs.allsegs[level_idx]
threshold = cs.levels[level_idx]

polygons = []
for seg in contour_segs:
    # 过滤点数不足无法构成闭合多边形的无效轮廓
    if len(seg) < 3:
        continue
    poly = Polygon(seg)
    if poly.is_valid:
        polygons.append(poly)

# 处理轮廓嵌套:外轮廓面积减去内部空洞的面积
polygons.sort(key=lambda x: x.area, reverse=True)
total_area = 0
used_flag = [False] * len(polygons)

for i, outer_poly in enumerate(polygons):
    if used_flag[i]:
        continue
    current_area = outer_poly.area
    # 遍历嵌套在当前外轮廓内的内部轮廓,扣除空洞面积
    for j, inner_poly in enumerate(polygons[i+1:], start=i+1):
        if used_flag[j]:
            continue
        if outer_poly.contains(inner_poly):
            current_area -= inner_poly.area
            used_flag[j] = True
    total_area += current_area
    used_flag[i] = True

print(f"从轮廓计算的高于阈值{threshold}的区域总面积为:{total_area}")

注意事项

你提供的示例代码存在小笔误,colors['white','yellow','red']缺少赋值等号,修正为colors=['white','yellow','red']即可正常运行。

内容的提问来源于stack exchange,提问作者Nuanda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 07:57:00