lnyan/stablediffusion-infinity
807
1import numpy as np2 3##########4# https://stackoverflow.com/questions/42147776/producing-2d-perlin-noise-with-numpy/42154921#421549215def perlin(x, y, seed=0):6 # permutation table7 np.random.seed(seed)8 p = np.arange(256, dtype=int)9 np.random.shuffle(p)10 p = np.stack([p, p]).flatten()11 # coordinates of the top-left12 xi, yi = x.astype(int), y.astype(int)13 # internal coordinates14 xf, yf = x - xi, y - yi15 # fade factors16 u, v = fade(xf), fade(yf)17 # noise components18 n00 = gradient(p[p[xi] + yi], xf, yf)19 n01 = gradient(p[p[xi] + yi + 1], xf, yf - 1)20 n11 = gradient(p[p[xi + 1] + yi + 1], xf - 1, yf - 1)21 n10 = gradient(p[p[xi + 1] + yi], xf - 1, yf)22 # combine noises23 x1 = lerp(n00, n10, u)24 x2 = lerp(n01, n11, u) # FIX1: I was using n10 instead of n0125 return lerp(x1, x2, v) # FIX2: I also had to reverse x1 and x2 here26 27 28def lerp(a, b, x):29 "linear interpolation"30 return a + x * (b - a)31 32 33def fade(t):34 "6t^5 - 15t^4 + 10t^3"35 return 6 * t ** 5 - 15 * t ** 4 + 10 * t ** 336 37 38def gradient(h, x, y):39 "grad converts h to the right gradient vector and return the dot product with (x,y)"40 vectors = np.array([[0, 1], [0, -1], [1, 0], [-1, 0]])41 g = vectors[h % 4]42 return g[:, :, 0] * x + g[:, :, 1] * y43 44 45##########