File size: 958 Bytes
2eba938
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""OpenCV image enhancement matching the browser pipeline."""
from __future__ import annotations

import cv2
import numpy as np


def enhance_bgr(image: np.ndarray) -> np.ndarray:
    """Apply exposure normalize, CLAHE on L channel, and mild sharpen."""
    lab = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)
    l, a, b = cv2.split(lab)

    mean_l = float(np.mean(l))
    if mean_l > 1:
        gain = np.clip(128.0 / mean_l, 0.7, 1.4)
        l = np.clip(l.astype(np.float32) * gain, 0, 255).astype(np.uint8)

    lo, hi = np.percentile(l, (2, 98))
    if hi > lo:
        l = np.clip((l.astype(np.float32) - lo) * (255.0 / (hi - lo)), 0, 255).astype(np.uint8)

    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
    l = clahe.apply(l)

    enhanced = cv2.cvtColor(cv2.merge([l, a, b]), cv2.COLOR_LAB2BGR)
    blurred = cv2.GaussianBlur(enhanced, (0, 0), 1.0)
    sharpened = cv2.addWeighted(enhanced, 1.35, blurred, -0.35, 0)
    return sharpened