[Python] I forcibly wrote a short Perlin noise generation function in Numpy.

Introduction

** ・ 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.

The function I wrote

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

Calculation / plot

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: perlin.png

Other 3D plots and extended dimensions

Summary

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

[Python] I forcibly wrote a short Perlin noise generation function in Numpy.
I wrote a function to load a Git extension script in Python
A memo that I wrote a quicksort in Python
I wrote a class in Python3 and Java
I made a prime number generation program in Python
I made a prime number generation program in Python 2
Create a function in Python
I wrote Fizz Buzz in Python
I wrote the queue in Python
I wrote the stack in Python
I wrote a script to extract a web page link in Python
I made a payroll program in Python!
Precautions when pickling a function in python
Write a short property definition in Python
I created a password tool in Python.
I wrote a code to convert quaternions to z-y-x Euler angles in Python
I wrote FizzBuzz in python using a support vector machine (library LIVSVM).
I wrote a graph like R glmnet in Python for sparse modeling in Lasso
To execute a Python enumerate function in JavaScript
[Fundamental Information Technology Engineer Examination] I wrote a linear search algorithm in Python.
Get the caller of a function in Python
I want to create a window in Python
I tried playing a typing game in Python
I wrote "Introduction to Effect Verification" in Python
[Memo] I tried a pivot table in Python
I made a familiar function that can be used in statistics with Python
I wrote a design pattern in kotlin Prototype
I implemented the inverse gamma function in python
I tried adding a Python3 module in C
I wrote a Japanese parser in Japanese using pyparsing.
I made a Caesar cryptographic program in Python.
I want to embed a variable in a Python string
I want to easily implement a timeout in python
I wrote a design pattern in kotlin Factory edition
I wrote a design pattern in kotlin Builder edition
I want to write in Python! (2) Let's write a test
I wrote a design pattern in kotlin Singleton edition
I wrote a design pattern in kotlin Adapter edition
I tried to implement a pseudo pachislot in Python
I wrote a design pattern in kotlin, Iterator edition
I want to randomly sample a file in Python
I want to work with a robot in python.
[Python, ObsPy] I wrote a beach ball with Matplotlib + ObsPy
I wrote a design pattern in kotlin Template edition
I implemented a Vim-like replacement command in Slackbot #Python
What does the last () in a function mean in Python?
I wrote python3.4 in .envrc with direnv and allowed it, but I got a syntax error
I also tried to imitate the function monad and State monad with a generator in Python
I wrote a doctest in "I tried to simulate the probability of a bingo game with Python"
I made a simple typing game with tkinter in Python
I tried to implement a one-dimensional cellular automaton in Python
A function that divides iterable into N pieces in Python
I wrote a program quickly to study DI with Python ①
[Python] I want to get a common set between numpy
I made a quick feed reader using feedparser in Python
I tried "a program that removes duplicate statements in Python"
I tried "How to get a method decorated in Python"
I wrote an empty directory automatic creation script in Python
To return char * in a callback function using ctypes in Python
[python] Manage functions in a dictionary (command table, function table, function pointer)
I created a class in Python and tried duck typing