import numpy as np
# get IoU overlap ratio
def compute_mean_iou(y_pred, y_true):
mean_iou = []
for i in range(y_pred.shape[0]):
area_a = (y_pred[i][2] - y_pred[i][0]) * (y_pred[i][3] - y_pred[i][1])
area_b = (y_true[i][2] - y_true[i][0]) * (y_true[i][3] - y_true[i][1])
iou_x1 = np.maximum(y_pred[i][0], y_true[i][0])
iou_y1 = np.maximum(y_pred[i][1], y_true[i][1])
iou_x2 = np.minimum(y_pred[i][2], y_true[i][2])
iou_y2 = np.minimum(y_pred[i][3], y_true[i][3])
iou_w = iou_x2 - iou_x1
iou_h = iou_y2 - iou_y1
if iou_w < 0 or iou_h < 0:
mean_iou.append(0.0)
else:
area_iou = iou_w * iou_h
iou = area_iou / (area_a + area_b - area_iou)
mean_iou.append(iou)
return sum(mean_iou)/len(mean_iou)
# [x1, y1, x2, y2]
a = np.array(([[0, 0, 1, 3],[0, 0, 1, 3]]), dtype=np.float32)
b = np.array(([[0, 0, 1, 1],[0, 0, 1, 1]]), dtype=np.float32)
print(compute_mean_iou(a, b))
https://github.com/yoyoyo-yo/Gasyori100knock/blob/master/Question_91_100/answers/answer_93.py
Recommended Posts