geometry.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. """几何工具:NMS、点/框与多边形 ROI 的关系。
  2. 只依赖标准库 + 纯 Python 计算(numpy 可选加速),保证在 RK/Jetson 上都能跑。
  3. 所有坐标均为像素坐标;ROI 在配置里是**归一化**坐标,使用时用
  4. :func:`normalized_to_pixel_polygon` 转成像素。
  5. """
  6. from __future__ import annotations
  7. from typing import List, Sequence, Tuple
  8. from ..schema import Box
  9. Point = Tuple[float, float]
  10. Polygon = Sequence[Point]
  11. __all__ = [
  12. "box_in_polygon_ratio",
  13. "clip_polygon",
  14. "nms",
  15. "normalized_to_pixel_polygon",
  16. "point_in_polygon",
  17. "polygon_area",
  18. ]
  19. def normalized_to_pixel_polygon(polygon: Polygon, width: float, height: float) -> List[Point]:
  20. """归一化多边形 → 像素多边形。"""
  21. if not polygon:
  22. return [(0.0, 0.0), (width, 0.0), (width, height), (0.0, height)]
  23. return [(float(x) * width, float(y) * height) for x, y in polygon]
  24. def clip_polygon(polygon: Polygon, width: float, height: float) -> List[Point]:
  25. """把多边形顶点夹到图像范围内。"""
  26. return [
  27. (min(max(float(x), 0.0), width), min(max(float(y), 0.0), height))
  28. for x, y in polygon
  29. ]
  30. def polygon_area(polygon: Polygon) -> float:
  31. """鞋带公式,返回绝对值面积。"""
  32. if len(polygon) < 3:
  33. return 0.0
  34. total = 0.0
  35. for i in range(len(polygon)):
  36. x1, y1 = polygon[i]
  37. x2, y2 = polygon[(i + 1) % len(polygon)]
  38. total += x1 * y2 - x2 * y1
  39. return abs(total) / 2.0
  40. def point_in_polygon(point: Point, polygon: Polygon) -> bool:
  41. """射线法判断点是否在多边形内(含边界近似)。"""
  42. if len(polygon) < 3:
  43. return False
  44. x, y = float(point[0]), float(point[1])
  45. inside = False
  46. n = len(polygon)
  47. for i in range(n):
  48. x1, y1 = polygon[i]
  49. x2, y2 = polygon[(i + 1) % n]
  50. if (y1 > y) != (y2 > y):
  51. x_cross = x1 + (y - y1) * (x2 - x1) / (y2 - y1)
  52. if x < x_cross:
  53. inside = not inside
  54. return inside
  55. def box_in_polygon_ratio(
  56. box: Box,
  57. polygon: Polygon,
  58. samples_x: int = 7,
  59. samples_y: int = 7,
  60. ) -> float:
  61. """用网格采样估计"框落在 ROI 内的面积比例"(0..1)。
  62. 比精确多边形裁剪简单得多,且对现场 ROI 精度完全够用;采样点先取中心,
  63. 保证目标很小时也能被识别到。
  64. """
  65. if len(polygon) < 3 or box.area <= 0:
  66. return 0.0
  67. sx = max(1, int(samples_x))
  68. sy = max(1, int(samples_y))
  69. hits = 0
  70. total = 0
  71. for ix in range(sx):
  72. fx = (ix + 0.5) / sx
  73. x = box.x1 + fx * box.width
  74. for iy in range(sy):
  75. fy = (iy + 0.5) / sy
  76. y = box.y1 + fy * box.height
  77. total += 1
  78. if point_in_polygon((x, y), polygon):
  79. hits += 1
  80. if total == 0:
  81. return 0.0
  82. return float(hits) / float(total)
  83. def nms(boxes: List[Box], iou_threshold: float = 0.5, per_class: bool = True) -> List[Box]:
  84. """非极大值抑制。``per_class=True`` 时按类别分别抑制(YOLO 常见做法)。"""
  85. if not boxes:
  86. return []
  87. order = sorted(boxes, key=lambda b: b.score, reverse=True)
  88. keep: List[Box] = []
  89. for box in order:
  90. suppressed = False
  91. for kept in keep:
  92. if per_class and kept.class_id != box.class_id:
  93. continue
  94. if box.iou(kept) > iou_threshold:
  95. suppressed = True
  96. break
  97. if not suppressed:
  98. keep.append(box)
  99. return keep