2022-03-23 13:46:57 +01:00

55 lines
1.7 KiB
Python

import numpy as np
def compute_iou_from_boxes(box1, box2):
"""
Each box of the form (x1, y1, delx, dely)
"""
ax1, ay1, aw, ah = box1
bx1, by1, bw, bh = box2
ax2, ay2, bx2, by2 = ax1 + aw, ay1 + ah, bx1 + bw, by1 + bh
if (ax1 > bx2) or (bx1 > ax2) or (ay1 > by2) or (by1 > ay2):
return 0
intersection = (min(ax2, bx2) - max(ax1, bx1)) * (min(ay2, by2) - max(ay1, by1))
area_a = (ax2 - ax1) * (ay2 - ay1)
area_b = (bx2 - bx1) * (by2 - by1)
union = area_a + area_b - intersection
return intersection / union
def find_max_overlap(box, box_list):
best_candidate = max(box_list, key=lambda x: compute_iou_from_boxes(box, x))
iou = compute_iou_from_boxes(box, best_candidate)
return best_candidate, iou
def compute_page_iou(results_box_list, gt_box_list):
results = results_box_list.copy()
gt = gt_box_list.copy()
if (not results) or (not gt):
return 0
iou_sum = 0
denominator = max(len(results), len(gt))
while gt and results:
gt_box = gt.pop()
best_match, best_iou = find_max_overlap(gt_box, results)
results.remove(best_match)
iou_sum += best_iou
score = iou_sum / denominator
return score
def compute_document_score(results_dict, annotation_dict):
page_weights = np.array([len(v) for v in annotation_dict.values()])
page_weights = page_weights / sum(page_weights)
scores = []
for key in annotation_dict:
scores.append(compute_page_iou(results_dict[key], annotation_dict[key]))
scores = np.array(scores)
doc_score = np.average(scores, weights=page_weights)
return doc_score
def compute_document_score_tables(results_dict, annotation_dict):
pass