简体   繁体   English

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

[英]How to Stitch Images in a folder in python

I am trying to stitch two images to each other horizontally and I want to do this for all images in a folder.我试图将两个图像水平缝合在一起,我想对文件夹中的所有图像执行此操作。 I have images named as: img1.jpg img1a.jpg img2.jpg img2a.jpg我有图像命名为: img1.jpg img1a.jpg img2.jpg img2a.jpg

So that img1 and img1a should be stitched and img2 should be stitched with img2a.这样img1和img1a应该被拼接,img2应该和img2a拼接。

I am using the following code two stitch two images manually but couldn't implement how to extend it to the entire folder.我正在使用以下代码手动缝合两个图像,但无法实现如何将其扩展到整个文件夹。

I would appreciate any help.我将不胜感激任何帮助。

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')

I assume that in folder are only pairs to stitch.我假设文件夹中只有成对缝合。

Use os.listdir(folder) to get all files in folder.使用os.listdir(folder)获取文件夹中的所有文件。 Set them in alphabetic order using sorted() (sometimes listdir() gives files in different order - probably sorted by time of creation)使用sorted()按字母顺序设置它们(有时listdir()以不同的顺序给出文件 - 可能按创建时间排序)

Using zip() and two sublists all_files[::2] , all_files[1::2] you can create pairs which you can run with your code使用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)  

EDIT: you can also use iter() with zip() to create pairs编辑:您还可以使用iter()zip()来创建对

it = iter(all_files)
for a, b in zip(it, it):
    stitch(a, b)

or或者

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM