我正在尝试将两个图像水平地相互拼接,并且我想对文件夹中的所有图像执行此操作。我的图像命名为: img1.jpg img1a.jpg img2.jpg img2a.jpg
这样img1和img1a应该被拼接,img2应该和img2a被拼接。
我正在使用以下代码手动缝合两个图像,但无法实现如何将其扩展到整个文件夹。
如果有任何帮助,我将不胜感激。
import sys
from PIL import Image
images = map(Image.open, ['img1.jpg', 'img1a.jpg'])
widths, heights = zip(*(i.size for i in images))
total_width = sum(widths)
max_height = max(heights)
new_im = Image.new('RGB', (total_width, max_height))
x_offset = 0
for im in images:
new_im.paste(im, (x_offset,0))
x_offset += im.size[0]
new_im.save('img1.jpg')
最佳答案
我假设文件夹中只有对要缝合的。
使用os.listdir(folder)
获取文件夹中的所有文件。使用 sorted()
按字母顺序设置它们(有时 listdir()
给出不同顺序的文件 - 可能按创建时间排序)
使用zip()
和两个子列表all_files[::2]
、all_files[1::2]
你可以创建对您可以使用您的代码运行
for a, b in zip(all_files[::2], all_files[1::2]):
stitch(a, b)
<小时/>
import os
import sys
from PIL import Image
def stitch(name1, name2):
images = map(Image.open, [name1, name2])
widths, heights = zip(*(i.size for i in images))
total_width = sum(widths)
max_height = max(heights)
new_im = Image.new('RGB', (total_width, max_height))
x_offset = 0
for im in images:
new_im.paste(im, (x_offset,0))
x_offset += im.size[0]
new_im.save(name1)
# ----
folder = 'some_folder'
# get all files in alphabetic order
all_files = sorted(os.listdir(folder))
# add folder to filename to have full path
all_files = [os.path.join(folder, name) for name in all_files]
# create pairs
for a, b in zip(all_files[::2], all_files[1::2]):
stitch(a, b)
<小时/>
编辑:您还可以使用 iter()
和 zip()
来创建对
it = iter(all_files)
for a, b in zip(it, it):
stitch(a, b)
或
关于python - 如何在python中拼接文件夹中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59332900/