from PIL import Image
import os
import pdb
def merge_images_with_same_name(folder_paths, output_folder):
    # Get the list of filenames in the first folder
    os.makedirs(output_folder,exist_ok=True)
    filenames = sorted(os.listdir(folder_paths[0]))
    num = 0
    for filename in filenames:
        images = []
        for i,folder_path in enumerate(folder_paths):
            file_path = os.path.join(folder_path, filename)
            #pdb.set_trace()
            if os.path.isfile(file_path):
                image = Image.open(file_path)
                if i == 0:
                    w,h = image.size
                else:
                    image = image.resize((w,h))
                images.append(image)
            else:
                print(file_path)
                continue

        # Create a new blank image to merge the others into
        total_width = sum(image.width for image in images)
        max_height = max(image.height for image in images)
        merged_image = Image.new("RGB", (total_width, max_height))

        # Paste each image into the merged image
        current_width = 0
        for image in images:
            merged_image.paste(image, (current_width, 0))
            current_width += image.width

        # Save the merged image
        output_path = os.path.join(output_folder, f"{filename}")
        merged_image.save(output_path)
        num += 1
        print(num)

if __name__ == "__main__":
    # Provide the paths to the folders
    folders = [
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "G",
        "H"
    ]

    output_folder = "./cmp_images/"
    

    merge_images_with_same_name(folders, output_folder)
