health.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. """P0-3 视觉自监测:图像质量 / 传感器退化 / 数据链健康。
  2. 现场最容易出现的“算法看起来在跑、其实输入已经不可用”的情况:
  3. * 镜头结露、雨滴、油污 → 画面整体模糊或局部低纹理;
  4. * 逆光/夜间补光过曝 → 大面积削顶;
  5. * 镜头被遮挡/贴纸 → 画面近乎均匀,Laplacian 方差趋零;
  6. * 取流断链 → 由 ``runner`` 的 ``FRAME_TIMEOUT`` 处理。
  7. 本模块**不改变**分类结果,只输出可解释的健康报告;``runner`` 把
  8. ``sensor_degraded`` / ``perception_uncertain`` 映射到 flags bit10/bit8,
  9. 并按 GB/T 45163.5 5.1.4 请求 MRC(bit9)。
  10. """
  11. from __future__ import annotations
  12. import math
  13. import time
  14. from dataclasses import dataclass, field
  15. from typing import Dict, List, Optional
  16. import numpy as np
  17. try: # pragma: no cover - 与 evidence_v2 同一策略
  18. import cv2
  19. except ImportError: # pragma: no cover
  20. cv2 = None # type: ignore
  21. from .config import Config
  22. __all__ = ["FrameHealthMonitor", "HealthParams", "HealthReport"]
  23. @dataclass(frozen=True)
  24. class HealthParams:
  25. """``health.*`` 配置(阈值现场可整定)。"""
  26. enabled: bool = True
  27. work_width: int = 320
  28. blur_var_min: float = 18.0
  29. dark_clip_ratio_max: float = 0.97
  30. bright_clip_ratio_max: float = 0.55
  31. low_texture_ratio_max: float = 0.88
  32. degrade_persist_s: float = 0.8
  33. recover_persist_s: float = 1.5
  34. @classmethod
  35. def from_config(cls, cfg: Config) -> "HealthParams":
  36. raw = cfg.section("health")
  37. return cls(
  38. enabled=bool(raw.get("enabled", True)),
  39. work_width=max(64, int(raw.get("work_width", 320))),
  40. blur_var_min=max(0.0, float(raw.get("blur_var_min", 18.0))),
  41. dark_clip_ratio_max=float(raw.get("dark_clip_ratio_max", 0.97)),
  42. bright_clip_ratio_max=float(raw.get("bright_clip_ratio_max", 0.55)),
  43. low_texture_ratio_max=float(raw.get("low_texture_ratio_max", 0.88)),
  44. degrade_persist_s=max(0.0, float(raw.get("degrade_persist_s", 0.8))),
  45. recover_persist_s=max(0.0, float(raw.get("recover_persist_s", 1.5))),
  46. )
  47. @dataclass
  48. class HealthReport:
  49. """一帧的健康结论;字段可直接写 JSONL。"""
  50. ts: float = 0.0
  51. sensor_degraded: bool = False
  52. perception_uncertain: bool = False
  53. blur_var: float = 0.0
  54. dark_clip_ratio: float = 0.0
  55. bright_clip_ratio: float = 0.0
  56. low_texture_ratio: float = 0.0
  57. motion_diff: float = 0.0
  58. reasons: List[str] = field(default_factory=list)
  59. @property
  60. def ok(self) -> bool:
  61. return not self.sensor_degraded and not self.perception_uncertain
  62. def to_dict(self) -> Dict[str, object]:
  63. return {
  64. "ts": round(float(self.ts), 6),
  65. "ok": bool(self.ok),
  66. "sensor_degraded": bool(self.sensor_degraded),
  67. "perception_uncertain": bool(self.perception_uncertain),
  68. "blur_var": round(float(self.blur_var), 3),
  69. "dark_clip_ratio": round(float(self.dark_clip_ratio), 4),
  70. "bright_clip_ratio": round(float(self.bright_clip_ratio), 4),
  71. "low_texture_ratio": round(float(self.low_texture_ratio), 4),
  72. "motion_diff": round(float(self.motion_diff), 4),
  73. "reasons": list(self.reasons),
  74. }
  75. class FrameHealthMonitor:
  76. """逐帧图像健康监测(线程内使用,非线程安全)。"""
  77. def __init__(self, params: Optional[HealthParams] = None) -> None:
  78. self.p = params or HealthParams()
  79. self._degraded = False
  80. self._bad_since: Optional[float] = None
  81. self._good_since: Optional[float] = None
  82. self._prev_thumb: Optional[np.ndarray] = None
  83. self._last = HealthReport()
  84. @classmethod
  85. def from_config(cls, cfg: Config) -> "FrameHealthMonitor":
  86. return cls(HealthParams.from_config(cfg))
  87. @property
  88. def last(self) -> HealthReport:
  89. return self._last
  90. def reset(self) -> None:
  91. self._degraded = False
  92. self._bad_since = None
  93. self._good_since = None
  94. self._prev_thumb = None
  95. self._last = HealthReport()
  96. def observe(self, image: np.ndarray, ts: Optional[float] = None) -> HealthReport:
  97. """分析一帧;``enabled=False`` 时只返回空报告(零开销)。"""
  98. ts_value = float(time.time() if ts is None else ts)
  99. if not self.p.enabled:
  100. self._last = HealthReport(ts=ts_value)
  101. return self._last
  102. if image is None or getattr(image, "size", 0) == 0:
  103. self._last = HealthReport(
  104. ts=ts_value,
  105. sensor_degraded=True,
  106. perception_uncertain=True,
  107. reasons=["no_image"],
  108. )
  109. return self._last
  110. gray = image
  111. if gray.ndim == 3:
  112. if cv2 is not None:
  113. gray = cv2.cvtColor(gray, cv2.COLOR_BGR2GRAY)
  114. else: # pragma: no cover - 无 OpenCV 时退化为亮度均值
  115. gray = gray[..., :3].mean(axis=2).astype(np.uint8)
  116. h, w = gray.shape[:2]
  117. scale = min(1.0, float(self.p.work_width) / float(max(1, w)))
  118. if cv2 is not None and scale < 1.0:
  119. gray = cv2.resize(
  120. gray, (int(round(w * scale)), int(round(h * scale))),
  121. interpolation=cv2.INTER_AREA,
  122. )
  123. blur_var = 0.0
  124. if cv2 is not None:
  125. blur_var = float(cv2.Laplacian(gray, cv2.CV_64F).var())
  126. total = float(max(1, gray.size))
  127. dark = float(np.count_nonzero(gray <= 5)) / total
  128. bright = float(np.count_nonzero(gray >= 250)) / total
  129. low_texture = self._low_texture_ratio(gray)
  130. motion_diff = self._motion_diff(gray)
  131. reasons: List[str] = []
  132. blur_bad = blur_var < self.p.blur_var_min and low_texture >= 0.65
  133. dark_bad = dark >= self.p.dark_clip_ratio_max and low_texture >= 0.80
  134. bright_bad = bright >= self.p.bright_clip_ratio_max and low_texture >= 0.80
  135. flat_bad = low_texture >= self.p.low_texture_ratio_max
  136. if blur_bad:
  137. reasons.append("blur")
  138. if dark_bad:
  139. reasons.append("dark_clip")
  140. if bright_bad:
  141. reasons.append("bright_clip")
  142. if flat_bad:
  143. reasons.append("low_texture")
  144. raw_bad = blur_bad or dark_bad or bright_bad or flat_bad
  145. # 迟滞:连续 raw_bad 超过 degrade_persist_s 才报退化;恢复也要
  146. # 连续正常 recover_persist_s,避免雨滴/飞虫造成逐帧抖动。
  147. if raw_bad:
  148. if self._bad_since is None:
  149. self._bad_since = ts_value
  150. self._good_since = None
  151. if ts_value - self._bad_since >= self.p.degrade_persist_s:
  152. self._degraded = True
  153. else:
  154. self._bad_since = None
  155. if self._good_since is None:
  156. self._good_since = ts_value
  157. if ts_value - self._good_since >= self.p.recover_persist_s:
  158. self._degraded = False
  159. self._last = HealthReport(
  160. ts=ts_value,
  161. sensor_degraded=bool(self._degraded),
  162. perception_uncertain=bool(self._degraded),
  163. blur_var=blur_var,
  164. dark_clip_ratio=dark,
  165. bright_clip_ratio=bright,
  166. low_texture_ratio=low_texture,
  167. motion_diff=motion_diff,
  168. reasons=reasons if self._degraded else [],
  169. )
  170. return self._last
  171. # ---------------------------------------------------------------- 内部
  172. @staticmethod
  173. def _low_texture_ratio(gray: np.ndarray) -> float:
  174. h, w = gray.shape[:2]
  175. block = 16
  176. if h < block or w < block:
  177. return 1.0 if float(np.std(gray)) < 3.5 else 0.0
  178. hh = (h // block) * block
  179. ww = (w // block) * block
  180. blocks = gray[:hh, :ww].reshape(hh // block, block, ww // block, block)
  181. stds = blocks.std(axis=(1, 3))
  182. return float(np.mean(stds < 3.5))
  183. def _motion_diff(self, gray: np.ndarray) -> float:
  184. thumb = gray
  185. if cv2 is not None:
  186. thumb = cv2.resize(gray, (160, 90), interpolation=cv2.INTER_AREA)
  187. if self._prev_thumb is None or self._prev_thumb.shape != thumb.shape:
  188. self._prev_thumb = thumb.astype(np.uint8, copy=True)
  189. return 0.0
  190. diff = float(
  191. np.abs(thumb.astype(np.float32) - self._prev_thumb.astype(np.float32)).mean()
  192. )
  193. self._prev_thumb = thumb.astype(np.uint8, copy=True)
  194. return diff if math.isfinite(diff) else 0.0