Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Create a Voronoi diagram as a raster image in Python. Converted from PIL to DrawBot.
# http://forum.drawbot.com/topic/148/voronoi-fun/2
import random
import math
def generate_voronoi_diagram(imgx, imgy, num_cells):
nx = []
ny = []
nr = []
ng = []
nb = []
for i in range(num_cells):
nx.append(random.randrange(imgx))
ny.append(random.randrange(imgy))
nr.append(random.random())
ng.append(random.random())
nb.append(random.random())
im = ImageObject()
with im:
size(imgx, imgy)
for y in range(imgy):
for x in range(imgx):
dmin = math.hypot(imgx-1, imgy-1)
j = -1
for i in range(num_cells):
d = math.hypot(nx[i]-x, ny[i]-y)
if d < dmin:
dmin = d
j = i
fill(nr[j], ng[j], nb[j])
rect(x, y, 1, 1)
image(im, (0, 0))
size(200, 200)
generate_voronoi_diagram(width(), height(), 7)
saveImage("VoronoiDiagram.png")
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.