How to paste groups of images from a list on top of a base image with the Pillow module?

Viewed 265

All images are in PNG format.

 from PIL import Image

First of all, I would have a base image:

image_base = Image.open (image.png)

Second, I would have a list of my desired combinations (each string is linked to an image path) to paste over the base image, such that combinations [0] [0], combinations [0] [1], and combinations [0] [2] pasted on top of the base image would compose a final image of the 8 desired (look at the first index, it goes up to 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] ']

My goal would be to figure out how to iterate through the list and paste each combination with the same first index above the base image. In this case, every 3 values ​​in the list, create a composition.

1 Answers

It is situation when range(len()) can be useful because it can use step in range()

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

and it gives lists

['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]']

And now you can use every list to create image

new = base.copy()

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

PIL doc: Image.paste()


EDIT:

Nested loops.

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, ....)
Related