This program draws a ‘tree’ by drawing a trunk (initially; later it’s a branch) and appending a tree, recursively. Uses Pillow.
# Adapted from http://rosettacode.org/wiki/Fractal_tree#Python # to parameterise, and add colour. # http://pillow.readthedocs.org/ # Author: Alan Richmond, Python3.codes, and others (Rosettacode) import math, colorsys from PIL import Image, ImageDraw spread = 17 # how much branches spread apart width, height = 1000, 800 # window size maxd = 12 # maximum recursion depth len = 8.0 # branch length factor # http://pillow.readthedocs.org/en/latest/reference/Image.html img = Image.new('RGB', (width, height)) # http://pillow.readthedocs.org/en/latest/reference/ImageDraw.html d = ImageDraw.Draw(img) # This function calls itself to add sub-trees def drawTree(x1, y1, angle, depth): if depth > 0: # compute this branch's next endpoint x2 = x1 + int(math.cos(math.radians(angle)) * depth * len) y2 = y1 + int(math.sin(math.radians(angle)) * depth * len) # https://docs.python.org/2/library/colorsys.html (r, g, b) = colorsys.hsv_to_rgb(float(depth) / maxd, 1.0, 1.0) R, G, B = int(255 * r), int(255 * g), int(255 * b) # draw the branch d.line([x1, y1, x2, y2], (R, G, B), depth) # and append 2 trees by recursion drawTree(x2, y2, angle - spread, depth - 1) drawTree(x2, y2, angle + spread, depth - 1) # Start drawing! drawTree(width / 2, height * 0.9, -90, maxd) img.show() img.save("Tree.png", "PNG")
Python Imaging Library (abbreviated as PIL) (in newer versions known as Pillow) is a free library for the Python programming language that adds support for opening, manipulating, and saving many different image file formats. It is available for Windows, Mac OS X and Linux. The latest version of PIL is 1.1.7, was released in September 2009 and supports Python 1.5.2–2.7, with Python 3 support to be released "later".
Development appears to be discontinued with the last commit to the PIL repository coming in 2011. Consequently, a successor project called Pillow has forked the PIL repository and added Python 3.x support. This fork has been adopted as a replacement for the original PIL in Linux distributions including Debian and Ubuntu (since 13.04).