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

如何直接获取props中area属性最大元素的索引(无需临时数组)

问题描述

以下代码片段:

import numpy as np
from skimage.measure import label, regionprops

image = np.array([[1, 1, 0], [1, 0, 0], [0, 0, 2]])
labels = label(image, background=0, connectivity=2)
props = regionprops(labels, image, cache=True)

print(image)
print(np.argmax([p.area for p in props]))

运行后输出:

[[1 1 0]
 [1 0 0]
 [0 0 2]]
0

其中0是props中area属性值最大的元素的索引。请问是否存在更直接的计算方式,无需创建[p.area for p in props]这类临时数组?不强制使用NumPy。

解决方案

当然有,以下几种方式都可以避免生成临时面积数组,直接得到目标索引:

方式一:手动遍历跟踪

通过遍历props时实时记录最大面积对应的索引,逻辑直观且无额外内存开销:

max_area = -1
max_index = 0
for idx, prop in enumerate(props):
    if prop.area > max_area:
        max_area = prop.area
        max_index = idx
print(max_index)

方式二:利用内置max函数

借助Python内置max函数的key参数,直接对enumerate(props)的元素进行比较,一行代码完成:

max_index = max(enumerate(props), key=lambda item: item[1].area)[0]
print(max_index)

这两种方法都不需要生成完整的面积数组,遍历过程中完成比较,在处理大量区域时内存效率会更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 21:35:24