Add padding to images to get them into the same shape

前端 未结 6 1749
野趣味
野趣味 2020-12-31 04:21

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

6条回答
  •  甜味超标
    2020-12-31 04:41

    try to use this function:

    from PIL import Image, ImageOps
    
    
    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)
    
    
    def resize_with_padding(img, expected_size):
        img.thumbnail((expected_size[0], expected_size[1]))
        # print(img.size)
        delta_width = expected_size[0] - img.size[0]
        delta_height = expected_size[1] - 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)
    
    
    if __name__ == "__main__":
        img = Image.open("./demo.jpg")
        print(img)
        img = resize_with_padding(img, (500, 400))
        print(img.size)
        img.show()
        img.save("resized_img.jpg")
    

    raw image

    after resizing with padding

    see https://gist.github.com/BIGBALLON/cb6ab73f6aaaa068ab6756611bb324b2

提交回复
热议问题