合并许多图像相同的文件名从许多不同的文件夹在一个批处理与python [已关闭]

uklbhaso  于 2023-03-06  发布在  Python
关注(0)|答案(1)|浏览(87)
    • 已关闭**。此问题需要超过focused。当前不接受答案。
    • 想要改进此问题吗?**更新此问题,使其仅关注editing this post的一个问题。

20小时前关门了。
Improve this question
我试图从4个不同的文件夹中一个接一个地组合所有图像,例如,我有这4个文件夹:

  • 文件夹1:a_1.png、a_2.png、a_3.png
  • 文件夹2:a_1.png、a_3.png、a_5.png
  • 文件夹3:a_1.png、a_6.png、a_3.png
  • folder4:a_2.png,a_6.png,a_5.png我想做的是合并:
  • a_1.png位于文件夹1中,a_1.png位于文件夹2中,a_1.png位于文件夹3中
  • 文件夹1中的a_2.png和文件夹4中的a_2.png
  • 文件夹1中的a_3.png和文件夹2中的a_3.png .....

我也没什么好办法,你帮我解决吧

lp0sw83n

lp0sw83n1#

我想你说的“结合两幅图像”,是指把它们连接起来,就像把它们缝合成一幅

from pathlib import Path
from PIL import Image

src_parent_dir = Path("parent/folder/of/folder1/2/3/and/4")
dest_dir = Path("folder/to/result/images")
img_name2path = {}  # look up buffer

for child in src_parent_dir.glob("*/*.png"):  # assume all images ends with png
    img_name = child.name
    src0_path = img_name2path.get(img_name)
    if src0_path is None:  # store first image, look for second image
        img_name2path[img_name] = child
    else:  # first image found
        src0 = Image.open(src0_path)
        src1 = Image.open(child)
        dst = Image.new("RGBA", (src0.width + src1.width,
                        max(src0.height, src1.height)))
        dst.paste(src0, (0, 0))
        dst.paste(src1, (src0.width, 0))
        # this puts them side by side horizontally
        '''
        dst = Image.new("RGBA", (max(src0.width, src1.width)
                        src0.height + src1.height)))
        dst.paste(src0, (0, 0))
        dst.paste(src1, (0, src0.height))
        # use this to stack them vertically instead
        '''
        name = src0_path.stem
        suffix0 = src0_path.parent.name  # used to make dest file name
        suffix1 = child.parent.name  # used to make dest file name
        dst.save(Path(dest_dir, f"{name}_{suffix0}_{suffix1}.png"))
        # result image is named like a_1_folder1_folder2.png
        img_name2path[child.name] = None  # reset buffer
# Finally, deal with leftover single images
for img_name, src_path in img_name2path.items():
    if src_path is None:  # no leftover
        continue
    src = Image.open(src_path)
    dst = Image.new("RGBA", (src.width, src.height))
    dst.paste(src, (0, 0))
    dst.save(Path(dest_dir, 
                  f"{src_path.stem}_{src_path.parent.name}.png"))

相关问题