polygon_fast.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import numpy as np
  2. from shapely.geometry import Polygon
  3. """
  4. :param det_x: [1, N] Xs of detection's vertices
  5. :param det_y: [1, N] Ys of detection's vertices
  6. :param gt_x: [1, N] Xs of groundtruth's vertices
  7. :param gt_y: [1, N] Ys of groundtruth's vertices
  8. ##############
  9. All the calculation of 'AREA' in this script is handled by:
  10. 1) First generating a binary mask with the polygon area filled up with 1's
  11. 2) Summing up all the 1's
  12. """
  13. def area(x, y):
  14. polygon = Polygon(np.stack([x, y], axis=1))
  15. return float(polygon.area)
  16. def approx_area_of_intersection(det_x, det_y, gt_x, gt_y):
  17. """
  18. This helper determine if both polygons are intersecting with each others with an approximation method.
  19. Area of intersection represented by the minimum bounding rectangular [xmin, ymin, xmax, ymax]
  20. """
  21. det_ymax = np.max(det_y)
  22. det_xmax = np.max(det_x)
  23. det_ymin = np.min(det_y)
  24. det_xmin = np.min(det_x)
  25. gt_ymax = np.max(gt_y)
  26. gt_xmax = np.max(gt_x)
  27. gt_ymin = np.min(gt_y)
  28. gt_xmin = np.min(gt_x)
  29. all_min_ymax = np.minimum(det_ymax, gt_ymax)
  30. all_max_ymin = np.maximum(det_ymin, gt_ymin)
  31. intersect_heights = np.maximum(0.0, (all_min_ymax - all_max_ymin))
  32. all_min_xmax = np.minimum(det_xmax, gt_xmax)
  33. all_max_xmin = np.maximum(det_xmin, gt_xmin)
  34. intersect_widths = np.maximum(0.0, (all_min_xmax - all_max_xmin))
  35. return intersect_heights * intersect_widths
  36. def area_of_intersection(det_x, det_y, gt_x, gt_y):
  37. p1 = Polygon(np.stack([det_x, det_y], axis=1)).buffer(0)
  38. p2 = Polygon(np.stack([gt_x, gt_y], axis=1)).buffer(0)
  39. return float(p1.intersection(p2).area)
  40. def area_of_union(det_x, det_y, gt_x, gt_y):
  41. p1 = Polygon(np.stack([det_x, det_y], axis=1)).buffer(0)
  42. p2 = Polygon(np.stack([gt_x, gt_y], axis=1)).buffer(0)
  43. return float(p1.union(p2).area)
  44. def iou(det_x, det_y, gt_x, gt_y):
  45. return area_of_intersection(det_x, det_y, gt_x, gt_y) / (
  46. area_of_union(det_x, det_y, gt_x, gt_y) + 1.0)
  47. def iod(det_x, det_y, gt_x, gt_y):
  48. """
  49. This helper determine the fraction of intersection area over detection area
  50. """
  51. return area_of_intersection(det_x, det_y, gt_x, gt_y) / (
  52. area(det_x, det_y) + 1.0)