"""Canonical proxy-v4 stretch160 preprocessing.""" import hashlib import numpy as np from PIL import Image def preprocess_u8(image_u8: np.ndarray) -> np.ndarray: """Return the canonical uint8 160x160 image before /255 and RGB replication.""" pixels = np.asarray(image_u8) if pixels.dtype != np.uint8 or pixels.ndim != 2 or pixels.size == 0: raise ValueError("source image must be a nonempty 2-D uint8 grayscale array") stretched = pixels.astype(np.float32) active = stretched[stretched > 10] if active.size > 50: low, high = np.percentile(active, [2, 99.5]) stretched = np.clip((stretched - low) / max(high - low, 1e-6), 0, 1) else: stretched = stretched / 255.0 resized = Image.fromarray((stretched * 255).astype(np.uint8)).resize( (160, 160), Image.Resampling.BILINEAR ) return np.asarray(resized, dtype=np.uint8).copy() def tensor_sha256(prepared_u8: np.ndarray) -> str: """Hash the contiguous float32 RGB tensor consumed by ResNet18.""" pixels = np.asarray(prepared_u8) if pixels.dtype != np.uint8 or pixels.shape != (160, 160): raise ValueError("prepared image must be uint8[160,160]") tensor = np.repeat((pixels.astype(np.float32) / 255.0)[None], 3, axis=0) return hashlib.sha256(np.ascontiguousarray(tensor).tobytes()).hexdigest()