Spaces:
Sleeping

File size: 2,764 Bytes
6aee097
 
 
 
 
 
 
 
 
 
29088fd
6aee097
 
 
 
 
 
 
 
 
 
 
 
 
29088fd
 
6aee097
29088fd
 
 
 
6aee097
 
 
29088fd
6aee097
29088fd
 
 
 
 
 
 
 
 
 
 
6aee097
 
 
 
29088fd
6aee097
29088fd
 
 
6aee097
 
 
 
 
29088fd
6aee097
29088fd
6aee097
29088fd
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
from __future__ import annotations

from typing import Literal

import cv2
import numpy as np

PreprocessMode = Literal["auto", "clahe", "denoise", "none"]

LOW_LIGHT_THRESHOLD = 80.0
LOW_CONTRAST_STD = 28.0


def _validate_frame(frame: np.ndarray) -> None:
    if frame is None:
        raise ValueError("frame must not be None")
    if not isinstance(frame, np.ndarray):
        raise TypeError("frame must be a numpy.ndarray")
    if frame.ndim != 3 or frame.shape[2] != 3:
        raise ValueError("frame must be a BGR image with shape (height, width, 3)")
    if frame.size == 0:
        raise ValueError("frame must not be empty")


def enhance_low_light_clahe(frame: np.ndarray, clip_limit: float = 2.0) -> np.ndarray:
    """CLAHE on the LAB luminance channel (keeps colours, which the signal classifier needs)."""
    _validate_frame(frame)
    lab = cv2.cvtColor(frame, cv2.COLOR_BGR2LAB)
    l_channel, a_channel, b_channel = cv2.split(lab)
    l_channel = cv2.createCLAHE(clipLimit=clip_limit, tileGridSize=(8, 8)).apply(l_channel)
    return cv2.cvtColor(cv2.merge((l_channel, a_channel, b_channel)), cv2.COLOR_LAB2BGR)


def reduce_blur_and_noise(frame: np.ndarray) -> np.ndarray:
    """Edge-preserving denoise for rain / sensor noise (slow on 1080p: use only when needed)."""
    _validate_frame(frame)
    return cv2.bilateralFilter(frame, d=7, sigmaColor=50, sigmaSpace=50)


def frame_quality(frame: np.ndarray) -> dict[str, float]:
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    small = cv2.resize(gray, (320, int(320 * gray.shape[0] / max(gray.shape[1], 1))))
    return {
        "brightness": float(small.mean()),
        "contrast": float(small.std()),
        "sharpness": float(cv2.Laplacian(small, cv2.CV_64F).var()),
    }


def preprocess_frame(frame: np.ndarray, mode: PreprocessMode = "auto") -> np.ndarray:
    """
    Normalise a BGR frame for detection.

    auto: CLAHE only when the frame is dark (night) or flat (haze / rain / glare);
          otherwise the frame is returned unchanged. Denoising is not applied in
          auto mode because it smears number plates and costs ~40 ms per 1080p frame.
    """
    _validate_frame(frame)
    if mode not in {"auto", "clahe", "denoise", "none"}:
        raise ValueError("mode must be one of: 'auto', 'clahe', 'denoise', 'none'")
    if mode == "none":
        return frame
    if mode == "clahe":
        return enhance_low_light_clahe(frame)
    if mode == "denoise":
        return reduce_blur_and_noise(frame)
    q = frame_quality(frame)
    if q["brightness"] < LOW_LIGHT_THRESHOLD:
        return enhance_low_light_clahe(frame, clip_limit=3.0)
    if q["contrast"] < LOW_CONTRAST_STD:
        return enhance_low_light_clahe(frame, clip_limit=2.0)
    return frame