gpt4 book ai didi

python - 使用 numpy 产生 2D 柏林噪声

转载 作者:太空狗 更新时间:2023-10-29 22:12:34 24 4
gpt4 key购买 nike

我正在尝试使用 numpy 生成 2D perlin 噪声,但我得到的不是平滑的东西:

my broken perlin noise, with ugly squares everywhere

可以肯定的是,我在某处混淆了我的尺寸,可能是在我将四个梯度组合在一起时……但我找不到它,我的大脑现在正在融化。谁能帮我查明问题所在?

无论如何,这是代码:

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt

def perlin(x,y,seed=0):
# permutation table
np.random.seed(seed)
p = np.arange(256,dtype=int)
np.random.shuffle(p)
p = np.stack([p,p]).flatten()
# coordinates of the first corner
xi = x.astype(int)
yi = y.astype(int)
# internal coordinates
xf = x - xi
yf = y - yi
# fade factors
u = fade(xf)
v = fade(yf)
# noise components
n00 = gradient(p[p[xi]+yi],xf,yf)
n01 = gradient(p[p[xi]+yi+1],xf,yf-1)
n11 = gradient(p[p[xi+1]+yi+1],xf-1,yf-1)
n10 = gradient(p[p[xi+1]+yi],xf-1,yf)
# combine noises
x1 = lerp(n00,n10,u)
x2 = lerp(n10,n11,u)
return lerp(x2,x1,v)

def lerp(a,b,x):
"linear interpolation"
return a + x * (b-a)

def fade(t):
"6t^5 - 15t^4 + 10t^3"
return 6 * t**5 - 15 * t**4 + 10 * t**3

def gradient(h,x,y):
"grad converts h to the right gradient vector and return the dot product with (x,y)"
vectors = np.array([[0,1],[0,-1],[1,0],[-1,0]])
g = vectors[h%4]
return g[:,:,0] * x + g[:,:,1] * y

lin = np.linspace(0,5,100,endpoint=False)
y,x = np.meshgrid(lin,lin)

plt.imshow(perlin(x,y,seed=0))

最佳答案

感谢 Paul Panzer 和一夜安眠,它现在可以正常工作了......

import numpy as np
import matplotlib.pyplot as plt

def perlin(x, y, seed=0):
# permutation table
np.random.seed(seed)
p = np.arange(256, dtype=int)
np.random.shuffle(p)
p = np.stack([p, p]).flatten()
# coordinates of the top-left
xi, yi = x.astype(int), y.astype(int)
# internal coordinates
xf, yf = x - xi, y - yi
# fade factors
u, v = fade(xf), fade(yf)
# noise components
n00 = gradient(p[p[xi] + yi], xf, yf)
n01 = gradient(p[p[xi] + yi + 1], xf, yf - 1)
n11 = gradient(p[p[xi + 1] + yi + 1], xf - 1, yf - 1)
n10 = gradient(p[p[xi + 1] + yi], xf - 1, yf)
# combine noises
x1 = lerp(n00, n10, u)
x2 = lerp(n01, n11, u) # FIX1: I was using n10 instead of n01
return lerp(x1, x2, v) # FIX2: I also had to reverse x1 and x2 here

def lerp(a, b, x):
"linear interpolation"
return a + x * (b - a)

def fade(t):
"6t^5 - 15t^4 + 10t^3"
return 6 * t**5 - 15 * t**4 + 10 * t**3

def gradient(h, x, y):
"grad converts h to the right gradient vector and return the dot product with (x,y)"
vectors = np.array([[0, 1], [0, -1], [1, 0], [-1, 0]])
g = vectors[h % 4]
return g[:, :, 0] * x + g[:, :, 1] * y

lin = np.linspace(0, 5, 100, endpoint=False)
x, y = np.meshgrid(lin, lin) # FIX3: I thought I had to invert x and y here but it was a mistake

plt.imshow(perlin(x, y, seed=2), origin='upper')

关于python - 使用 numpy 产生 2D 柏林噪声,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42147776/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com