** ・ What is Perlin noise? ** Perlin noise is easy-to-use noise (such as random terrain generation) with moderate continuity and clutter. Others have written the details, so I'll just introduce the code here.
perlin.py
#Library import
import numpy as np
import matplotlib.pyplot as plt
#Children who produce linear interpolation and continuity
def fade(t):return 6*t**5-15*t**4+10*t**3
def lerp(a,b,t):return a+fade(t)*(b-a)
#Body
def perlin(r,seed=np.random.randint(0,100)):
np.random.seed(seed)
ri = np.floor(r).astype(int) #Integer part, used as an index
ri[0] -= ri[0].min() #
ri[1] -= ri[1].min() #Ready to use as an index
rf = np.array(r) % 1 #Decimal part
g = 2 * np.random.rand(ri[0].max()+2,ri[1].max()+2,2) - 1 #Gradient of grid points
e = np.array([[[[0,0],[0,1],[1,0],[1,1]]]]) #four corners
er = (np.array([rf]).transpose(2,3,0,1) - e).reshape(r.shape[1],r.shape[2],4,1,2) #Position vector seen from each point of the four corners
gr = np.r_["3,4,0",g[ri[0],ri[1]],g[ri[0],ri[1]+1],g[ri[0]+1,ri[1]],g[ri[0]+1,ri[1]+1]].transpose(0,1,3,2).reshape(r.shape[1],r.shape[2],4,2,1) #Processed into a shape that can calculate the inner product by collecting the gradients of the four corners with the familiar fancy sort
p = (er@gr).reshape(r.shape[1],r.shape[2],4).transpose(2,0,1) #Dot product calculation with gradient for all points
return lerp(lerp(p[0],p[2],rf[0]),lerp(p[1],p[3],rf[0]),rf[1]) #Interpolate and return
perlin.py
N = 512
y = np.zeros((N,N))
for i in np.random.rand(1): #Perlin noise seems to show its true potential when you change the frequency and stack several sheets, so loop and add (please do as much as you like)
x = np.linspace(0,8*i,N)
r = np.array(np.meshgrid(x,x))
y += perlin(r) #shape of meshgrid(2,N,N)Pass by
plt.imshow(y)
plt.show()
Result:
This code was written because I didn't want to use loops. On the way, a 5D tensor comes out, but it feels good to be able to write clearly.
Recommended Posts