Created
May 18, 2021 07:30
-
-
Save JustinSDK/aea5a7aa170eb36b25d0f5194018af5a to your computer and use it in GitHub Desktop.
Perlin 雜訊與傅立葉轉換
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
from math import floor | |
from random import randint | |
import matplotlib.pyplot as plt | |
def blending(t): | |
return 6 * (t ** 5) - 15 * (t ** 4) + 10 * (t ** 3) | |
blending = np.frompyfunc(blending, 1, 1) | |
def lerp(s1, s2, t): | |
return s1 + t * (s2 - s1) | |
lerp = np.frompyfunc(lerp, 3, 1) | |
def grad1(n, s): | |
return s if n % 2 == 0 else -s | |
grad1 = np.frompyfunc(grad1, 2, 1) | |
np.random.seed(10) # 為了每次取得相同雜訊,這邊設定了亂數種子 | |
rand_table = np.random.randint(255, size = 256) | |
def perlin1(x): | |
xi = np.floor(x) | |
s = x - xi | |
a = rand_table[(xi % 256).astype(np.int)] | |
b = rand_table[((xi + 1) % 256).astype(np.int)] | |
return lerp(grad1(a, s), grad1(b, s - 1), blending(s)) # 全部的雜訊 | |
def singal(t, sample_rate): | |
noise_level = 10 # 雜訊的變化程度 | |
x = np.linspace(0, noise_level * t, int(t * sample_rate), endpoint = False) | |
return perlin1(x) | |
t = 2 | |
sample_rate = 800 | |
samples = singal(t, sample_rate) | |
x = np.linspace(0, t, int(t * sample_rate), endpoint = False) | |
plt.title('Perlin noise') | |
plt.xlabel('x') | |
plt.ylabel('y') | |
plt.gca().set_aspect(1) | |
plt.plot(x, samples) | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment