I am busy writing something to manipulate a image and paste other images onto it.
I am trying to change the background and the hat on a dog to various others and output multiple files with randomly generated images. The input images come from folders (backgrounds
and hats
). As we take pictures and copy them into the folder called background, I want to be able to run my Python script to change the background of the dog by picking a random image from the backgrounds
folder. I want to be able to do the same with images in the hats
folder. Will add more folders over time, but that's another day's question.
So far, I am able to paste items onto the main image. I have multiple PNG files in the folders and I get three images out, but all three images are the same. My code only seems to load one background and one hat.
Please help on how I can paste random images from the two folders onto my main image of the dog. Dog stays static, but backgrounds and hats will change. The options should be as many as the combinations can allow. So three folders with three options each will have alot of combination options. I have set the limit to three, but each time the images should render different combinations.
My code so far:
import glob
from PIL import Image
def main():
q = 0
hat_image = glob.glob("hats/*.png")
for image in hat_image:
with open(image, 'rb') as file:
hat = Image.open(file)
bg_image = glob.glob("backgrounds/*.png")
for image in bg_image:
with open(image, 'rb') as file:
bg = Image.open(file)
try:
while q < 3:
img = Image.open("base.png")
img.paste(hat, (276, 176), hat)
# mouth = Image.open("./mouth/mouth1.png")
img.paste(bg, (226,476), bg)
img.save("final{}.png".format(q), "PNG")
q += 1
except IOError:
pass
if __name__ == "__main__":
main()