Skip to content Skip to sidebar Skip to footer

How Do I Randomly Select Multiple Images From Folders And Then Layer Them As A Single Image In Python?

I'm trying to use python to create a composite .png of randomly selected and layered png's all with transparent backgrounds, so all layers are visible in the finished piece. For ex

Solution 1:

Something like this maybe? This discovers all paths to PNG images in your two directories, and then picks one at random from each directory/layer. Then it iterates over the selected paths, and pastes them into a single image. I haven't tested this, but it should work:

from pathlib import Path
from random import choice

layers = [list(Path(directory).glob("*.png")) for directory in ("bigcircle/", "mediumcircle/")]

selected_paths = [choice(paths) for paths in layers]

img = Image.new("RGB", (4961, 4961), color=(0, 220, 15))
for path in selected_paths:
    layer = Image.open(str(path), "r")
    img.paste(layer, (0, 0), layer)


img.save("output.png")

Post a Comment for "How Do I Randomly Select Multiple Images From Folders And Then Layer Them As A Single Image In Python?"