Advertisement
here2share

# Tk_rainbow_perlin_noise_v2.py

Oct 12th, 2022
804
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.04 KB | None | 0 0
  1. # Tk_rainbow_perlin_noise_v2.py
  2.  
  3. from tkinter import *
  4. from PIL import Image, ImageTk
  5. import random
  6. import math
  7.  
  8. ww = 500
  9. hh = 500
  10. root = Tk()
  11. root.title("Rainbow Perlin Noise")
  12. root.geometry("%dx%d+0+0"%(ww,hh))
  13. canvas = Canvas(root, width=ww, height=hh)
  14. canvas.grid()
  15. root.update()
  16.  
  17. # create new image
  18. img = Image.new("RGB",(ww, hh), "white")
  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. def fBm(x, y, per, octs):
  42.     val = 0
  43.     for o in range(octs):
  44.         val += 0.5**o * noise(x*2**o, y*2**o, per*2**o)
  45.     return val
  46.  
  47. rainbow=[]
  48. def z(r,g,b):
  49.     rainbow.append((r,g,b))
  50. r,g,b=255,0,0
  51. for g in range(256):
  52.     z(r,g,b)
  53. for r in range(254, -1, -1):
  54.     z(r,g,b)
  55. for b in range(256):
  56.     z(r,g,b)
  57. for g in range(254, -1, -1):
  58.     z(r,g,b)
  59. for r in range(256):
  60.     z(r,g,b)
  61. for b in range(254, -1, -1):
  62.     z(r,g,b)
  63. rainbow*=2
  64.  
  65. colors = len(rainbow)/2-1
  66.  
  67. while 1:
  68.     perm = list(range(256))
  69.     random.shuffle(perm)
  70.     perm += perm
  71.     xyz = []
  72.     size, freq, octs = ww*hh, 1/132.0, 5 # <<<
  73.     frame = int(size*freq)
  74.     for y in range(hh):
  75.         for x in range(ww):
  76.             zzz = fBm(x*freq, y*freq, frame, octs)
  77.             xyz.append(rainbow[int(zzz*colors+colors)])
  78.     img.putdata(xyz)
  79.     imgTk = ImageTk.PhotoImage(img)
  80.     #time.sleep(0.02)
  81.     canvas.create_image(-2, 0, anchor=NW, image=imgTk)
  82.     root.update()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement