File size: 2,023 Bytes
7ab08b3
d8334ba
a696cf3
d8334ba
 
a696cf3
24d3175
d8334ba
a696cf3
d8334ba
24d3175
 
 
 
 
 
 
 
d8334ba
 
 
a848267
d8334ba
 
 
b9f1947
 
 
 
 
 
 
 
 
 
 
 
d8334ba
b9f1947
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8334ba
 
 
 
 
 
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
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)