""" Automatic Number Plate Recognition (ANPR) for Indian plates. Pipeline -------- 1. ``PlateDetector`` (YOLO) localises plates inside a vehicle crop. 2. ``PlateRecognizer`` (fast-plate-ocr CCT model, fine-tuned on Indian one- and two-line plates) outputs per-slot character probabilities. 3. ``decode_constrained`` (core.plate_format) picks the best legal Indian plate. 4. ``PlateVoter`` averages slot probabilities across video frames for a track, which is far more reliable than trusting any single frame. EasyOCR is kept only as a legacy baseline for benchmarking (tools/eval_ocr.py). """ from __future__ import annotations import logging import threading from dataclasses import dataclass, field from pathlib import Path from typing import Any import cv2 import numpy as np from core.plate_format import DecodeResult, decode_constrained, is_valid_indian_plate, repair_text LOGGER = logging.getLogger(__name__) PROJECT_ROOT = Path(__file__).resolve().parent.parent MODELS_DIR = PROJECT_ROOT / "models" DEFAULT_PLATE_MODEL_PATH = MODELS_DIR / "lp_best.pt" CUSTOM_OCR_ONNX = MODELS_DIR / "plate_ocr" / "india_plate_ocr.onnx" CUSTOM_OCR_CONFIG = MODELS_DIR / "plate_ocr" / "india_plate_config.yaml" HUB_OCR_MODEL = "cct-xs-v2-global-model" UNKNOWN_PLATE_TEXT = "MANUAL_REVIEW" OCR_CONFIDENCE_THRESHOLD = 0.45 _lock = threading.Lock() _plate_detectors: dict[str, Any] = {} _recognizer: "PlateRecognizer | None" = None _easyocr_reader = None # --------------------------------------------------------------------------- # Data classes # --------------------------------------------------------------------------- @dataclass class PlateText: text: str confidence: float valid_format: bool raw_text: str = "" probs: np.ndarray | None = None @property def accepted(self) -> bool: return self.text != UNKNOWN_PLATE_TEXT @dataclass class OCRResult: text: str confidence: float plate_detected: bool valid_format: bool = False plate_bbox: tuple[int, int, int, int] | None = None # in vehicle-crop coordinates plate_crop: np.ndarray | None = field(default=None, repr=False) probs: np.ndarray | None = field(default=None, repr=False) detector_confidence: float = 0.0 def to_dict(self) -> dict[str, Any]: return { "text": self.text, "confidence": round(float(self.confidence), 4), "plate_detected": self.plate_detected, "valid_format": self.valid_format, "plate_bbox": list(self.plate_bbox) if self.plate_bbox else None, } # --------------------------------------------------------------------------- # Plate detection # --------------------------------------------------------------------------- def _resolve(path: str | Path) -> Path: p = Path(path) if p.exists(): return p for candidate in (MODELS_DIR / p.name, PROJECT_ROOT / p.name): if candidate.exists(): return candidate return p def _load_plate_detector(model_path: str | Path = DEFAULT_PLATE_MODEL_PATH): from ultralytics import YOLO weights = _resolve(model_path) if not weights.exists(): raise FileNotFoundError(f"License plate detector weights not found: {weights}") key = str(weights.resolve()) with _lock: if key not in _plate_detectors: _plate_detectors[key] = YOLO(key) return _plate_detectors[key] def detect_plates( image: np.ndarray, model_path: str | Path = DEFAULT_PLATE_MODEL_PATH, confidence_threshold: float = 0.25, image_size: int = 640, device: Any = None, ) -> list[tuple[tuple[int, int, int, int], float]]: """Return [(x1, y1, x2, y2), conf] for plates in ``image`` sorted by confidence.""" if image is None or image.size == 0 or min(image.shape[:2]) < 16: return [] model = _load_plate_detector(model_path) kwargs: dict[str, Any] = {"conf": confidence_threshold, "imgsz": image_size, "verbose": False} if device is not None: kwargs["device"] = device result = model.predict(image, **kwargs)[0] boxes = getattr(result, "boxes", None) if boxes is None or len(boxes) == 0: return [] h, w = image.shape[:2] out = [] for (x1, y1, x2, y2), conf in zip(boxes.xyxy.cpu().numpy(), boxes.conf.cpu().numpy()): bw, bh = x2 - x1, y2 - y1 pad_x, pad_y = bw * 0.06, bh * 0.12 box = ( int(max(0, x1 - pad_x)), int(max(0, y1 - pad_y)), int(min(w, x2 + pad_x)), int(min(h, y2 + pad_y)), ) if box[2] - box[0] >= 8 and box[3] - box[1] >= 4: out.append((box, float(conf))) out.sort(key=lambda item: item[1], reverse=True) return out def extract_license_plate(vehicle_crop: np.ndarray, model_path: str | Path = DEFAULT_PLATE_MODEL_PATH, confidence_threshold: float = 0.25, image_size: int = 640) -> np.ndarray | None: """Backward-compatible helper returning the best plate crop or None.""" plates = detect_plates(vehicle_crop, model_path, confidence_threshold, image_size) if not plates: return None x1, y1, x2, y2 = plates[0][0] return vehicle_crop[y1:y2, x1:x2] # --------------------------------------------------------------------------- # Plate recognition # --------------------------------------------------------------------------- class PlateRecognizer: """Thin wrapper over fast-plate-ocr's ONNX model exposing raw slot probabilities.""" def __init__(self, onnx_path: Path | None = None, config_path: Path | None = None) -> None: from fast_plate_ocr import LicensePlateRecognizer if onnx_path is None and CUSTOM_OCR_ONNX.exists() and CUSTOM_OCR_CONFIG.exists(): onnx_path, config_path = CUSTOM_OCR_ONNX, CUSTOM_OCR_CONFIG if onnx_path is not None: self._model = LicensePlateRecognizer(onnx_model_path=onnx_path, plate_config_path=config_path, device="cpu") self.source = f"custom:{Path(onnx_path).name}" else: self._model = LicensePlateRecognizer(HUB_OCR_MODEL, device="cpu") self.source = f"hub:{HUB_OCR_MODEL}" cfg = self._model.config self.alphabet: str = cfg.alphabet self.pad_char: str = cfg.pad_char self.slots: int = cfg.max_plate_slots self.rgb: bool = cfg.image_color_mode == "rgb" def _prepare(self, crop: np.ndarray) -> np.ndarray: if crop.ndim == 2: return cv2.cvtColor(crop, cv2.COLOR_GRAY2RGB) if self.rgb else crop return cv2.cvtColor(crop, cv2.COLOR_BGR2RGB) if self.rgb else cv2.cvtColor(crop, cv2.COLOR_BGR2GRAY) def slot_probs(self, crops: list[np.ndarray]) -> np.ndarray: """Return (N, slots, alphabet) probabilities.""" from fast_plate_ocr.inference.plate_recognizer import _load_image_from_source from fast_plate_ocr.core.process import preprocess_image model = self._model x = _load_image_from_source([self._prepare(c) for c in crops], model.config) x = preprocess_image(x) out = model.model.run([model.plate_output_name], {"input": x})[0] return np.asarray(out, dtype=np.float32).reshape(len(crops), self.slots, len(self.alphabet)) def get_recognizer() -> PlateRecognizer: global _recognizer with _lock: if _recognizer is None: _recognizer = PlateRecognizer() LOGGER.info("Plate OCR backend: %s", _recognizer.source) return _recognizer def _tta_variants(crop: np.ndarray) -> list[np.ndarray]: """Original + contrast-normalised view; averaging both helps on hazy/night CCTV crops.""" gray = cv2.cvtColor(crop, cv2.COLOR_BGR2GRAY) if crop.ndim == 3 else crop clahe = cv2.createCLAHE(clipLimit=2.5, tileGridSize=(4, 4)).apply(gray) return [crop, cv2.cvtColor(clahe, cv2.COLOR_GRAY2BGR)] def plate_probs(plate_crop: np.ndarray, tta: bool = True) -> np.ndarray: rec = get_recognizer() variants = _tta_variants(plate_crop) if tta else [plate_crop] return rec.slot_probs(variants).mean(axis=0) def decode_probs(probs: np.ndarray, confidence_threshold: float = OCR_CONFIDENCE_THRESHOLD) -> PlateText: rec = get_recognizer() result: DecodeResult = decode_constrained(probs, rec.alphabet, rec.pad_char) accepted = result.valid and result.confidence >= confidence_threshold and len(result.text) >= 6 return PlateText( text=result.text if accepted else UNKNOWN_PLATE_TEXT, confidence=result.confidence, valid_format=result.valid, raw_text=result.text, probs=probs, ) def recognize_plate_text(plate_crop: np.ndarray, confidence_threshold: float = OCR_CONFIDENCE_THRESHOLD, tta: bool = True) -> PlateText: if plate_crop is None or plate_crop.size == 0 or min(plate_crop.shape[:2]) < 4: return PlateText(UNKNOWN_PLATE_TEXT, 0.0, False) try: probs = plate_probs(plate_crop, tta=tta) except Exception as exc: # pragma: no cover - runtime safety LOGGER.warning("Plate OCR failed: %s", exc) return PlateText(UNKNOWN_PLATE_TEXT, 0.0, False) return decode_probs(probs, confidence_threshold) def read_vehicle_license_plate( vehicle_crop: np.ndarray, model_path: str | Path = DEFAULT_PLATE_MODEL_PATH, plate_confidence_threshold: float = 0.25, ocr_confidence_threshold: float = OCR_CONFIDENCE_THRESHOLD, device: Any = None, ) -> OCRResult: """Localise the plate inside a vehicle crop and read it.""" if vehicle_crop is None or vehicle_crop.size == 0: return OCRResult(UNKNOWN_PLATE_TEXT, 0.0, False) plates = detect_plates(vehicle_crop, model_path, plate_confidence_threshold, device=device) if not plates: return OCRResult(UNKNOWN_PLATE_TEXT, 0.0, False) best: OCRResult | None = None for box, det_conf in plates[:2]: x1, y1, x2, y2 = box crop = vehicle_crop[y1:y2, x1:x2] reading = recognize_plate_text(crop, ocr_confidence_threshold) candidate = OCRResult( text=reading.text, confidence=reading.confidence, plate_detected=True, valid_format=reading.valid_format, plate_bbox=box, plate_crop=crop, probs=reading.probs, detector_confidence=det_conf, ) if best is None or (candidate.valid_format, candidate.confidence) > (best.valid_format, best.confidence): best = candidate return best # type: ignore[return-value] # --------------------------------------------------------------------------- # Multi-frame voting # --------------------------------------------------------------------------- class PlateVoter: """ Accumulates per-slot probabilities for one vehicle track across frames. Each observation is weighted by detector confidence and plate size (bigger, sharper plates are more trustworthy). The decoded text of the weighted mean is much more stable than any single-frame read. """ def __init__(self, max_observations: int = 12) -> None: self.max_observations = max_observations self._obs: list[tuple[float, np.ndarray]] = [] self.best_crop: np.ndarray | None = None self._best_crop_score = -1.0 def __len__(self) -> int: return len(self._obs) def add(self, result: OCRResult) -> None: if result.probs is None or result.plate_crop is None: return h, w = result.plate_crop.shape[:2] sharpness = float(cv2.Laplacian(cv2.cvtColor(result.plate_crop, cv2.COLOR_BGR2GRAY), cv2.CV_64F).var()) \ if result.plate_crop.ndim == 3 else 0.0 weight = max(result.detector_confidence, 0.1) * min(1.0, (w * h) / 4000.0) * (0.5 + result.confidence) self._obs.append((weight, result.probs)) self._obs.sort(key=lambda item: item[0], reverse=True) del self._obs[self.max_observations:] crop_score = weight * (1.0 + min(sharpness, 500.0) / 500.0) if crop_score > self._best_crop_score: self._best_crop_score = crop_score self.best_crop = result.plate_crop.copy() def result(self, confidence_threshold: float = OCR_CONFIDENCE_THRESHOLD) -> PlateText: if not self._obs: return PlateText(UNKNOWN_PLATE_TEXT, 0.0, False) weights = np.array([w for w, _ in self._obs]) stacked = np.stack([p for _, p in self._obs]) mean = (stacked * weights[:, None, None]).sum(axis=0) / weights.sum() return decode_probs(mean, confidence_threshold) # --------------------------------------------------------------------------- # Legacy EasyOCR baseline (benchmark only) # --------------------------------------------------------------------------- def recognize_plate_text_easyocr(plate_crop: np.ndarray) -> tuple[str, float]: global _easyocr_reader import easyocr if _easyocr_reader is None: _easyocr_reader = easyocr.Reader(["en"], gpu=False, verbose=False) up = cv2.resize(plate_crop, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC) results = _easyocr_reader.readtext(up, detail=1, allowlist="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") results = sorted(results, key=lambda r: (np.mean(np.asarray(r[0])[:, 1]) // max(1, up.shape[0] / 3), np.mean(np.asarray(r[0])[:, 0]))) text = "".join(r[1] for r in results).upper() conf = float(np.mean([r[2] for r in results])) if results else 0.0 return repair_text(text), conf __all__ = [ "OCRResult", "PlateText", "PlateVoter", "PlateRecognizer", "UNKNOWN_PLATE_TEXT", "detect_plates", "extract_license_plate", "recognize_plate_text", "read_vehicle_license_plate", "is_valid_indian_plate", ]