#!/usr/bin/env python
from PIL import Image, ImageDraw

sample_every = 200

def branch_lines(dr, pxs, x, y, ct):
	try:
		col = pxs[x, y]
	except IndexError:
		return
	rx = x - (col[0] - min(col))
	ry = y + (col[0] - min(col))
	gx = ct
	gy = y - (col[1] - min(col))
	bx = x - (col[2] - min(col))
	by = ct
	dr.line((x, y, rx, ry, gx, gy, bx, by), fill=col, width=4)
	if ct > 5:
		branch_lines(dr, pxs, rx, ry, ct/1.5)
		branch_lines(dr, pxs, gx, gy, ct/1.5)
		branch_lines(dr, pxs, bx, by, ct/1.5)

def main():
	img = Image.open("base.jpg")
	img = img.convert('RGBA')
	draw = ImageDraw.Draw(img)
	pixels = img.load()
	sample_posx, sample_posy = sample_every, sample_every
	while sample_posy < img.size[1]:
		while sample_posx < img.size[0]:
			branch_lines(draw, pixels, sample_posx, sample_posy, 100)
			sample_posx = sample_posx + sample_every
		else:
			sample_posx = sample_every
			sample_posy = sample_posy + sample_every
		sample_posy = sample_posy + sample_every
	img.save("out.png")

if __name__ == '__main__':
	main()