Advertisement
here2share

# Tk_grays_perlin_noise.py

May 6th, 2020
1,543
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.81 KB | None | 0 0
  1. # Tk_grays_perlin_noise.py
  2.  
  3. from Tkinter import *
  4. from PIL import Image, ImageTk
  5. import random
  6. import math
  7.  
  8. wt = 256
  9. ht = 256
  10. root = Tk()
  11. root.title("Grays Perlin Noise")
  12. root.geometry("%dx%d+0+0"%(wt,ht))
  13. canvas = Canvas(root, width=wt, height=ht)
  14. canvas.grid()
  15.  
  16. # create new image
  17. img = Image.new("RGB",(wt, ht), "white")
  18.  
  19.  
  20. dirs = [(math.cos(a * 2.0 * math.pi / 256),
  21.          math.sin(a * 2.0 * math.pi / 256))
  22.          for a in range(256)]
  23.  
  24.  
  25. def noise(x, y, per):
  26.     # Perlin noise is generated from a summation of little "surflets" which are the product of a randomly oriented
  27.     # gradient and a separable polynomial falloff function.
  28.     def surflet(gridX, gridY):
  29.         distX, distY = abs(x-gridX), abs(y-gridY)
  30.         polyX = 1 - 6*distX**5 + 15*distX**4 - 10*distX**3  # polynomial falloff function
  31.         polyY = 1 - 6*distY**5 + 15*distY**4 - 10*distY**3
  32.  
  33.         hashed = perm[perm[int(gridX) % per] + int(gridY) % per]
  34.         grad = (x-gridX)*dirs[hashed][0] + (y-gridY)*dirs[hashed][1]
  35.         return polyX * polyY * grad
  36.     intX, intY = int(x), int(y)
  37.  
  38.     return (surflet(intX+0, intY+0) + surflet(intX+1, intY+0) +
  39.             surflet(intX+0, intY+1) + surflet(intX+1, intY+1))
  40.  
  41.  
  42. def fBm(x, y, per, octs):
  43.     val = 0
  44.     for o in range(octs):
  45.         val += 0.5**o * noise(x*2**o, y*2**o, per*2**o)
  46.     return val
  47.  
  48. while 1:
  49.     perm = range(256)
  50.     random.shuffle(perm)
  51.     perm += perm
  52.     xy = []
  53.     size, freq, octs = 256, 1/32.0, 5
  54.     for y in range(size):
  55.         for x in range(size):
  56.             zzz = fBm(x*freq, y*freq, int(size*freq), octs)
  57.             xy.extend([tuple([int(zzz*128)+128])*3])
  58.     img.putdata(xy)
  59.     imgTk = ImageTk.PhotoImage(img)
  60.     #time.sleep(0.02)
  61.     canvas.create_image(-2, 0, anchor=NW, image=imgTk)
  62.     root.update()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement