|
a |
|
b/utils/preprocessing.py |
|
|
1 |
import cv2 |
|
|
2 |
import numpy as np |
|
|
3 |
|
|
|
4 |
def preprocess_image(image_path, target_size=(256, 256)): |
|
|
5 |
""" |
|
|
6 |
Load and preprocess the image for model prediction. |
|
|
7 |
|
|
|
8 |
Args: |
|
|
9 |
image_path (str): Path to input X-ray image. |
|
|
10 |
target_size (tuple): Size expected by the model. |
|
|
11 |
|
|
|
12 |
Returns: |
|
|
13 |
preprocessed_img (np.array): Preprocessed image tensor (1, H, W, C) |
|
|
14 |
original_img (np.array): Original image for display or saving |
|
|
15 |
""" |
|
|
16 |
# Load image in grayscale (you can also use RGB if model was trained in RGB) |
|
|
17 |
img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE) |
|
|
18 |
original_img = img.copy() |
|
|
19 |
|
|
|
20 |
# Resize to target shape |
|
|
21 |
img = cv2.resize(img, target_size) |
|
|
22 |
|
|
|
23 |
# Normalize to [0, 1] |
|
|
24 |
img = img / 255.0 |
|
|
25 |
|
|
|
26 |
# Expand dimensions to match model input shape (1, H, W, 1) |
|
|
27 |
img = np.expand_dims(img, axis=-1) |
|
|
28 |
img = np.expand_dims(img, axis=0) |
|
|
29 |
|
|
|
30 |
return img, original_img |