"""几何工具:NMS、点/框与多边形 ROI 的关系。 只依赖标准库 + 纯 Python 计算(numpy 可选加速),保证在 RK/Jetson 上都能跑。 所有坐标均为像素坐标;ROI 在配置里是**归一化**坐标,使用时用 :func:`normalized_to_pixel_polygon` 转成像素。 """ from __future__ import annotations from typing import List, Sequence, Tuple from ..schema import Box Point = Tuple[float, float] Polygon = Sequence[Point] __all__ = [ "box_in_polygon_ratio", "clip_polygon", "nms", "normalized_to_pixel_polygon", "point_in_polygon", "polygon_area", ] def normalized_to_pixel_polygon(polygon: Polygon, width: float, height: float) -> List[Point]: """归一化多边形 → 像素多边形。""" if not polygon: return [(0.0, 0.0), (width, 0.0), (width, height), (0.0, height)] return [(float(x) * width, float(y) * height) for x, y in polygon] def clip_polygon(polygon: Polygon, width: float, height: float) -> List[Point]: """把多边形顶点夹到图像范围内。""" return [ (min(max(float(x), 0.0), width), min(max(float(y), 0.0), height)) for x, y in polygon ] def polygon_area(polygon: Polygon) -> float: """鞋带公式,返回绝对值面积。""" if len(polygon) < 3: return 0.0 total = 0.0 for i in range(len(polygon)): x1, y1 = polygon[i] x2, y2 = polygon[(i + 1) % len(polygon)] total += x1 * y2 - x2 * y1 return abs(total) / 2.0 def point_in_polygon(point: Point, polygon: Polygon) -> bool: """射线法判断点是否在多边形内(含边界近似)。""" if len(polygon) < 3: return False x, y = float(point[0]), float(point[1]) inside = False n = len(polygon) for i in range(n): x1, y1 = polygon[i] x2, y2 = polygon[(i + 1) % n] if (y1 > y) != (y2 > y): x_cross = x1 + (y - y1) * (x2 - x1) / (y2 - y1) if x < x_cross: inside = not inside return inside def box_in_polygon_ratio( box: Box, polygon: Polygon, samples_x: int = 7, samples_y: int = 7, ) -> float: """用网格采样估计"框落在 ROI 内的面积比例"(0..1)。 比精确多边形裁剪简单得多,且对现场 ROI 精度完全够用;采样点先取中心, 保证目标很小时也能被识别到。 """ if len(polygon) < 3 or box.area <= 0: return 0.0 sx = max(1, int(samples_x)) sy = max(1, int(samples_y)) hits = 0 total = 0 for ix in range(sx): fx = (ix + 0.5) / sx x = box.x1 + fx * box.width for iy in range(sy): fy = (iy + 0.5) / sy y = box.y1 + fy * box.height total += 1 if point_in_polygon((x, y), polygon): hits += 1 if total == 0: return 0.0 return float(hits) / float(total) def nms(boxes: List[Box], iou_threshold: float = 0.5, per_class: bool = True) -> List[Box]: """非极大值抑制。``per_class=True`` 时按类别分别抑制(YOLO 常见做法)。""" if not boxes: return [] order = sorted(boxes, key=lambda b: b.score, reverse=True) keep: List[Box] = [] for box in order: suppressed = False for kept in keep: if per_class and kept.class_id != box.class_id: continue if box.iou(kept) > iou_threshold: suppressed = True break if not suppressed: keep.append(box) return keep