Created
December 3, 2016 21:48
-
-
Save zphixon/927e9b55502b28ea8a2a9bf8a2048409 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# adapted and annotated from rosettacode | |
# https://rosettacode.org/wiki/Voronoi_diagram#Python | |
# pillow library | |
from PIL import Image | |
import random | |
import math | |
# cells is synonymous with sites | |
def generate_voronoi_diagram(width, height, num_cells, name): | |
# image to use | |
image = Image.new("RGB", (width, height)) | |
imgx, imgy = image.size | |
# site points | |
nx = [] | |
ny = [] | |
# site colors | |
nr = [] | |
ng = [] | |
nb = [] | |
# place voronoi points | |
for i in range(num_cells): | |
nx.append(random.randrange(imgx)) | |
ny.append(random.randrange(imgy)) | |
# randomize color of site: blue-ish | |
nr.append(random.randrange(25) + 100) | |
ng.append(random.randrange(25) + 146) | |
nb.append(random.randrange(25) + 219) | |
# look at every pixel starting in top left | |
for y in range(imgy): | |
for x in range(imgx): | |
# distance from center to corner initially | |
# later set as distance to closest site | |
dmin = math.hypot(imgx - 1, imgy - 1) | |
# which site to use | |
j = -1 | |
# loop through sites | |
for i in range(num_cells): | |
# find distance to current site | |
d = math.hypot(nx[i] - x, ny[i] - y) | |
# check if current site is closer | |
if d < dmin: | |
dmin = d | |
j = i | |
# set current pixel to color of closest cell | |
image.putpixel((x, y), (nr[j], ng[j], nb[j])) | |
# save image | |
image.save(name, "PNG") | |
# generate diagram | |
generate_voronoi_diagram(1860, 1920, 32, "screen.png") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment