Last active
May 15, 2022 12:26
-
-
Save devbruce/140b6d697bea18950995a249229e214b to your computer and use it in GitHub Desktop.
Image Letterboxing (or Pillarboxing)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
import numpy as np | |
__all__ = ['letterbox'] | |
def letterbox(img_arr, target_size, boxes=None): | |
"""Image Letterboxing (or Pillarboxing) | |
Args: | |
img_arr (np.ndarray dtype=uint8) | |
target_size (tuple): (height: int, width: int) | |
boxes (np.ndarray dtype=np.int32): shape (n, 4) --> [x_min, y_min, x_max, y_max] | |
""" | |
img_arr = img_arr.copy() | |
if boxes: | |
boxes = boxes.copy() | |
input_height, input_width = img_arr.shape[:2] | |
target_height, target_width = target_size | |
scale = min(target_width / input_width, target_height / input_height) | |
resized_width, resized_height = int(scale * input_width), int(scale * input_height) | |
img_resized = cv2.resize(img_arr, dsize=(resized_width, resized_height)) | |
half_pad_width, half_pad_height = (target_width - resized_width) // 2, (target_height - resized_height) // 2 | |
img_padded = np.zeros(shape=(target_height, target_width, 3), dtype=np.uint8) | |
img_padded[half_pad_height:half_pad_height+resized_height, half_pad_width:half_pad_width+resized_width, :] = img_resized | |
if not boxes: | |
return img_padded | |
else: | |
boxes[:, [0, 2]] = boxes[:, [0, 2]] * scale + half_pad_width | |
boxes[:, [1, 3]] = boxes[:, [1, 3]] * scale + half_pad_height | |
return img_padded, boxes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment