如何使用枕头模块将列表中的图像组粘贴到基本图像的顶部?

2024-05-13 19:10:41 发布

您现在位置:Python中文网/ 问答频道 /正文

所有图像均为PNG格式

 from PIL import Image

首先,我会有一个基本的形象:

image_base = Image.open (image.png)

其次,我将有一个所需组合的列表(每个字符串都链接到一个图像路径)以粘贴到基础图像上,这样粘贴在基础图像顶部的组合[0][0]、组合[0][1]和组合[0][2]将构成8个所需的最终图像(查看第一个索引,它上升到7)

list = ['combinations [0] [0]', 'combinations [0] [1]', 'combinations [0] [2]', 'combinations [1] [0]', 'combinations [1] [1 ] ',' combinations [1] [2] ',' combinations [2] [0] ',' combinations [2] [1] ',' combinations [2] [2] ',' combinations [3] [0 ] ',' combinations [3] [1] ',' combinations [3] [2] ',' combinations [4] [0] ',' combinations [4] [1] ',' combinations [4] [2 ] ',' combinations [5] [0] ',' combinations [5] [1] ',' combinations [5] [2] ',' combinations [6] [0] ',' combinations [6] [1 ] ',' combinations [6] [2] ',' combinations [7] [0] ',' combinations [7] [1] ',' combinations [7] [2] ']

我的目标是找出如何迭代列表,并在基础图像上方粘贴具有相同第一个索引的每个组合。在这种情况下,每3个值​​在列表中,创建一个合成


Tags: from图像imageimport列表basepilpng
1条回答
网友
1楼 · 发布于 2024-05-13 19:10:41

这种情况下range(len())可能有用,因为它可以在range()中使用step

for i in range(0, len(list), 3):
    print(list[i:i+3])

它给出了列表

['combinations [0] [0]', 'combinations [0] [1]', 'combinations [0] [2]']
['combinations [1] [0]', 'combinations [1] [1]', 'combinations [1] [2]']
['combinations [2] [0]', 'combinations [2] [1]', 'combinations [2] [2]']
['combinations [3] [0]', 'combinations [3] [1]', 'combinations [3] [2]']
['combinations [4] [0]', 'combinations [4] [1]', 'combinations [4] [2]']
['combinations [5] [0]', 'combinations [5] [1]', 'combinations [5] [2]']
['combinations [6] [0]', 'combinations [6] [1]', 'combinations [6] [2]']
['combinations [7] [0]', 'combinations [7] [1]', 'combinations [7] [2]']

现在您可以使用每个列表创建图像

new = base.copy()

for path in list[i:i+3]:
    image = Image.open(path)
    new.paste(image, ....)

PIL文件:Image.paste()


编辑:

嵌套循环

for i in range(0, len(list), 3):
    #print(list[i:i+3])
    new = base.copy()

    for path in list[i:i+3]:
        image = Image.open(path)
        new.paste(image, ....)

相关问题 更多 >