Advertisement
here2share

# Tk_colorful_perlin_noise.py

Mar 31st, 2022
876
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.17 KB | None | 0 0
  1. # Tk_colorful_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("Colorful 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. dirs = [(math.cos(a * 2.0 * math.pi / 256),
  20.          math.sin(a * 2.0 * math.pi / 256))
  21.          for a in range(256)]
  22.  
  23.  
  24. def noise(x, y, per):
  25.     # Perlin noise is generated from a summation of little "surflets" which are the product of a randomly oriented
  26.     # gradient and a separable polynomial falloff function.
  27.     def surflet(gridX, gridY):
  28.         distX, distY = abs(x-gridX), abs(y-gridY)
  29.         polyX = 1 - 6*distX**5 + 15*distX**4 - 10*distX**3  # polynomial falloff function
  30.         polyY = 1 - 6*distY**5 + 15*distY**4 - 10*distY**3
  31.  
  32.         hashed = perm[perm[int(gridX) % per] + int(gridY) % per]
  33.         grad = (x-gridX)*dirs[hashed][0] + (y-gridY)*dirs[hashed][1]
  34.         return polyX * polyY * grad
  35.     intX, intY = int(x), int(y)
  36.  
  37.     return (surflet(intX+0, intY+0) + surflet(intX+1, intY+0) +
  38.             surflet(intX+0, intY+1) + surflet(intX+1, intY+1))
  39.  
  40. def fBm(x, y, per, octs):
  41.     val = 0
  42.     for o in range(octs):
  43.         val += 0.5**o * noise(x*2**o, y*2**o, per*2**o)
  44.     return val
  45.  
  46. rainbow=[]
  47. def z(r,g,b):
  48.     rainbow.append((r,g,b))
  49. r,g,b=255,0,0
  50. for g in range(256):
  51.     z(r,g,b)
  52. for r in range(254, -1, -1):
  53.     z(r,g,b)
  54. for b in range(256):
  55.     z(r,g,b)
  56. for g in range(254, -1, -1):
  57.     z(r,g,b)
  58. for r in range(256):
  59.     z(r,g,b)
  60. for b in range(254, -1, -1):
  61.     z(r,g,b)
  62. rainbow*=2
  63.  
  64. colors = len(rainbow)/2-1
  65.  
  66. while 1:
  67.     perm = list(range(256))
  68.     random.shuffle(perm)
  69.     perm += perm
  70.     xy = []
  71.     size, freq, octs = 256, 1/32.0, 5
  72.     for y in range(size):
  73.         for x in range(size):
  74.             zzz = fBm(x*freq, y*freq, int(size*freq), octs)
  75.             xy.append(rainbow[int(zzz*colors+colors)])
  76.     img.putdata(xy)
  77.     imgTk = ImageTk.PhotoImage(img)
  78.     #time.sleep(0.02)
  79.     canvas.create_image(-2, 0, anchor=NW, image=imgTk)
  80.     root.update()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement