| import numpy as np | |
| from PIL import Image | |
| def preprocess(image_path, input_size=(224, 224)): | |
| """Load and preprocess image for ResNet50.""" | |
| img = Image.open(image_path).convert('RGB') | |
| img = img.resize(input_size, Image.BICUBIC) | |
| img_array = np.array(img, dtype=np.float32) | |
| # ImageNet normalization: (img/255 - mean) / std | |
| mean = np.array([0.485, 0.456, 0.406], dtype=np.float32) | |
| std = np.array([0.229, 0.224, 0.225], dtype=np.float32) | |
| img_array = img_array / 255.0 | |
| img_array = (img_array - mean) / std | |
| # HWC -> CHW -> NCHW | |
| img_array = img_array.transpose(2, 0, 1) | |
| img_array = np.expand_dims(img_array, axis=0) | |
| return img_array.astype(np.float32) | |