简体   繁体   中英

Get max rectangle area from numpy array

I want to get max rectangle area from numpy array that looks like that:

.. 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]
...]

For now I have:

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

But I expect many thousands of rows or even more. Is there a more efficient way of calculating this?

You can calculate the area of the rectangles in bulk with:

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

Next you can obtain the index (row) with the largest area with:

np.areas

For your given sample data, the first rectangle is the largest:

>>> 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM