Advertisement
here2share

# tk_HyperVoronoi.py

Apr 13th, 2023
938
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.67 KB | None | 0 0
  1. # tk_HyperVoronoi.py
  2.  
  3. from tkinter import *
  4. from PIL import Image, ImageTk
  5. import random
  6. import math
  7. import time
  8.  
  9. # Define constants
  10. ww = 300
  11. hh = 300
  12. rgb = [i for i in range(0, 256, 50)]
  13. colors = [(r, g, b) for r in rgb for g in rgb for b in rgb][100:-40]
  14. L = len(colors)
  15.  
  16. xy2field = {}
  17. c = 0
  18. for y in range(hh):
  19.     for x in range(ww):
  20.         xy2field[x,y] = c
  21.         c += 1
  22.        
  23. XY = [0] * (ww * hh)
  24.  
  25. # Define function for calculating distance between two points
  26. def distance(x1, y1, x2, y2):
  27.     return (x1 - x2)**2 + (y1 - y2)**2 # no need to get exact distance
  28.  
  29. def blend_colors(c1, c2, c3):
  30.     r = int((c1[0] + c2[0] + c3[0]) / 3)
  31.     g = int((c1[1] + c2[1] + c3[0]) / 3)
  32.     b = int((c1[2] + c2[2] + c3[0]) / 3)
  33.     return (r, g, b)
  34.  
  35. rndi = random.randint
  36. def Voronoi(numPoints):
  37.     basePoints = []
  38.     for i in range(numPoints):
  39.         x = rndi(0, ww)
  40.         y = rndi(0, hh)
  41.         basePoints.append((x, y, colors[i%L]))
  42.    
  43.     for y in range(hh):
  44.         for x in range(ww):
  45.             distances = []
  46.             for px, py, color in basePoints:
  47.                 distances.append([distance(x, y, px, py), color])
  48.             sorted_distances = sorted(distances)
  49.             # blend the two closest colors
  50.             blended_color = blend_colors(sorted_distances[0][-1], sorted_distances[1][-1], sorted_distances[2][-1])
  51.             points[xy2field[x,y]] = blended_color
  52.          
  53.     return points
  54.  
  55. root = Tk()
  56. root.title("Tk HyperVoronoi")
  57. root.geometry("%dx%d+-10+0"%(ww,hh))
  58. canvas = Canvas(root, width=ww, height=hh)
  59. canvas.pack()
  60.  
  61. while 1:
  62.     random.shuffle(colors)
  63.     points = XY[:]
  64.     pixels = Voronoi(30)
  65.     img = Image.new("RGB", (ww,hh))
  66.     img.putdata(pixels)
  67.  
  68.     imgTk = ImageTk.PhotoImage(img)
  69.     canvas.create_image(0, 0, anchor=NW, image=imgTk)
  70.     canvas.update()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement