Spaces:
Sleeping
Sleeping
Download image_preprocessor.py from DerradjAdel/Lifeline_labs_AI: direct link, hf CLI and curl.
- Browser
- Download file 2.02 kB
-
https://huggingface.co/spaces/DerradjAdel/Lifeline_labs_AI/resolve/main/image_preprocessor.py
- Command line
-
hf download hf://spaces/DerradjAdel/Lifeline_labs_AI/image_preprocessor.py
-
curl -L -o image_preprocessor.py https://huggingface.co/spaces/DerradjAdel/Lifeline_labs_AI/resolve/main/image_preprocessor.py
2.02 kB
| import io | |
| import numpy as np | |
| from PIL import Image | |
| from tensorflow.keras.preprocessing.image import ImageDataGenerator | |
| # Adjust target size to match your 3-class model input (224×224) | |
| TARGET_SIZE = (299, 299) | |
| # Optional augmentation setup | |
| augmenter = ImageDataGenerator( | |
| rescale=1./255, | |
| rotation_range=10, | |
| width_shift_range=0.01, | |
| height_shift_range=0.01, | |
| zoom_range=0.01, | |
| shear_range=0.01, | |
| brightness_range=[0.9, 1.5], # simulate X-ray exposure differences | |
| fill_mode='constant' | |
| ) | |
| def load_and_resize(image_bytes, target_size=TARGET_SIZE): | |
| img = Image.open(io.BytesIO(image_bytes)).convert("L") | |
| return img.resize(target_size) | |
| def augment_image(img: Image.Image): | |
| """ | |
| Apply a random augmentation to the given PIL Image. | |
| Returns a new PIL Image (grayscale). | |
| """ | |
| # Convert PIL image to array (height, width) | |
| arr = np.array(img) | |
| # Add channel dimension: (height, width) -> (height, width, 1) | |
| arr = np.expand_dims(arr, axis=-1) | |
| # Add batch dimension: (height, width, 1) -> (1, height, width, 1) | |
| batch = np.expand_dims(arr, axis=0) | |
| # Apply augmentation: output shape is (1, height, width, 1) | |
| transformed = next(augmenter.flow(batch, batch_size=1)) | |
| # Remove batch dim: (1, h, w, 1) -> (h, w, 1) | |
| arr_aug = transformed[0] | |
| # Convert back to 2D grayscale by squeezing channel | |
| arr_aug = np.clip(arr_aug * 255, 0, 255).astype('uint8').squeeze(-1) | |
| return Image.fromarray(arr_aug, mode='L') | |
| def to_array(img: Image.Image): | |
| """ | |
| Convert PIL Image to normalized NumPy array suitable for model input. | |
| Output shape: (1, height, width, 1) | |
| """ | |
| arr = np.array(img).astype('float32') / 255.0 # (h, w) | |
| # Add channel and batch dims | |
| arr = np.expand_dims(arr, axis=-1) # (h, w, 1) | |
| return np.expand_dims(arr, axis=0) # (1, h, w, 1) | |
| def preprocess_for_model(image_bytes, augment=False): | |
| img = load_and_resize(image_bytes) | |
| if augment: | |
| img = augment_image(img) | |
| return to_array(img) | |