draw_rect.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. """在匹配图上绘制模板四角透视框(多边形)。"""
  2. from __future__ import annotations
  3. from pathlib import Path
  4. import cv2
  5. import numpy as np
  6. from routing import repo_path
  7. def draw_rect(
  8. corners_xy: np.ndarray | list,
  9. *,
  10. match_image: str | Path,
  11. output_path: str | Path,
  12. outline_color_bgr: tuple[int, int, int] = (0, 255, 0),
  13. outline_thickness_pixels: int = 6,
  14. ) -> Path:
  15. """
  16. ``corners_xy``:``(4, 2)`` 顶点顺序与 ``corner_points_on_match_img`` 一致(闭合四边形)。
  17. """
  18. scr = repo_path(match_image)
  19. bgr = cv2.imread(str(scr), cv2.IMREAD_COLOR)
  20. if bgr is None:
  21. raise FileNotFoundError(f"无法读取匹配图:{scr}")
  22. pts = np.asarray(corners_xy, dtype=np.float64).reshape(4, 2)
  23. if pts.shape != (4, 2) or not np.all(np.isfinite(pts)):
  24. raise ValueError("corners_xy 须为 (4, 2) 有限坐标")
  25. pi = pts.astype(np.int32).reshape(-1, 1, 2)
  26. cv2.polylines(
  27. bgr,
  28. [pi],
  29. isClosed=True,
  30. color=outline_color_bgr,
  31. thickness=int(outline_thickness_pixels),
  32. lineType=cv2.LINE_AA,
  33. )
  34. out = repo_path(output_path)
  35. out.parent.mkdir(parents=True, exist_ok=True)
  36. if not cv2.imwrite(str(out), bgr):
  37. raise OSError(f"无法写入:{out}")
  38. return out