首页 > 解决方案 > 如何循环此 Python PIL 代码以重复使用不同的图像?

问题描述

我有以下代码使用 PIL 将图像粘贴到另一个图像的顶部。我想重复此过程以自动处理 1000 多张图像。有没有办法通过从一个文件夹中选择 1000 多个图像并将它们粘贴到另一个文件夹中的另外 1000 多个图像之上来循环它?

from PIL import Image, ImageOps

img = Image.open('image1.png', 'r')
img_w, img_h = img.size
background = Image.open('image2.png', 'r')
bg_w, bg_h = background.size
offset = ((bg_w - img_w) // 1, (bg_h - img_h) // 6)
background.paste(img, offset)

background.save('out.png')

标签: pythonpython-imaging-library

解决方案


我的解释是,您希望一个文件夹中的所有图像都遍历另一个文件夹中的所有图像。

您需要遍历目录中的所有文件,除非IOError它不支持您已经结束的图像文件。

您将需要导入os,并将图像保存为迭代编号的文件名。

这就是您的代码的样子:

from PIL import Image, ImageOps
import os

dir = "C:/Users/User/Pictures/"
dir2 = "C:/Users/User/Pictures/"

images = os.listdir(dir)
images2 = os.listdir(dir2)
itr = 1

for image in images:
    for image2 in images2:
        try:
            img = Image.open(dir + image, 'r')
            img_w, img_h = img.size
            background = Image.open(dir + image2, 'r')
            print("Image = " + image + " background = " + image2 + " at itr "+ str(itr))
            print("")
            bg_w, bg_h = background.size
            offset = ((bg_w - img_w) // 1, (bg_h - img_h) // 6)
            background.paste(img, offset)
            background.save('./How do I loop this Python PIL code/' + str(itr)+ ".png")
            itr += 1
        except IOError:
            pass

推荐阅读