python - 如何循环此 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')
解决方案
我的解释是,您希望一个文件夹中的所有图像都遍历另一个文件夹中的所有图像。
您需要遍历目录中的所有文件,除非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
推荐阅读
- coldfusion - ColdFusion 11 没有关闭 java.io.FileInputStream
- python - 查找数组是否为排列的最佳方法
- javascript - Error TypeError: $(…).DataTable is not a function
- typescript - TypeError:单击不是下拉列表的功能
- ios - 在 Objective-c 中访问二维 NSArray 中的值
- amazon-web-services - 如何将 yamel 文件内容传递给云形成嵌套堆栈?
- python - 在条形图中显示每个 bin 的值 - Python
- entity-framework-6 - 实体框架撤消删除而不再次查询数据库
- powershell - 使用 CLSID 创建 COM 组件的实例
- java - GregorianCalendar 不能加 97 天?