Reputation: 604
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?
Upvotes: 4
Views: 1225
Reputation: 476544
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.argmax(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
Upvotes: 4