# Compute mean and std from the TRAINING set only — never from validation or test def compute_train_stats(train_dir, sample_limit=1000): """Compute pixel mean and std across the training set.""" pixel_values = [] count = 0 for class_name in os.listdir(train_dir): class_path = os.path.join(train_dir, class_name) for fname in os.listdir(class_path): if count >= sample_limit: break img = cv2.imread(os.path.join(class_path, fname), cv2.IMREAD_GRAYSCALE) if img is not None: pixel_values.append(img.astype(np.float32).flatten() / 255.0) count += 1 pixels = np.concatenate(pixel_values) return pixels.mean(), pixels.std() train_mean, train_std = compute_train_stats(TRAIN_DIR) image_normalized = (image_scaled - train_mean) / train_std