python - 如何在python中拼接文件夹中的图像

标签 python image-processing

我正在尝试将两个图像水平地相互拼接,并且我想对文件夹中的所有图像执行此操作。我的图像命名为: 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/

相关文章:

python - 根据长度和交集从列表列表中选择元素

python - 如何检查 virtualenv 是否是用 '--no-site-packages' 创建的?

python - 类型错误 : translate() takes exactly one argument (2 given)

php - 为什么这个基本的 imagejpeg() 缩放器返回黑色图像?

image - 如何将 .Jpeg 图像转换为 .Bmp

python - 在python中向列表实例添加一个方法

python - 根据单独的字典有条件地创建字典

iphone - 如何从 iPhone 中的图像中去除红眼?

c# - 如何在 Windows Phone 上压缩图像

python - 如何将 Gabor 滤波器应用于六边形采样的图像?