"""画面标注渲染(多语言:中文 / 英文 / 越南文),以及 JPEG 编码。 字体策略:PIL 单个字体无法做「逐字回退」,因此按会话语言选字体—— zh → assets 里的中文字体(覆盖 CJK) en/vi → DejaVu Sans 等拉丁+越南文字体(覆盖 ắ ầ ế ệ ố ộ ơ ư 等) 可用环境变量 DCCAI_FONT_ZH / DCCAI_FONT_LATIN 覆盖。 文字绘制使用「一次 PIL 转换 + 批量绘制」,避免每个标签都做一次 BGR↔RGB 全图拷贝。 """ from __future__ import annotations import threading import cv2 import numpy as np from PIL import Image, ImageDraw, ImageFont import os from . import config, i18n # 中文字体(CJK) _FONTS_ZH = [ os.environ.get("DCCAI_FONT_ZH", ""), config.ASSETS_DIR / "MiSans-Thin.ttf", config.ASSETS_DIR / "Alibaba_PuHuiTi_2.0_35_Thin_35_Thin.ttf", "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc", "/System/Library/Fonts/PingFang.ttc", "/System/Library/Fonts/Hiragino Sans GB.ttc", "C:/Windows/Fonts/msyh.ttc", ] # 拉丁 / 越南文字体(含 Latin Extended Additional) _FONTS_LATIN = [ os.environ.get("DCCAI_FONT_LATIN", ""), "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf", config.ASSETS_DIR / "MiSans-Thin.ttf", ] _FONT_LOCK = threading.Lock() _FONT_CACHE: dict[tuple[str, int], ImageFont.FreeTypeFont] = {} def _candidates(lang: str): """中文用 CJK 字体,其它语言优先用含越南文音标的拉丁字体。""" if i18n.normalize(lang) == "zh": return _FONTS_ZH + _FONTS_LATIN return _FONTS_LATIN + _FONTS_ZH REGION_COLORS = { "construction": (60, 180, 90), "warehouse": (180, 140, 60), "restricted": (60, 60, 220), "machinery": (220, 120, 40), "high_work": (200, 80, 200), } DEFAULT_COLOR = (200, 200, 200) def _font(size: int, lang: str = "zh"): key = (i18n.normalize(lang) or "zh", int(size)) with _FONT_LOCK: if key not in _FONT_CACHE: f = None for p in _candidates(key[0]): if not p: continue try: f = ImageFont.truetype(str(p), size) break except Exception: continue _FONT_CACHE[key] = f or ImageFont.load_default() return _FONT_CACHE[key] def draw(frame: np.ndarray, items: list[dict], hud: list[str] | None = None, regions: dict | None = None, lang: str = "zh") -> np.ndarray: """在 BGR 帧上绘制区域、检测框与本地化标签。返回同一帧对象(原地修改)。""" img = frame if regions: overlay = img.copy() for key, poly in regions.items(): if key == "count_line" or not poly or len(poly) < 3: continue col = REGION_COLORS.get(key, DEFAULT_COLOR) pts = np.array(poly, dtype=np.int32) cv2.polylines(img, [pts], True, col, 2) cv2.fillPoly(overlay, [pts], col) img = cv2.addWeighted(overlay, 0.12, img, 0.88, 0) line = regions.get("count_line") if line and len(line) >= 2: cv2.line(img, (int(line[0][0]), int(line[0][1])), (int(line[1][0]), int(line[1][1])), (0, 255, 255), 2) texts: list[tuple[str, int, int, tuple[int, int, int], bool]] = [] for it in items: box = it.get("box") if not box: continue x1, y1, x2, y2 = (int(v) for v in box) color = tuple(int(c) for c in it.get("color", (255, 255, 255))) cv2.rectangle(img, (x1, y1), (x2, y2), color, 3 if it.get("kind") == "event" else 2) label = it.get("label", "") if label and it.get("conf") is not None: label = f"{label} {it['conf']:.2f}" if label: texts.append((label, x1 + 2, max(24, y1 - 24), color, True)) hud_band_h = (32 * len(hud) + 14) if hud else 0 fh = img.shape[0] if regions: for key, poly in regions.items(): if key == "count_line" or not poly or len(poly) < 3: continue ys = [p[1] for p in poly] xs = [p[0] for p in poly] y = min(max(int(max(ys)) - 32, hud_band_h + 6), fh - 34) texts.append((config.region_name(lang, key), int(min(xs)) + 8, y, REGION_COLORS.get(key, DEFAULT_COLOR), True)) if hud: band = img[0:hud_band_h, 0:420].copy() cv2.rectangle(band, (0, 0), (420, hud_band_h), (0, 0, 0), -1) img[0:hud_band_h, 0:420] = cv2.addWeighted(band, 0.55, img[0:hud_band_h, 0:420], 0.45, 0) y = 34 for line in hud: texts.append((line, 18, y, (0, 255, 255), False)) y += 32 if texts: _draw_texts(img, texts, scale=max(0.6, min(1.6, img.shape[1] / 1280)), lang=lang) return img def _draw_texts(img: np.ndarray, texts, scale: float = 1.0, lang: str = "zh") -> None: """一次性把全部文字画到图上。""" base = int(20 * scale) pil = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) d = ImageDraw.Draw(pil) for text, x, y, bgr, bg in texts: font = _font(base, lang) rgb = (int(bgr[2]), int(bgr[1]), int(bgr[0])) if bg: try: l, t, r, b = d.textbbox((x, y), text, font=font) d.rectangle([l - 3, t - 2, r + 3, b + 2], fill=(0, 0, 0)) except Exception: pass d.text((x, y), text, font=font, fill=rgb) img[:] = cv2.cvtColor(np.array(pil), cv2.COLOR_RGB2BGR) def encode_jpeg(frame: np.ndarray, quality: int = 75) -> bytes: ok, buf = cv2.imencode(".jpg", frame, [int(cv2.IMWRITE_JPEG_QUALITY), quality]) return buf.tobytes() if ok else b""