Add margins to the image with Python, Pillow like enlarging the canvas
If you want to make an image an arbitrary size, but do not want to change the aspect ratio or trim it, adjust the size by adding margins to the top, bottom, left, and right of the image.
Perform a process similar to enlarging a canvas with image editing software.
This is realized by
paste() of the Python image processing library Polliw (PIL).
The following contents will be described.
- Add margins of any width vertically and horizontally
- Add margins to the rectangle to make it square
Please refer to the following post for the installation and basic usage of Pillow (PIL).
Please refer to the following post about trimming.
PIL and load the original image.
from PIL import Image im = Image.open('data/src/lena.jpg')
Add margins of any width vertically and horizontally
Generate a solid image with
new(), and paste the original image with
Define the following function.
def add_margin(pil_img, top, right, bottom, left, color): width, height = pil_img.size new_width = width + right + left new_height = height + top + bottom result = Image.new(pil_img.mode, (new_width, new_height), color) result.paste(pil_img, (left, top)) return result
Use as follows.
im_new = add_margin(im, 50, 10, 0, 100, (128, 0, 64)) im_new.save('data/dst/lena_add_margin.jpg', quality=95)
Add margins to the rectangle to make it square
Add a margin to the short side to make it square while maintaining the aspect ratio of the rectangular image.
Since it is troublesome to calculate and specify the width of the margins one by one, the following functions are newly defined.
def expand2square(pil_img, background_color): width, height = pil_img.size if width == height: return pil_img elif width > height: result = Image.new(pil_img.mode, (width, width), background_color) result.paste(pil_img, (0, (width - height) // 2)) return result else: result = Image.new(pil_img.mode, (height, height), background_color) result.paste(pil_img, ((height - width) // 2, 0)) return result
Use as follows.
im_new = expand2square(im, (0, 0, 0)) im_new.save('data/dst/lena_square.jpg', quality=95)
When you want to make a square of a certain size, such as making a thumbnail, add a margin and then
im_new = expand2square(im, (0, 0, 0)).resize((150, 150))
For more information about generating thumbnail images, see the following post: