"""画面标注渲染(支持中文),以及 JPEG 编码。 文字绘制使用「一次 PIL 转换 + 批量绘制」,避免每个标签都做一次 BGR↔RGB 全图拷贝。 """ from __future__ import annotations import threading import cv2 import numpy as np from PIL import Image, ImageDraw, ImageFont from . import config _FONT_CANDIDATES = [ config.ASSETS_DIR / "MiSans-Thin.ttf", config.ASSETS_DIR / "Alibaba_PuHuiTi_2.0_35_Thin_35_Thin.ttf", "/System/Library/Fonts/PingFang.ttc", "/System/Library/Fonts/Hiragino Sans GB.ttc", "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc", "C:/Windows/Fonts/msyh.ttc", ] _FONT_LOCK = threading.Lock() _FONT_CACHE: dict[int, ImageFont.FreeTypeFont] = {} 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): with _FONT_LOCK: if size not in _FONT_CACHE: f = None for p in _FONT_CANDIDATES: try: f = ImageFont.truetype(str(p), size) break except Exception: continue _FONT_CACHE[size] = f or ImageFont.load_default() return _FONT_CACHE[size] def draw(frame: np.ndarray, items: list[dict], hud: list[str] | None = None, regions: dict | None = None) -> 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_NAMES.get(key, 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))) return img def _draw_texts(img: np.ndarray, texts, scale: float = 1.0) -> 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) 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""