How to batch concatenate images in Python?

In Python, you can use the Python Imaging Library (PIL) library for image processing and stitching. Here is a method for batch stitching images.

from PIL import Image
import os

def join_images(input_folder, output_file):
    images = []
    for filename in os.listdir(input_folder):
        if filename.endswith(".jpg") or filename.endswith(".png"):
            images.append(Image.open(os.path.join(input_folder, filename)))

    widths, heights = zip(*(i.size for i in images))

    total_width = sum(widths)
    max_height = max(heights)

    new_image = Image.new('RGB', (total_width, max_height))

    x_offset = 0
    for image in images:
        new_image.paste(image, (x_offset, 0))
        x_offset += image.width

    new_image.save(output_file)

# 使用示例
input_folder = "path/to/input/folder/"
output_file = "path/to/output/file.jpg"
join_images(input_folder, output_file)

Please replace input_folder with the path to the folder containing the images to be stitched together, and replace output_file with the file path for the output stitched image. When the function is run, all the images in the folder will be stitched together horizontally and saved as the specified output file.

bannerAds