"""P0-3 视觉自监测:图像质量 / 传感器退化 / 数据链健康。 现场最容易出现的“算法看起来在跑、其实输入已经不可用”的情况: * 镜头结露、雨滴、油污 → 画面整体模糊或局部低纹理; * 逆光/夜间补光过曝 → 大面积削顶; * 镜头被遮挡/贴纸 → 画面近乎均匀,Laplacian 方差趋零; * 取流断链 → 由 ``runner`` 的 ``FRAME_TIMEOUT`` 处理。 本模块**不改变**分类结果,只输出可解释的健康报告;``runner`` 把 ``sensor_degraded`` / ``perception_uncertain`` 映射到 flags bit10/bit8, 并按 GB/T 45163.5 5.1.4 请求 MRC(bit9)。 """ from __future__ import annotations import math import time from dataclasses import dataclass, field from typing import Dict, List, Optional import numpy as np try: # pragma: no cover - 与 evidence_v2 同一策略 import cv2 except ImportError: # pragma: no cover cv2 = None # type: ignore from .config import Config __all__ = ["FrameHealthMonitor", "HealthParams", "HealthReport"] @dataclass(frozen=True) class HealthParams: """``health.*`` 配置(阈值现场可整定)。""" enabled: bool = True work_width: int = 320 blur_var_min: float = 18.0 dark_clip_ratio_max: float = 0.97 bright_clip_ratio_max: float = 0.55 low_texture_ratio_max: float = 0.88 degrade_persist_s: float = 0.8 recover_persist_s: float = 1.5 @classmethod def from_config(cls, cfg: Config) -> "HealthParams": raw = cfg.section("health") return cls( enabled=bool(raw.get("enabled", True)), work_width=max(64, int(raw.get("work_width", 320))), blur_var_min=max(0.0, float(raw.get("blur_var_min", 18.0))), dark_clip_ratio_max=float(raw.get("dark_clip_ratio_max", 0.97)), bright_clip_ratio_max=float(raw.get("bright_clip_ratio_max", 0.55)), low_texture_ratio_max=float(raw.get("low_texture_ratio_max", 0.88)), degrade_persist_s=max(0.0, float(raw.get("degrade_persist_s", 0.8))), recover_persist_s=max(0.0, float(raw.get("recover_persist_s", 1.5))), ) @dataclass class HealthReport: """一帧的健康结论;字段可直接写 JSONL。""" ts: float = 0.0 sensor_degraded: bool = False perception_uncertain: bool = False blur_var: float = 0.0 dark_clip_ratio: float = 0.0 bright_clip_ratio: float = 0.0 low_texture_ratio: float = 0.0 motion_diff: float = 0.0 reasons: List[str] = field(default_factory=list) @property def ok(self) -> bool: return not self.sensor_degraded and not self.perception_uncertain def to_dict(self) -> Dict[str, object]: return { "ts": round(float(self.ts), 6), "ok": bool(self.ok), "sensor_degraded": bool(self.sensor_degraded), "perception_uncertain": bool(self.perception_uncertain), "blur_var": round(float(self.blur_var), 3), "dark_clip_ratio": round(float(self.dark_clip_ratio), 4), "bright_clip_ratio": round(float(self.bright_clip_ratio), 4), "low_texture_ratio": round(float(self.low_texture_ratio), 4), "motion_diff": round(float(self.motion_diff), 4), "reasons": list(self.reasons), } class FrameHealthMonitor: """逐帧图像健康监测(线程内使用,非线程安全)。""" def __init__(self, params: Optional[HealthParams] = None) -> None: self.p = params or HealthParams() self._degraded = False self._bad_since: Optional[float] = None self._good_since: Optional[float] = None self._prev_thumb: Optional[np.ndarray] = None self._last = HealthReport() @classmethod def from_config(cls, cfg: Config) -> "FrameHealthMonitor": return cls(HealthParams.from_config(cfg)) @property def last(self) -> HealthReport: return self._last def reset(self) -> None: self._degraded = False self._bad_since = None self._good_since = None self._prev_thumb = None self._last = HealthReport() def observe(self, image: np.ndarray, ts: Optional[float] = None) -> HealthReport: """分析一帧;``enabled=False`` 时只返回空报告(零开销)。""" ts_value = float(time.time() if ts is None else ts) if not self.p.enabled: self._last = HealthReport(ts=ts_value) return self._last if image is None or getattr(image, "size", 0) == 0: self._last = HealthReport( ts=ts_value, sensor_degraded=True, perception_uncertain=True, reasons=["no_image"], ) return self._last gray = image if gray.ndim == 3: if cv2 is not None: gray = cv2.cvtColor(gray, cv2.COLOR_BGR2GRAY) else: # pragma: no cover - 无 OpenCV 时退化为亮度均值 gray = gray[..., :3].mean(axis=2).astype(np.uint8) h, w = gray.shape[:2] scale = min(1.0, float(self.p.work_width) / float(max(1, w))) if cv2 is not None and scale < 1.0: gray = cv2.resize( gray, (int(round(w * scale)), int(round(h * scale))), interpolation=cv2.INTER_AREA, ) blur_var = 0.0 if cv2 is not None: blur_var = float(cv2.Laplacian(gray, cv2.CV_64F).var()) total = float(max(1, gray.size)) dark = float(np.count_nonzero(gray <= 5)) / total bright = float(np.count_nonzero(gray >= 250)) / total low_texture = self._low_texture_ratio(gray) motion_diff = self._motion_diff(gray) reasons: List[str] = [] blur_bad = blur_var < self.p.blur_var_min and low_texture >= 0.65 dark_bad = dark >= self.p.dark_clip_ratio_max and low_texture >= 0.80 bright_bad = bright >= self.p.bright_clip_ratio_max and low_texture >= 0.80 flat_bad = low_texture >= self.p.low_texture_ratio_max if blur_bad: reasons.append("blur") if dark_bad: reasons.append("dark_clip") if bright_bad: reasons.append("bright_clip") if flat_bad: reasons.append("low_texture") raw_bad = blur_bad or dark_bad or bright_bad or flat_bad # 迟滞:连续 raw_bad 超过 degrade_persist_s 才报退化;恢复也要 # 连续正常 recover_persist_s,避免雨滴/飞虫造成逐帧抖动。 if raw_bad: if self._bad_since is None: self._bad_since = ts_value self._good_since = None if ts_value - self._bad_since >= self.p.degrade_persist_s: self._degraded = True else: self._bad_since = None if self._good_since is None: self._good_since = ts_value if ts_value - self._good_since >= self.p.recover_persist_s: self._degraded = False self._last = HealthReport( ts=ts_value, sensor_degraded=bool(self._degraded), perception_uncertain=bool(self._degraded), blur_var=blur_var, dark_clip_ratio=dark, bright_clip_ratio=bright, low_texture_ratio=low_texture, motion_diff=motion_diff, reasons=reasons if self._degraded else [], ) return self._last # ---------------------------------------------------------------- 内部 @staticmethod def _low_texture_ratio(gray: np.ndarray) -> float: h, w = gray.shape[:2] block = 16 if h < block or w < block: return 1.0 if float(np.std(gray)) < 3.5 else 0.0 hh = (h // block) * block ww = (w // block) * block blocks = gray[:hh, :ww].reshape(hh // block, block, ww // block, block) stds = blocks.std(axis=(1, 3)) return float(np.mean(stds < 3.5)) def _motion_diff(self, gray: np.ndarray) -> float: thumb = gray if cv2 is not None: thumb = cv2.resize(gray, (160, 90), interpolation=cv2.INTER_AREA) if self._prev_thumb is None or self._prev_thumb.shape != thumb.shape: self._prev_thumb = thumb.astype(np.uint8, copy=True) return 0.0 diff = float( np.abs(thumb.astype(np.float32) - self._prev_thumb.astype(np.float32)).mean() ) self._prev_thumb = thumb.astype(np.uint8, copy=True) return diff if math.isfinite(diff) else 0.0