Team Ai
Apppublic

Estherdev-code/breast-cancer-detection

sourceHugging Faceapache-2.0updated 5mo agoView on Hugging Face
0likes
preprocess.py66 linesDownload Raw Back to root
1"""2preprocess.py3-------------4Stage 1: Image Intelligence Layer5CLAHE preprocessing pipeline matching the trained ResNet50 model.6"""7 8import cv29import numpy as np10from tensorflow.keras.applications.resnet50 import preprocess_input11 12 13def load_image(image_path):14    """Load a mammogram image in grayscale."""15    image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)16    if image is None:17        raise ValueError(f"Could not load image at: {image_path}")18    return image19 20 21def denoise(image):22    """Apply Gaussian blur to suppress random noise."""23    return cv2.GaussianBlur(image, (3, 3), 0)24 25 26def apply_clahe(image):27    """Contrast Limited Adaptive Histogram Equalization."""28    clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8, 8))29    return clahe.apply(image)30 31 32def resize(image, target_size=(224, 224)):33    """Resize to ResNet50 input size."""34    return cv2.resize(image, target_size, interpolation=cv2.INTER_LINEAR)35 36 37def convert_to_rgb(image):38    """Convert grayscale to 3-channel RGB."""39    return cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)40 41 42def preprocess(image_path):43    """Full preprocessing pipeline for a file path."""44    image = load_image(image_path)45    image = denoise(image)46    image = apply_clahe(image)47    image = resize(image)48    image = convert_to_rgb(image)49    return image50 51 52def preprocess_from_array(image_array):53    """Same pipeline but for an already-loaded numpy array."""54    image = denoise(image_array)55    image = apply_clahe(image)56    image = resize(image)57    image = convert_to_rgb(image)58    return image59 60 61def prepare_for_model(image):62    """Apply ResNet50-specific normalization."""63    image = image.astype("float32")64    image = np.expand_dims(image, axis=0)65    image = preprocess_input(image)66    return image