Skip to content

Instantly share code, notes, and snippets.

@gumblex gumblex/imgfill.py

Last active Mar 6, 2016
Embed
What would you like to do?
Fill a canvas with a given image of different sizes.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import random
from PIL import Image
'''
Copyright (c) 2016 gumblex
This program is free software. It comes without any warranty, to
the extent permitted by applicable law. You can redistribute it
and/or modify it under the terms of the Do What The Fuck You Want
To Public License, Version 2, as published by Sam Hocevar. See
http://www.wtfpl.net/ for more details.
'''
srandom = random.SystemRandom()
def test_img_overlap(bg, fg, x, y, w, size):
bga = bg.getdata(3)
fg = fg.copy().resize((size, size), Image.NEAREST)
for pos, px in enumerate(fg.getdata(3)):
y1, x1 = divmod(pos, size)
try:
if px and bga[(y1+y)*w+x1+x]:
return True
except IndexError:
pass
def rnd_pos_size(w=512, h=249, num=100, maxs=60, mins=3):
for i in range(num):
yield (srandom.randint(0, w), srandom.randint(0, h),
srandom.randint(mins, maxs))
def draw_no_overlap(src, possize, w=512, h=249, num=300, maxs=60, mins=5, sigma=20):
img = Image.new('RGBA', (w, h), (255, 255, 255, 0))
glp = Image.open(src).convert('RGBA')
sizes = sorted((min(maxs, max(mins, int(srandom.normalvariate(mins+1, sigma)))) for i in range(num)), reverse=1)
# sizes = sorted((int(random.paretovariate(1)) for i in range(num)), reverse=1)
# sizes = sorted((random.randint(mins, maxs) for i in range(num)), reverse=1)
# [60]*3 + [47]*7 + [37]*8 + [33]*2 + [27]*11 + [20]*16 + [18]*4 + [15]*13
# + and more small ones
for num, s in enumerate(sizes):
print(num, s)
g = glp.copy().resize((s, s), Image.LANCZOS)
x, y = srandom.randint(0, w-s), srandom.randint(0, h-s)
while test_img_overlap(img, g, x, y, w, s):
x, y = srandom.randint(0, w-s), srandom.randint(0, h-s)
img.paste(g, (x, y), g)
return img
def main(src):
img = draw_no_overlap(src, rnd_pos_size())
img.save('imgfill.png')
if __name__ == '__main__':
main(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.