How to batch stitch images using Python?
To batch merge images using Python, you can utilize the PIL (Python Imaging Library) library. Here is a simple example code:
from PIL import Image
def concatenate_images(image_list, output_path):
"""拼接图片"""
# 获取第一张图片的宽度和高度
width, height = image_list[0].size
# 创建一个新的图像对象,宽度为所有图片的总宽度,高度为第一张图片的高度
concatenated_image = Image.new('RGB', (width * len(image_list), height))
# 拼接图片
x_offset = 0
for image in image_list:
concatenated_image.paste(image, (x_offset, 0))
x_offset += image.width
# 保存拼接后的图片
concatenated_image.save(output_path)
# 读取需要拼接的图片
image1 = Image.open("image1.jpg")
image2 = Image.open("image2.jpg")
image3 = Image.open("image3.jpg")
# 拼接图片
concatenate_images([image1, image2, image3], "concatenated_image.jpg")
In this example, we first import the Image class and the concatenate_images function. The concatenate_images function takes a list of image objects that need to be concatenated and an output path as parameters. The function first gets the width and height of the first image, then creates a new image object with a width equal to the total width of all images and a height equal to the height of the first image. It then pastes each image in the list onto the new image object in the correct position using the paste method. Finally, it saves the concatenated image to the specified output path using the save method.
Simply replace the image paths in the sample code with your own image paths, and then run the code to batch stitch the images.