Created
October 12, 2021 02:54
-
-
Save InputBlackBoxOutput/147edbd8c9caedabdc04e3b8ef5344af to your computer and use it in GitHub Desktop.
Resize an image to a square image with the help of minimal padding
This file contains hidden or 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
from PIL import Image | |
def resize_image(img_path, desired_size = 300, background_color=None): | |
img = Image.open(img_path) | |
old_size = img.size | |
if background_color == None: | |
background_color = img.load()[0,0] | |
ratio = float(desired_size-10)/max(old_size) | |
new_size = tuple([int(x*ratio) for x in old_size]) | |
img = img.resize(new_size, Image.ANTIALIAS) | |
output = Image.new("RGB", (desired_size, desired_size), color=background_color) | |
output.paste(img, ((desired_size-new_size[0])//2, (desired_size-new_size[1])//2)) | |
return output | |
if __name__ == '__main__': | |
img = resize_image("image.png", background_color=(255, 255, 255)) | |
img.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment