import cv2 import numpy as np def detect_brightness(img): """ Detects the average brightness of an image. Returns: Average pixel value (0-255). """ if len(img.shape) == 3: gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) else: gray = img return np.mean(gray) def apply_gamma_correction(img, gamma=1.0): """ Applies gamma correction to improve intensity. """ invGamma = 1.0 / gamma table = np.array([((i / 255.0) ** invGamma) * 255 for i in np.arange(256)]).astype("uint8") return cv2.LUT(img, table) def apply_clahe(img, clip_limit=2.0, tile_grid_size=(8, 8)): """ Contrast Limited Adaptive Histogram Equalization. """ lab = cv2.cvtColor(img, cv2.COLOR_RGB2LAB) l, a, b = cv2.split(lab) clahe = cv2.createCLAHE(clipLimit=clip_limit, tileGridSize=tile_grid_size) cl = clahe.apply(l) limg = cv2.merge((cl, a, b)) return cv2.cvtColor(limg, cv2.COLOR_LAB2RGB) def apply_denoising(img, h=10): """ Non-local Means Denoising. """ return cv2.fastNlMeansDenoisingColored(img, None, h, h, 7, 21) def apply_sharpening(img): """ Laplacian-based sharpening. """ kernel = np.array([[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]]) return cv2.filter2D(img, -1, kernel) def enhancement_pipeline(img, config): """ Full sequential enhancement pipeline. """ processed = img.copy() if config.get('gamma_enable', True): processed = apply_gamma_correction(processed, config.get('gamma', 1.5)) if config.get('clahe_enable', True): processed = apply_clahe(processed, config.get('clahe_clip', 3.0)) if config.get('denoise_enable', True): processed = apply_denoising(processed, config.get('denoise_h', 10)) if config.get('sharpen_enable', True): processed = apply_sharpening(processed) return processed