Advertisement
here2share

# tk_2D_grayscale_art.py

Apr 24th, 2023
827
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.39 KB | None | 0 0
  1. # tk_2D_grayscale_art.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 = 512
  11. hh = 512
  12.  
  13. o255 = [z for z in range(256)]
  14. o255 = o255[1:-1] + o255[::-1]
  15. Lo = len(o255)
  16.  
  17. xy2field = {}
  18. c = 0
  19. for y in range(hh):
  20.     for x in range(ww):
  21.         xy2field[x,y] = c
  22.         c += 1
  23.        
  24. XY = [0] * (ww * hh)
  25.  
  26. # Define function for calculating distance between two points
  27. def distance(x1, y1, x2, y2):
  28.     return int(((x1 - x2)**2 + (y1 - y2)**2)**0.5) # no need to get exact distance
  29.  
  30. rndi = random.randint
  31. def Voronoi(numPoints):
  32.     basePoints = []
  33.     for i in range(numPoints):
  34.         x = rndi(0, ww)
  35.         y = rndi(0, hh)
  36.         basePoints.append((x, y))
  37.    
  38.     for y in range(hh):
  39.         for x in range(ww):
  40.             distances = []
  41.             for px, py in basePoints:
  42.                 distances += [distance(x, y, px, py)]
  43.             distances = sorted(distances)
  44.             r = o255[sum(distances[:3])%Lo]
  45.             # g = o255[sum(distances[2:6])%Lo]
  46.             # b = o255[sum(distances[4:9])%Lo]
  47.             points[xy2field[x,y]] = (r,r,r)
  48.          
  49.     return points
  50.  
  51. root = Tk()
  52. root.title("Tk 2D Grayscale Art")
  53. root.geometry("%dx%d+-10+0"%(ww,hh))
  54. canvas = Canvas(root, width=ww, height=hh)
  55. canvas.pack()
  56.  
  57. while 1:
  58.     points = XY[:]
  59.     pixels = Voronoi(30)
  60.     img = Image.new("RGB", (ww,hh))
  61.     img.putdata(pixels)
  62.  
  63.     imgTk = ImageTk.PhotoImage(img)
  64.     canvas.create_image(0, 0, anchor=NW, image=imgTk)
  65.     canvas.update()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement