render.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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. # 随仓库分发(assets/DejaVuSans.ttf,Bitstream Vera 许可),无需系统装字体,
  30. # 因此基础镜像不用为了越南文重新构建
  31. config.ASSETS_DIR / "DejaVuSans.ttf",
  32. "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
  33. "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
  34. "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",
  35. config.ASSETS_DIR / "MiSans-Thin.ttf",
  36. ]
  37. _FONT_LOCK = threading.Lock()
  38. _FONT_CACHE: dict[tuple[str, int], ImageFont.FreeTypeFont] = {}
  39. def _candidates(lang: str):
  40. """中文用 CJK 字体,其它语言优先用含越南文音标的拉丁字体。"""
  41. if i18n.normalize(lang) == "zh":
  42. return _FONTS_ZH + _FONTS_LATIN
  43. return _FONTS_LATIN + _FONTS_ZH
  44. REGION_COLORS = {
  45. "construction": (60, 180, 90),
  46. "warehouse": (180, 140, 60),
  47. "restricted": (60, 60, 220),
  48. "machinery": (220, 120, 40),
  49. "high_work": (200, 80, 200),
  50. }
  51. DEFAULT_COLOR = (200, 200, 200)
  52. def _font(size: int, lang: str = "zh"):
  53. key = (i18n.normalize(lang) or "zh", int(size))
  54. with _FONT_LOCK:
  55. if key not in _FONT_CACHE:
  56. f = None
  57. for p in _candidates(key[0]):
  58. if not p:
  59. continue
  60. try:
  61. f = ImageFont.truetype(str(p), size)
  62. break
  63. except Exception:
  64. continue
  65. _FONT_CACHE[key] = f or ImageFont.load_default()
  66. return _FONT_CACHE[key]
  67. def draw(frame: np.ndarray, items: list[dict], hud: list[str] | None = None,
  68. regions: dict | None = None, lang: str = "zh") -> np.ndarray:
  69. """在 BGR 帧上绘制区域、检测框与本地化标签。返回同一帧对象(原地修改)。"""
  70. img = frame
  71. if regions:
  72. overlay = img.copy()
  73. for key, poly in regions.items():
  74. if key == "count_line" or not poly or len(poly) < 3:
  75. continue
  76. col = REGION_COLORS.get(key, DEFAULT_COLOR)
  77. pts = np.array(poly, dtype=np.int32)
  78. cv2.polylines(img, [pts], True, col, 2)
  79. cv2.fillPoly(overlay, [pts], col)
  80. img = cv2.addWeighted(overlay, 0.12, img, 0.88, 0)
  81. line = regions.get("count_line")
  82. if line and len(line) >= 2:
  83. cv2.line(img, (int(line[0][0]), int(line[0][1])),
  84. (int(line[1][0]), int(line[1][1])), (0, 255, 255), 2)
  85. texts: list[tuple[str, int, int, tuple[int, int, int], bool]] = []
  86. for it in items:
  87. box = it.get("box")
  88. if not box:
  89. continue
  90. x1, y1, x2, y2 = (int(v) for v in box)
  91. color = tuple(int(c) for c in it.get("color", (255, 255, 255)))
  92. cv2.rectangle(img, (x1, y1), (x2, y2), color, 3 if it.get("kind") == "event" else 2)
  93. label = it.get("label", "")
  94. if label and it.get("conf") is not None:
  95. label = f"{label} {it['conf']:.2f}"
  96. if label:
  97. texts.append((label, x1 + 2, max(24, y1 - 24), color, True))
  98. hud_band_h = (32 * len(hud) + 14) if hud else 0
  99. fh = img.shape[0]
  100. if regions:
  101. for key, poly in regions.items():
  102. if key == "count_line" or not poly or len(poly) < 3:
  103. continue
  104. ys = [p[1] for p in poly]
  105. xs = [p[0] for p in poly]
  106. y = min(max(int(max(ys)) - 32, hud_band_h + 6), fh - 34)
  107. texts.append((config.region_name(lang, key),
  108. int(min(xs)) + 8, y,
  109. REGION_COLORS.get(key, DEFAULT_COLOR), True))
  110. if hud:
  111. band = img[0:hud_band_h, 0:420].copy()
  112. cv2.rectangle(band, (0, 0), (420, hud_band_h), (0, 0, 0), -1)
  113. img[0:hud_band_h, 0:420] = cv2.addWeighted(band, 0.55, img[0:hud_band_h, 0:420], 0.45, 0)
  114. y = 34
  115. for line in hud:
  116. texts.append((line, 18, y, (0, 255, 255), False))
  117. y += 32
  118. if texts:
  119. _draw_texts(img, texts, scale=max(0.6, min(1.6, img.shape[1] / 1280)), lang=lang)
  120. return img
  121. def _draw_texts(img: np.ndarray, texts, scale: float = 1.0, lang: str = "zh") -> None:
  122. """一次性把全部文字画到图上。"""
  123. base = int(20 * scale)
  124. pil = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
  125. d = ImageDraw.Draw(pil)
  126. for text, x, y, bgr, bg in texts:
  127. font = _font(base, lang)
  128. rgb = (int(bgr[2]), int(bgr[1]), int(bgr[0]))
  129. if bg:
  130. try:
  131. l, t, r, b = d.textbbox((x, y), text, font=font)
  132. d.rectangle([l - 3, t - 2, r + 3, b + 2], fill=(0, 0, 0))
  133. except Exception:
  134. pass
  135. d.text((x, y), text, font=font, fill=rgb)
  136. img[:] = cv2.cvtColor(np.array(pil), cv2.COLOR_RGB2BGR)
  137. def encode_jpeg(frame: np.ndarray, quality: int = 75) -> bytes:
  138. ok, buf = cv2.imencode(".jpg", frame, [int(cv2.IMWRITE_JPEG_QUALITY), quality])
  139. return buf.tobytes() if ok else b""