Advertisement
here2share

# Tk_perlin_noise.py

Jun 20th, 2019 (edited)
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.74 KB | None | 0 0
  1. # Tk_perlin_noise.py -- very slow
  2.  
  3. dir=r"C:/pydemo/test/"
  4.  
  5.  
  6. from Tkinter import *
  7. import random
  8. import math
  9. from PIL import Image
  10. from decimal import Decimal
  11.  
  12. root = Tk()
  13. width,height=400,400
  14. root.geometry("%dx%d+10+10"%(width,height))
  15. canvas = Canvas(root,width=width, height=height, background="grey" )
  16. canvas.grid()
  17.  
  18.  
  19. IMAGE_SIZE = 400
  20. PERLIN_RESOLUTION = 10
  21. GRADIENT = []
  22.  
  23.  
  24. for x in range(PERLIN_RESOLUTION + 1):
  25.     GRADIENT.append([])
  26.     for y in range(PERLIN_RESOLUTION + 1):
  27.         angle = random.random() * 2 * math.pi
  28.         vector = (
  29.             Decimal(math.cos(angle)),
  30.             Decimal(math.sin(angle))
  31.         )
  32.         GRADIENT[x].append(vector)
  33.  
  34. def smoothstep(a0, a1, w):
  35.     value = w*w*w*(w*(w*6 - 15) + 10)
  36.     return a0 + value*(a1 - a0)
  37.  
  38. def dotGridGradient(ix, iy, x, y):
  39.  
  40.     dx = x - Decimal(ix)
  41.     dy = y - Decimal(iy)
  42.  
  43.     return (dx*GRADIENT[iy][ix][0] + dy*GRADIENT[iy][ix][1])
  44.  
  45.  
  46. def perlin(x, y):
  47.     if x > 0.0:
  48.         x0 = int(x)
  49.     else:
  50.         x0 = int(x) - 1
  51.     x1 = x0 + 1
  52.     if y > 0.0:
  53.         y0 = int(y)
  54.     else:
  55.         y0 = int(y) - 1
  56.     y1 = y0 + 1
  57.  
  58.     sx = x - Decimal(x0)
  59.     sy = y - Decimal(y0)
  60.  
  61.     n0 = dotGridGradient(x0, y0, x, y)
  62.     n1 = dotGridGradient(x1, y0, x, y)
  63.     ix0 = smoothstep(n0, n1, sx)
  64.     n0 = dotGridGradient(x0, y1, x, y)
  65.     n1 = dotGridGradient(x1, y1, x, y)
  66.     ix1 = smoothstep(n0, n1, sx)
  67.     value = smoothstep(ix0, ix1, sy)
  68.  
  69.     return value
  70.  
  71.  
  72. image = Image.new('RGB', (IMAGE_SIZE, IMAGE_SIZE))
  73. pixels = image.load()
  74. for i in range(IMAGE_SIZE):
  75.     x = Decimal(i) / IMAGE_SIZE
  76.     for j in range(IMAGE_SIZE):
  77.         y = Decimal(j) / IMAGE_SIZE
  78.         value = perlin(x * 10, y * 10)
  79.         greyscale = int((value + 1) * 255 / 2)
  80.         pixels[i, j] = (greyscale, greyscale, greyscale)
  81.         canvas.create_line((i, j, i+1, j+1), fill='#'+('%02x'%greyscale)*3)
  82.     canvas.update()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement