l have a set of images of different sizes (45,50,3), (69,34,3), (34,98,3)
. l want to add padding to these images as follows:
Take the max width and leng
Here is a function doing all for you :
import cv2
def pad_images_to_same_size(images):
"""
:param images: sequence of images
:return: list of images padded so that all images have same width and height (max width and height are used)
"""
width_max = 0
height_max = 0
for img in images:
h, w = img.shape[:2]
width_max = max(width_max, w)
height_max = max(height_max, h)
images_padded = []
for img in images:
h, w = img.shape[:2]
diff_vert = height_max - h
pad_top = diff_vert//2
pad_bottom = diff_vert - pad_top
diff_hori = width_max - w
pad_left = diff_hori//2
pad_right = diff_hori - pad_left
img_padded = cv2.copyMakeBorder(img, pad_top, pad_bottom, pad_left, pad_right, cv2.BORDER_CONSTANT, value=0)
assert img_padded.shape[:2] == (height_max, width_max)
images_padded.append(img_padded)
return images_padded