evaluate_tool.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import numpy as np
  2. def calculate_iou(box1, box2):
  3. # 计算IoU的基础方法
  4. inter_x_min = max(box1[0], box2[0])
  5. inter_y_min = max(box1[1], box2[1])
  6. inter_x_max = min(box1[2], box2[2])
  7. inter_y_max = min(box1[3], box2[3])
  8. inter_area = max(0, inter_x_max - inter_x_min) * max(0, inter_y_max - inter_y_min)
  9. box1_area = (box1[2] - box1[0]) * (box1[3] - box1[1])
  10. box2_area = (box2[2] - box2[0]) * (box2[3] - box2[1])
  11. union_area = box1_area + box2_area - inter_area
  12. iou = inter_area / union_area if union_area > 0 else 0
  13. return iou
  14. def calculate_giou(box1, box2):
  15. iou = calculate_iou(box1, box2)
  16. # 计算最小外包围矩形
  17. c_x_min = min(box1[0], box2[0])
  18. c_y_min = min(box1[1], box2[1])
  19. c_x_max = max(box1[2], box2[2])
  20. c_y_max = max(box1[3], box2[3])
  21. c_area = (c_x_max - c_x_min) * (c_y_max - c_y_min)
  22. giou = iou - (
  23. c_area - (box1[2] - box1[0]) * (box1[3] - box1[1]) - (box2[2] - box2[0]) * (box2[3] - box2[1])) / c_area
  24. return giou
  25. def calculate_diou(box1, box2):
  26. iou = calculate_iou(box1, box2)
  27. # 计算中心点的距离
  28. box1_center = [(box1[0] + box1[2]) / 2, (box1[1] + box1[3]) / 2]
  29. box2_center = [(box2[0] + box2[2]) / 2, (box2[1] + box2[3]) / 2]
  30. center_distance = np.sum(np.square(np.array(box1_center) - np.array(box2_center)))
  31. # 计算最小外包围矩形的对角线距离
  32. c_x_min = min(box1[0], box2[0])
  33. c_y_min = min(box1[1], box2[1])
  34. c_x_max = max(box1[2], box2[2])
  35. c_y_max = max(box1[3], box2[3])
  36. c_diag_distance = np.sum(np.square(np.array([c_x_max, c_y_max]) - np.array([c_x_min, c_y_min])))
  37. diou = iou - center_distance / c_diag_distance
  38. return diou
  39. def calculate_ciou(box1, box2):
  40. diou = calculate_diou(box1, box2)
  41. # 计算长宽比一致性
  42. box1_w = box1[2] - box1[0]
  43. box1_h = box1[3] - box1[1]
  44. box2_w = box2[2] - box2[0]
  45. box2_h = box2[3] - box2[1]
  46. v = (4 / (np.pi ** 2)) * np.square(np.arctan(box1_w / box1_h) - np.arctan(box2_w / box2_h))
  47. alpha = v / (1 - calculate_iou(box1, box2) + v)
  48. ciou = diou - alpha * v
  49. return ciou