python - 从 numpy 数组中获取最大矩形区域

标签 python numpy

我想从 numpy 数组中获取最大矩形区域,如下所示:

.. class   conf xmin   ymin   xmax   ymax
[[ 19.     0.78 102.79  98.85 258.17 282.53]
 [  7.     0.66 245.61 211.98 270.66 234.76]
 [  6.     0.56  -6.51 143.64  39.31 286.06]
 [  6.     0.5  103.77  94.07 256.6  278.14]
...]

现在我有:

def chooseBiggest(predictions):
    max = 0;
    index = 0;
    for i in range(len(predictions)):
        pred = predictions[i]
        area = (pred[4] - pred[2])*(pred[5] - pred[3])
        if area > max:
            max = area
            index = i

    return index

但我预计会有数千行甚至更多。有没有更有效的计算方法?

最佳答案

您可以批量计算矩形的面积:

areas = (predictions[:,4] - predictions[:,2]) * (predictions[:,5] - predictions[:,3])

接下来可以得到面积最大的索引(行):

np.<b>argmax(</b>areas<b>)</b>

对于给定的样本数据,第一个矩形是最大的:

>>> predictions = np.array([[19., 0.78, 102.79, 98.85, 258.17, 282.53],
... [ 7., 0.66, 245.61, 211.98, 270.66, 234.76],
... [ 6., 0.56, -6.51, 143.64, 39.31, 286.06],
... [ 6., 0.5, 103.77, 94.07, 256.6, 278.14]])
>>> areas = (predictions[:,4] - predictions[:,2]) * (predictions[:,5] - predictions[:,3])
>>> areas
array([28540.1984,   570.639 ,  6525.6844, 28131.4181])
>>> np.argmax(areas)
0

关于python - 从 numpy 数组中获取最大矩形区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58892045/

相关文章:

python - for循环内的numpy vstack

python - cv2.imshow 显示 9 个屏幕而不是 1 个

python - 使用 python 3.5 按行比较两个文件,将每行差异输出到新文件中的新行

python - pycharm上pytorch 1.6.0安装问题

python - 更改从 Python 中的文件导入的数据的格式

python - 将 -inf 替换为零值

python - 如何将数组存储在太大而无法加载到内存中的 hdf5 文件中?

python - 元组的 Numpy 随机选择

python - 从没有循环的多级 Pandas 数据框中删除行列表

Python-如何将字典作为输入