render.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. """画面标注渲染(支持中文),以及 JPEG 编码。
  2. 文字绘制使用「一次 PIL 转换 + 批量绘制」,避免每个标签都做一次 BGR↔RGB 全图拷贝。
  3. """
  4. from __future__ import annotations
  5. import threading
  6. import cv2
  7. import numpy as np
  8. from PIL import Image, ImageDraw, ImageFont
  9. from . import config
  10. _FONT_CANDIDATES = [
  11. config.ASSETS_DIR / "MiSans-Thin.ttf",
  12. config.ASSETS_DIR / "Alibaba_PuHuiTi_2.0_35_Thin_35_Thin.ttf",
  13. "/System/Library/Fonts/PingFang.ttc",
  14. "/System/Library/Fonts/Hiragino Sans GB.ttc",
  15. "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
  16. "C:/Windows/Fonts/msyh.ttc",
  17. ]
  18. _FONT_LOCK = threading.Lock()
  19. _FONT_CACHE: dict[int, ImageFont.FreeTypeFont] = {}
  20. REGION_COLORS = {
  21. "construction": (60, 180, 90),
  22. "warehouse": (180, 140, 60),
  23. "restricted": (60, 60, 220),
  24. "machinery": (220, 120, 40),
  25. "high_work": (200, 80, 200),
  26. }
  27. DEFAULT_COLOR = (200, 200, 200)
  28. def _font(size: int):
  29. with _FONT_LOCK:
  30. if size not in _FONT_CACHE:
  31. f = None
  32. for p in _FONT_CANDIDATES:
  33. try:
  34. f = ImageFont.truetype(str(p), size)
  35. break
  36. except Exception:
  37. continue
  38. _FONT_CACHE[size] = f or ImageFont.load_default()
  39. return _FONT_CACHE[size]
  40. def draw(frame: np.ndarray, items: list[dict], hud: list[str] | None = None,
  41. regions: dict | None = None) -> np.ndarray:
  42. """在 BGR 帧上绘制区域、检测框与中文标签。返回同一帧对象(原地修改)。"""
  43. img = frame
  44. if regions:
  45. overlay = img.copy()
  46. for key, poly in regions.items():
  47. if key == "count_line" or not poly or len(poly) < 3:
  48. continue
  49. col = REGION_COLORS.get(key, DEFAULT_COLOR)
  50. pts = np.array(poly, dtype=np.int32)
  51. cv2.polylines(img, [pts], True, col, 2)
  52. cv2.fillPoly(overlay, [pts], col)
  53. img = cv2.addWeighted(overlay, 0.12, img, 0.88, 0)
  54. line = regions.get("count_line")
  55. if line and len(line) >= 2:
  56. cv2.line(img, (int(line[0][0]), int(line[0][1])),
  57. (int(line[1][0]), int(line[1][1])), (0, 255, 255), 2)
  58. texts: list[tuple[str, int, int, tuple[int, int, int], bool]] = []
  59. for it in items:
  60. box = it.get("box")
  61. if not box:
  62. continue
  63. x1, y1, x2, y2 = (int(v) for v in box)
  64. color = tuple(int(c) for c in it.get("color", (255, 255, 255)))
  65. cv2.rectangle(img, (x1, y1), (x2, y2), color, 3 if it.get("kind") == "event" else 2)
  66. label = it.get("label", "")
  67. if label and it.get("conf") is not None:
  68. label = f"{label} {it['conf']:.2f}"
  69. if label:
  70. texts.append((label, x1 + 2, max(24, y1 - 24), color, True))
  71. hud_band_h = (32 * len(hud) + 14) if hud else 0
  72. fh = img.shape[0]
  73. if regions:
  74. for key, poly in regions.items():
  75. if key == "count_line" or not poly or len(poly) < 3:
  76. continue
  77. ys = [p[1] for p in poly]
  78. xs = [p[0] for p in poly]
  79. y = min(max(int(max(ys)) - 32, hud_band_h + 6), fh - 34)
  80. texts.append((config.REGION_NAMES.get(key, key),
  81. int(min(xs)) + 8, y,
  82. REGION_COLORS.get(key, DEFAULT_COLOR), True))
  83. if hud:
  84. band = img[0:hud_band_h, 0:420].copy()
  85. cv2.rectangle(band, (0, 0), (420, hud_band_h), (0, 0, 0), -1)
  86. img[0:hud_band_h, 0:420] = cv2.addWeighted(band, 0.55, img[0:hud_band_h, 0:420], 0.45, 0)
  87. y = 34
  88. for line in hud:
  89. texts.append((line, 18, y, (0, 255, 255), False))
  90. y += 32
  91. if texts:
  92. _draw_texts(img, texts, scale=max(0.6, min(1.6, img.shape[1] / 1280)))
  93. return img
  94. def _draw_texts(img: np.ndarray, texts, scale: float = 1.0) -> None:
  95. """一次性把全部文字画到图上。"""
  96. base = int(20 * scale)
  97. pil = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
  98. d = ImageDraw.Draw(pil)
  99. for text, x, y, bgr, bg in texts:
  100. font = _font(base)
  101. rgb = (int(bgr[2]), int(bgr[1]), int(bgr[0]))
  102. if bg:
  103. try:
  104. l, t, r, b = d.textbbox((x, y), text, font=font)
  105. d.rectangle([l - 3, t - 2, r + 3, b + 2], fill=(0, 0, 0))
  106. except Exception:
  107. pass
  108. d.text((x, y), text, font=font, fill=rgb)
  109. img[:] = cv2.cvtColor(np.array(pil), cv2.COLOR_RGB2BGR)
  110. def encode_jpeg(frame: np.ndarray, quality: int = 75) -> bytes:
  111. ok, buf = cv2.imencode(".jpg", frame, [int(cv2.IMWRITE_JPEG_QUALITY), quality])
  112. return buf.tobytes() if ok else b""