|
| 1 | +################################################################################################################################ |
| 2 | + |
| 3 | +import numpy as np |
| 4 | + |
| 5 | +################################################################################################################################ |
| 6 | + |
| 7 | +# Straightforward IoU calculation that is not concerned with tensorflow formatting. |
| 8 | + |
| 9 | +def calculate_iou(y_true, y_pred): |
| 10 | + # input must be as [x1, y1, x2, y2] |
| 11 | + |
| 12 | + y_true = y_true.astype(np.float32) |
| 13 | + y_pred = y_pred.astype(np.float32) |
| 14 | + |
| 15 | + # AOG = Area of Groundtruth box |
| 16 | + AoG = np.abs(y_true[2] - y_true[0]) * np.abs(y_true[3] - y_true[1]) |
| 17 | + |
| 18 | + # AOP = Area of Predicted box |
| 19 | + AoP = np.abs(y_pred[2] - y_pred[0]) * np.abs(y_pred[3] - y_pred[1]) |
| 20 | + |
| 21 | + # overlaps are the co-ordinates of intersection box |
| 22 | + overlap_0 = np.maximum(y_true[0], y_pred[0]) |
| 23 | + overlap_1 = np.maximum(y_true[1], y_pred[1]) |
| 24 | + overlap_2 = np.minimum(y_true[2], y_pred[2]) |
| 25 | + overlap_3 = np.minimum(y_true[3], y_pred[3]) |
| 26 | + |
| 27 | + # intersection area |
| 28 | + intersection = np.abs(overlap_2 - overlap_0) * np.abs(overlap_3 - overlap_1) |
| 29 | + |
| 30 | + # area of union of both boxes |
| 31 | + union = AoG + AoP - intersection |
| 32 | + |
| 33 | + # iou calculation |
| 34 | + iou = intersection / union |
| 35 | + |
| 36 | + # return the mean IoU score for the batch |
| 37 | + return iou |
| 38 | + |
| 39 | +################################################################################################################################ |
0 commit comments