How to merge images with same size using the Python 3 module pillow?
In this article, the task is to merge image with size using the module pillow in python 3.
Python 3 module pillow :
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
This is the update of Python Imaging Library. It is a free and open-source additional library for the Python programming language that adds support for opening, manipulating, and saving many various image file formats. To merge images with same size we can use pillow. Really it was cool and very interesting Library.
Before we go and code let’s save 4 images into your local computer.
Right-click on above images and save image to local computer .
Using google colaboratory to code as it is easy to code, and we don’t need to install pillow separately. If you want to install pillow in local computer you can use the link https://pypi.org/project/Pillow/
In google colaboratory you can add jpg using + symbol as shown. Below.
After uploading images to google ,lets start coding.first import the Image.
from PIL import Image
Open image using pillow
img_01 = Image.open("digit-number-img-0.jpg") img_02 = Image.open("digit-number-img-1.jpg") img_03 = Image.open("digit-number-img-2.jpg") img_04 = Image.open("digit-number-img-3.jpg")
Get image size.
img_01_size = img_01.size img_02_size = img_02.size img_03_size = img_02.size img_02_size = img_02.size print('img 1 size: ', img_01_size) print('img 2 size: ', img_02_size) print('img 3 size: ', img_03_size) print('img 4 size: ', img_03_size)
Create an empty white image:
new_im = Image.new('RGB', (2*img_01_size,2*img_01_size), (250,250,250))
new_im.paste(img_01, (0,0)) new_im.paste(img_02, (img_01_size,0)) new_im.paste(img_03, (0,img_01_size)) new_im.paste(img_04, (img_01_size,img_01_size))
Save new image.
new_im.save("merged_images.png", "PNG") new_im.show()