Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # tk_HyperVoronoi.py
- from tkinter import *
- from PIL import Image, ImageTk
- import random
- import math
- import time
- # Define constants
- ww = 300
- hh = 300
- rgb = [i for i in range(0, 256, 50)]
- colors = [(r, g, b) for r in rgb for g in rgb for b in rgb][100:-40]
- L = len(colors)
- xy2field = {}
- c = 0
- for y in range(hh):
- for x in range(ww):
- xy2field[x,y] = c
- c += 1
- XY = [0] * (ww * hh)
- # Define function for calculating distance between two points
- def distance(x1, y1, x2, y2):
- return (x1 - x2)**2 + (y1 - y2)**2 # no need to get exact distance
- def blend_colors(c1, c2, c3):
- r = int((c1[0] + c2[0] + c3[0]) / 3)
- g = int((c1[1] + c2[1] + c3[0]) / 3)
- b = int((c1[2] + c2[2] + c3[0]) / 3)
- return (r, g, b)
- rndi = random.randint
- def Voronoi(numPoints):
- basePoints = []
- for i in range(numPoints):
- x = rndi(0, ww)
- y = rndi(0, hh)
- basePoints.append((x, y, colors[i%L]))
- for y in range(hh):
- for x in range(ww):
- distances = []
- for px, py, color in basePoints:
- distances.append([distance(x, y, px, py), color])
- sorted_distances = sorted(distances)
- # blend the two closest colors
- blended_color = blend_colors(sorted_distances[0][-1], sorted_distances[1][-1], sorted_distances[2][-1])
- points[xy2field[x,y]] = blended_color
- return points
- root = Tk()
- root.title("Tk HyperVoronoi")
- root.geometry("%dx%d+-10+0"%(ww,hh))
- canvas = Canvas(root, width=ww, height=hh)
- canvas.pack()
- while 1:
- random.shuffle(colors)
- points = XY[:]
- pixels = Voronoi(30)
- img = Image.new("RGB", (ww,hh))
- img.putdata(pixels)
- imgTk = ImageTk.PhotoImage(img)
- canvas.create_image(0, 0, anchor=NW, image=imgTk)
- canvas.update()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement