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
| import cv2 import numpy as np
class CLAHEPreprocessor: """ CLAHE (Contrast Limited Adaptive Histogram Equalization) 自适应预处理:跨相机光照归一化 解决问题: - 不同 DMS 摄像头光照条件不一致 - 夜间/隧道/逆光导致精度下降 - 跨数据集迁移困难 """ def __init__(self, clip_limit=2.0, grid_size=(8, 8)): self.clahe = cv2.createCLAHE( clipLimit=clip_limit, tileGridSize=grid_size ) def process(self, image: np.ndarray) -> np.ndarray: """ CLAHE 预处理 Args: image: BGR 图像 (H, W, 3) Returns: processed: 预处理后图像 """ lab = cv2.cvtColor(image, cv2.COLOR_BGR2LAB) lab[:, :, 0] = self.clahe.apply(lab[:, :, 0]) return cv2.cvtColor(lab, cv2.COLOR_LAB2BGR) def process_iris(self, image, eye_region): """对眼部区域增强(疲劳检测关键区域)""" x, y, w, h = eye_region eye = image[y:y+h, x:x+w] eye_clahe = self.process(eye) eye_gray = cv2.cvtColor(eye_clahe, cv2.COLOR_BGR2GRAY) eye_clahe2 = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(4, 4)) eye_enhanced = eye_clahe2.apply(eye_gray) return eye_enhanced
if __name__ == "__main__": preprocessor = CLAHEPreprocessor() for condition in ['bright', 'normal', 'dim', 'night_ir']: image = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8) if condition == 'dim': image = (image * 0.3).astype(np.uint8) elif condition == 'night_ir': image = np.repeat(image[:, :, 0:1], 3, axis=2) processed = preprocessor.process(image) print(f"{condition}: 原始均值={image.mean():.0f} → 处理后={processed.mean():.0f}")
|