Advertisement
here2share

# Tk_perlin_noise3.py

Nov 14th, 2020
1,054
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.49 KB | None | 0 0
  1. # Tk_perlin_noise3.py
  2.  
  3. from Tkinter import *
  4. from PIL import Image, ImageTk
  5. import random
  6. import math
  7. import time
  8. ww = 600
  9. hh = 600
  10.  
  11. if 1:
  12.     root = Tk()
  13.     root.title("Tk Perlin Noise")
  14.     root.geometry("%dx%d+-10+0"%(ww,hh))
  15.     canvas = Canvas(root, width=ww, height=hh)
  16.     canvas.pack()
  17. 0
  18.  
  19. if 1:
  20.     data = []
  21.     img = Image.new("RGB", (ww, hh))
  22.    
  23.     octaves = int(math.log(max(ww, hh), 2.0))
  24.     persistence = random.random()
  25.     imgAr = [[0.0 for i in range(ww)] for j in range(hh)] # image array
  26.     totAmp = 0.0
  27.     for k in range(octaves):
  28.         freq = 2 ** k
  29.         amp = persistence ** k
  30.         totAmp += amp
  31.         # create an image from n by m grid of random numbers (w/ amplitude)
  32.         # using Bilinear Interpolation
  33.         n = freq + 1; m = freq + 1 # grid size
  34.         ar = [[random.random() * amp for i in range(n)] for j in range(m)]
  35.         nx = ww / (n - 1.0); ny = hh / (m - 1.0)
  36.         for ky in range(hh):
  37.             for kx in range(ww):
  38.                 i = int(kx / nx); j = int(ky / ny)
  39.                 dx0 = kx - i * nx; dx1 = nx - dx0
  40.                 dy0 = ky - j * ny; dy1 = ny - dy0
  41.                 z = ar[j][i] * dx1 * dy1
  42.                 z += ar[j][i + 1] * dx0 * dy1
  43.                 z += ar[j + 1][i] * dx1 * dy0
  44.                 z += ar[j + 1][i + 1] * dx0 * dy0
  45.                 z /= nx * ny
  46.                 imgAr[ky][kx] += z # add image layers together
  47.  
  48.     # paint image
  49.     pixels = []
  50.     for ky in range(hh):
  51.         for kx in range(ww):
  52.             c = int(imgAr[ky][kx] / totAmp * 255)
  53.             pixels.append((c, c, c))
  54.    
  55.     img.putdata(pixels)
  56.    
  57.     imgTk = ImageTk.PhotoImage(img)
  58.     canvas.create_image(0, 0, anchor=NW, image=imgTk)
  59.     canvas.update()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement