render.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. """画面标注渲染(多语言:中文 / 英文 / 越南文),以及 JPEG 编码。
  2. 字体策略:PIL 单个字体无法做「逐字回退」,因此按会话语言选字体——
  3. zh → assets 里的中文字体(覆盖 CJK)
  4. en/vi → DejaVu Sans 等拉丁+越南文字体(覆盖 ắ ầ ế ệ ố ộ ơ ư 等)
  5. 可用环境变量 DCCAI_FONT_ZH / DCCAI_FONT_LATIN 覆盖。
  6. 文字绘制使用「一次 PIL 转换 + 批量绘制」,避免每个标签都做一次 BGR↔RGB 全图拷贝。
  7. """
  8. from __future__ import annotations
  9. import threading
  10. import cv2
  11. import numpy as np
  12. from PIL import Image, ImageDraw, ImageFont
  13. import os
  14. from . import config, i18n
  15. # 中文字体(CJK)
  16. _FONTS_ZH = [
  17. os.environ.get("DCCAI_FONT_ZH", ""),
  18. config.ASSETS_DIR / "MiSans-Thin.ttf",
  19. config.ASSETS_DIR / "Alibaba_PuHuiTi_2.0_35_Thin_35_Thin.ttf",
  20. "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
  21. "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
  22. "/System/Library/Fonts/PingFang.ttc",
  23. "/System/Library/Fonts/Hiragino Sans GB.ttc",
  24. "C:/Windows/Fonts/msyh.ttc",
  25. ]
  26. # 拉丁 / 越南文字体(含 Latin Extended Additional)
  27. _FONTS_LATIN = [
  28. os.environ.get("DCCAI_FONT_LATIN", ""),
  29. "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
  30. "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
  31. "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",
  32. config.ASSETS_DIR / "MiSans-Thin.ttf",
  33. ]
  34. _FONT_LOCK = threading.Lock()
  35. _FONT_CACHE: dict[tuple[str, int], ImageFont.FreeTypeFont] = {}
  36. def _candidates(lang: str):
  37. """中文用 CJK 字体,其它语言优先用含越南文音标的拉丁字体。"""
  38. if i18n.normalize(lang) == "zh":
  39. return _FONTS_ZH + _FONTS_LATIN
  40. return _FONTS_LATIN + _FONTS_ZH
  41. REGION_COLORS = {
  42. "construction": (60, 180, 90),
  43. "warehouse": (180, 140, 60),
  44. "restricted": (60, 60, 220),
  45. "machinery": (220, 120, 40),
  46. "high_work": (200, 80, 200),
  47. }
  48. DEFAULT_COLOR = (200, 200, 200)
  49. def _font(size: int, lang: str = "zh"):
  50. key = (i18n.normalize(lang) or "zh", int(size))
  51. with _FONT_LOCK:
  52. if key not in _FONT_CACHE:
  53. f = None
  54. for p in _candidates(key[0]):
  55. if not p:
  56. continue
  57. try:
  58. f = ImageFont.truetype(str(p), size)
  59. break
  60. except Exception:
  61. continue
  62. _FONT_CACHE[key] = f or ImageFont.load_default()
  63. return _FONT_CACHE[key]
  64. def draw(frame: np.ndarray, items: list[dict], hud: list[str] | None = None,
  65. regions: dict | None = None, lang: str = "zh") -> np.ndarray:
  66. """在 BGR 帧上绘制区域、检测框与本地化标签。返回同一帧对象(原地修改)。"""
  67. img = frame
  68. if regions:
  69. overlay = img.copy()
  70. for key, poly in regions.items():
  71. if key == "count_line" or not poly or len(poly) < 3:
  72. continue
  73. col = REGION_COLORS.get(key, DEFAULT_COLOR)
  74. pts = np.array(poly, dtype=np.int32)
  75. cv2.polylines(img, [pts], True, col, 2)
  76. cv2.fillPoly(overlay, [pts], col)
  77. img = cv2.addWeighted(overlay, 0.12, img, 0.88, 0)
  78. line = regions.get("count_line")
  79. if line and len(line) >= 2:
  80. cv2.line(img, (int(line[0][0]), int(line[0][1])),
  81. (int(line[1][0]), int(line[1][1])), (0, 255, 255), 2)
  82. texts: list[tuple[str, int, int, tuple[int, int, int], bool]] = []
  83. for it in items:
  84. box = it.get("box")
  85. if not box:
  86. continue
  87. x1, y1, x2, y2 = (int(v) for v in box)
  88. color = tuple(int(c) for c in it.get("color", (255, 255, 255)))
  89. cv2.rectangle(img, (x1, y1), (x2, y2), color, 3 if it.get("kind") == "event" else 2)
  90. label = it.get("label", "")
  91. if label and it.get("conf") is not None:
  92. label = f"{label} {it['conf']:.2f}"
  93. if label:
  94. texts.append((label, x1 + 2, max(24, y1 - 24), color, True))
  95. hud_band_h = (32 * len(hud) + 14) if hud else 0
  96. fh = img.shape[0]
  97. if regions:
  98. for key, poly in regions.items():
  99. if key == "count_line" or not poly or len(poly) < 3:
  100. continue
  101. ys = [p[1] for p in poly]
  102. xs = [p[0] for p in poly]
  103. y = min(max(int(max(ys)) - 32, hud_band_h + 6), fh - 34)
  104. texts.append((config.region_name(lang, key),
  105. int(min(xs)) + 8, y,
  106. REGION_COLORS.get(key, DEFAULT_COLOR), True))
  107. if hud:
  108. band = img[0:hud_band_h, 0:420].copy()
  109. cv2.rectangle(band, (0, 0), (420, hud_band_h), (0, 0, 0), -1)
  110. img[0:hud_band_h, 0:420] = cv2.addWeighted(band, 0.55, img[0:hud_band_h, 0:420], 0.45, 0)
  111. y = 34
  112. for line in hud:
  113. texts.append((line, 18, y, (0, 255, 255), False))
  114. y += 32
  115. if texts:
  116. _draw_texts(img, texts, scale=max(0.6, min(1.6, img.shape[1] / 1280)), lang=lang)
  117. return img
  118. def _draw_texts(img: np.ndarray, texts, scale: float = 1.0, lang: str = "zh") -> None:
  119. """一次性把全部文字画到图上。"""
  120. base = int(20 * scale)
  121. pil = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
  122. d = ImageDraw.Draw(pil)
  123. for text, x, y, bgr, bg in texts:
  124. font = _font(base, lang)
  125. rgb = (int(bgr[2]), int(bgr[1]), int(bgr[0]))
  126. if bg:
  127. try:
  128. l, t, r, b = d.textbbox((x, y), text, font=font)
  129. d.rectangle([l - 3, t - 2, r + 3, b + 2], fill=(0, 0, 0))
  130. except Exception:
  131. pass
  132. d.text((x, y), text, font=font, fill=rgb)
  133. img[:] = cv2.cvtColor(np.array(pil), cv2.COLOR_RGB2BGR)
  134. def encode_jpeg(frame: np.ndarray, quality: int = 75) -> bytes:
  135. ok, buf = cv2.imencode(".jpg", frame, [int(cv2.IMWRITE_JPEG_QUALITY), quality])
  136. return buf.tobytes() if ok else b""