Python Pillow merge images
Merging Images with Python Pillow
The Pillow package allows you to paste one image onto another. The merge() function takes a mode and an image tuple as arguments and merges them into a single image.
Syntax
Image.merge(mode, bands)
Where:
- mode – The mode to use for the output image.
-
bands – A sequence containing a single-band image for each band in the output image. All bands must have the same size.
-
Return Value – An image object.
Using the merge() function, you can merge the RGB bands of an image into:
from PIL import Image
image = Image.open("beach1.jpg")
r, g, b = image.split()
image.show()
image = Image.merge("RGB", (b, g, r))
image.show()
When you execute the above code, you can see the original image and the image with the merged RGB bands, as shown below.
Input Image
Output Image
Merging Two Images
In the same way, to merge two different images, you need
- Create an image object for the desired image using the open() function.
-
When merging two images, you need to ensure that the dimensions of both images are the same. Therefore, obtain the dimensions of each image and, if necessary, adjust them accordingly.
-
Use the Image.new() function to create an empty image.
-
Use the paste() function to paste the image.
-
Use the save() and show() functions to save and display the resulting image.
Example
The following example demonstrates merging two images using python pillow
from PIL import Image
#Read the two images
image1 = Image.open('images/elephant.jpg')
image1.show()
image2 = Image.open('images/ladakh.jpg')
image2.show()
#resize, first image
image1 = image1.resize((426, 240))
image1_size = image1.size
image2_size = image2.size
new_image = Image.new('RGB',(2*image1_size[0], image1_size[1]), (250,250,250))
new_image.paste(image1,(0,0))
new_image.paste(image2,(image1_size[0],0))
new_image.save("images/merged_image.jpg","JPEG")
new_image.show()
Output
If you save the above program as Example.py and execute it, it will display the two input images and the merged image using standard PNG display tools, as shown below.
Input Image 1
Input Image 2
Merged Image