from PIL import Image import numpy as np import cv2 def load_image(image_path, grayscale=False): img = Image.open(image_path) if grayscale: img = img.convert('L') return np.array(img) def pad_image_and_resize(img_array, target_size): h, w = img_array.shape[:2] max_side = max(h, w) delta_w = max_side - w delta_h = max_side - h top, bottom = delta_h // 2, delta_h - delta_h // 2 left, right = delta_w // 2, delta_w - delta_w // 2 # If the image has more than 2 dimensions (e.g., color images), pad the last dimension with (0,0) if img_array.ndim == 2: pad_width = ((top, bottom), (left, right)) else: pad_width = ((top, bottom), (left, right), (0, 0)) img_padded = np.pad(img_array, pad_width, mode='constant', constant_values=0) img_resized = cv2.resize(img_padded, (target_size, target_size), interpolation=cv2.INTER_AREA) return img_resized def tile_and_stack(image, num_tiles_per_side): tile_size = image.shape[0] // num_tiles_per_side tiles = [] for i in range(num_tiles_per_side): for j in range(num_tiles_per_side): tile = image[ i * tile_size:(i + 1) * tile_size, j * tile_size:(j + 1) * tile_size ] tiles.append(tile) stacked_image = np.stack(tiles, axis=0) # For grayscale: (num_tiles, tile_size, tile_size) return stacked_image