Spaces:
Sleeping
Sleeping
| from PIL import Image | |
| import numpy as np | |
| def center_crop(image: Image.Image, frac: float = 0.7): | |
| # crop so that 70% of the image is used | |
| w, h = image.size | |
| side = int(min(w, h) * frac) | |
| side = max(1, min(side, min(w, h))) | |
| cx = w // 2 | |
| cy = h // 2 | |
| left = cx - side // 2 | |
| upper = cy - side // 2 | |
| right = left + side | |
| lower = upper + side | |
| img = image.crop((left, upper, right, lower)) | |
| return img | |
| def preprocess_image(image: Image.Image, img_size: int = 224, fraction: float = 0.7): | |
| image = center_crop(image, frac=fraction) | |
| image = image.resize((img_size, img_size), Image.BILINEAR) | |
| arr = np.array(image).astype("float32") / 255.0 | |
| mean = np.array([0.485, 0.456, 0.406], dtype="float32") | |
| std = np.array([0.229, 0.224, 0.225], dtype="float32") | |
| arr = (arr - mean) / std | |
| arr = np.transpose(arr, (2, 0, 1)) | |
| arr = np.expand_dims(arr, axis=0) | |
| return arr | |