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

Python如何统计图像中Matplotlib生成的轮廓数量及相关属性

实现目标

编写程序统计一系列绘图中的Matplotlib轮廓数量,对所有轮廓数求和后展示总轮廓数。

已完成工作
  • 已完成目标变量的绘图工作,图中包含对应给定阈值的轮廓,效果示例如下:
    阈值轮廓图示例
  • 目前已生成多幅展示不同区域轮廓的同类绘图。
已尝试方案
  • 曾参考OpenCV轮廓计数相关教程,尝试使用cv2统计轮廓数量,但运行时出现报错,报错信息如下:
    cv2运行报错信息
  • 无法确定当前cv2实现方案的思路是否存在问题,想确认Matplotlib是否提供原生功能支持该需求,检索相关资料未找到可行解决方案,因此发起提问。

生成带轮廓绘图的核心代码如下:

threshVertVeloLL = vertVeloLLComp > 9

res = '1km'
buffer = '5km'
buffer_px = int((units(buffer) / units(res)).m)
bufferedVV = binary_dilation(threshVertVeloLL.values, footprint=disk(buffer_px))

labeled_image, _ = label(bufferedVV, np.ones((3,3), dtype=int))
remove_small_objects(labeled_image, min_size=buffer_px * 3, connectivity=2)

subsets_VV = []
for region in regionprops(labeled_image):
    subsets_VV.append(vertVeloLLComp.isel(
        yh=slice(region.bbox[0], region.bbox[2]),
        xh=slice(region.bbox[1], region.bbox[3])
    ))
    
plt.imshow(labeled_image)

images = []

for subset_VV in subsets_VV:
    fig, ax = plt.subplots(1, 1, figsize=(10,10))
    subset_VV.plot(ax=ax, cmap=get_cmap('coolwarm'))
    img = plt.contour(subset_VV.metpy.x, subset_VV.metpy.y, subset_VV, levels=[10.])
    '''How do I count number of contours in each image?'''
#    x_min = subset_VV['xh'].min().item()
#    x_max = subset_VV['xh'].max().item()
#    y_min = subset_VV['yh'].min().item()
#    y_max = subset_VV['yh'].max().item()
    #[0.15, 0.15, 0.25, 0.25]
#    ax_inset = fig.add_axes(
#        [0.15, 0.15, 0.25, 0.25])
#    vertVeloLLComp.plot(ax=ax_inset)
#    ax_inset.plot(
#        [x_min, x_max, x_max, x_min, x_min],
#        [y_min, y_min, y_max, y_max, y_min])
#    ax_inset.set_axis_off()
     images.append(img)
     plt.show()

本次咨询需要获取具体实现方案,同时想了解Matplotlib是否支持计算每个轮廓的面积、每个轮廓范围内变量的平均值,若需要补充其他信息可随时告知。

补充内容
  • 按要求提供绘图所用原始图像如下:
    原始图像
  • 自行编写的OpenCV测试代码如下:
for image in images:
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    
    edges= cv2.Canny(gray, 50,200)

    contours, hierarchy= cv2.findContours(edges.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 18:57:34