Add Padding to images

I have a dataset of variable sized images and so want to add Padding to maintain a constant size. How can I do so across the dataset?

Do you need to necessarily pad the images. If you want to make all the data in same size you can use image resizing.
For doing this all you need to do is create custom data loader and resize the loaded image and return as input.

Yeah, I think padding would work the best for my work. Is there a way?

In your customized data loader write the function -

def padding(img,expected_size):
    desired_size = expected_size
    delta_width = desired_size - img.size[0]
    delta_height = desired_size - img.size[1]
    pad_width = delta_width //2
    pad_height = delta_height //2
    padding = (pad_width,pad_height,delta_width-pad_width,delta_height-pad_height)
    return ImageOps.expand(img, padding)

1 Like