Skip to content

Instantly share code, notes, and snippets.

@gumblex gumblex/

Last active Mar 6, 2016
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 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)
if px and bga[(y1+y)*w+x1+x]:
return True
except IndexError:
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 ='RGBA', (w, h), (255, 255, 255, 0))
glp ='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())'imgfill.png')
if __name__ == '__main__':
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.