Source code for blocks.utils.image

import numpy as np
import cv2


[docs]def resize_and_pad(image: np.ndarray, target_width: int, target_height: int, upscale: bool = True) -> np.ndarray: """ Resize and pad (with zeros) the given image to the target width and height. :param image: input image :param target_width: target width :param target_height: target height :param upscale: upscale the image if it is smaller in both dimensions :return: resized and padded image """ scale_y = image.shape[0] / target_height scale_x = image.shape[1] / target_width scale = 1 / max(scale_y, scale_x) if scale_x < 1 and scale_y < 1 and not upscale: scale = 1 resized_image = cv2.resize(image, None, fx=scale, fy=scale) output_image = np.zeros((target_height, target_width, 3), dtype=np.uint8) pad_y = (output_image.shape[0] - resized_image.shape[0])//2 pad_x = (output_image.shape[1] - resized_image.shape[1])//2 output_image[pad_y:(pad_y+resized_image.shape[0]), pad_x:(pad_x+resized_image.shape[1])] = resized_image return output_image