Advertisement
here2share

# Tk_perlin_noise2.py

Nov 6th, 2020 (edited)
2,148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.38 KB | None | 0 0
  1. # Tk_perlin_noise2.py
  2.  
  3. from Tkinter import *
  4. from PIL import Image, ImageTk
  5. import random
  6. import math
  7. import time
  8.  
  9. root = Tk()
  10. root.title("Tk Perlin Noise")
  11. ww = 400
  12. hh = 400
  13. root.geometry("%dx%d+-10+0"%(ww,hh))
  14. canvas = Canvas(root, width=ww, height=hh)
  15. canvas.pack()
  16.  
  17. dirs = [(math.cos(a * 2.0 * math.pi / 256),
  18.          math.sin(a * 2.0 * math.pi / 256))
  19.          for a in range(256)]
  20.  
  21. def noise(x, y, per):
  22.     def surflet(gridX, gridY):
  23.         distX, distY = abs(x-gridX), abs(y-gridY)
  24.         polyX = 1 - 6*distX**5 + 15*distX**4 - 10*distX**3
  25.         polyY = 1 - 6*distY**5 + 15*distY**4 - 10*distY**3
  26.         hashed = perm[perm[int(gridX)%per] + int(gridY)%per]
  27.         grad = (x-gridX)*dirs[hashed][0] + (y-gridY)*dirs[hashed][1]
  28.         return polyX * polyY * grad
  29.     intX, intY = int(x), int(y)
  30.     return (surflet(intX+0, intY+0) + surflet(intX+1, intY+0) +
  31.             surflet(intX+0, intY+1) + surflet(intX+1, intY+1))
  32.  
  33. def fBm(x, y, per, octs):
  34.     val = 0
  35.     for o in range(octs):
  36.         val += 0.5**o * noise(x*2**o, y*2**o, per*2**o)
  37.     return int(val*256)
  38.  
  39. freq, octs = 1/32.0, 5
  40.  
  41. perm = range(256)
  42. perm += perm
  43.  
  44. while 1:
  45.     data = []
  46.     random.shuffle(perm)
  47.     for y in range(hh):
  48.         for x in range(ww):
  49.             data.append(fBm(x*freq, y*freq, int(ww*hh*freq), octs))
  50.  
  51.     img = Image.new("L", (ww, hh))
  52.  
  53.     img.putdata(data)
  54.  
  55.     imgTk = ImageTk.PhotoImage(img)
  56.     canvas.create_image(0, 0, anchor=NW, image=imgTk)
  57.     canvas.update()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement