pipecountapp-dev / scripts /image_enhance.py
Khunndev
Support image enhancement, outlier filtering, and adaptive multi-tile detection
2eba938
Raw History Blame Contribute Delete
958 Bytes
"""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