Python的噪声库中的Perlin噪声

5

我在生成我的项目的Perlin噪声方面遇到了问题。因为我想了解如何正确使用库,所以我尝试逐步跟随这个页面:https://medium.com/@yvanscher/playing-with-perlin-noise-generating-realistic-archipelagos-b59f004d8401。 在第一部分中,有如下代码:

import noise
import numpy as np
from scipy.misc import toimage

shape = (1024,1024)
scale = 100.0
octaves = 6
persistence = 0.5
lacunarity = 2.0

world = np.zeros(shape)
for i in range(shape[0]):
    for j in range(shape[1]):
        world[i][j] = noise.pnoise2(i/scale, 
                                    j/scale, 
                                    octaves=octaves, 
                                    persistence=persistence, 
                                    lacunarity=lacunarity, 
                                    repeatx=1024, 
                                    repeaty=1024, 
                                    base=0)

toimage(world).show()

我复制并粘贴了代码,并在结尾处做了一些小改动(toimage已过时),所以我的代码如下:
import noise
import numpy as np
from PIL import Image

shape = (1024,1024)
scale = 100
octaves = 6
persistence = 0.5
lacunarity = 2.0
seed = np.random.randint(0,100)

world = np.zeros(shape)
for i in range(shape[0]):
    for j in range(shape[1]):
        world[i][j] = noise.pnoise2(i/scale,
                                    j/scale,
                                    octaves=octaves,
                                    persistence=persistence,
                                    lacunarity=lacunarity,
                                    repeatx=1024,
                                    repeaty=1024,
                                    base=seed)

Image.fromarray(world, mode='L').show()

我尝试了许多不同的模式,但这种噪声与相干噪声并不接近。我的结果类似于这个(模式='L')。有人可以解释一下我做错了什么吗?

2个回答

3
这里是可运行的代码。我稍微整理了一下。详见注释。最后建议:在测试代码时,使用matplotlib进行可视化。它的imshow()函数比PIL更加稳健。
import noise
import numpy as np
from PIL import Image

shape = (1024,1024)
scale = .5
octaves = 6
persistence = 0.5
lacunarity = 2.0
seed = np.random.randint(0,100)

world = np.zeros(shape)

# make coordinate grid on [0,1]^2
x_idx = np.linspace(0, 1, shape[0])
y_idx = np.linspace(0, 1, shape[1])
world_x, world_y = np.meshgrid(x_idx, y_idx)

# apply perlin noise, instead of np.vectorize, consider using itertools.starmap()
world = np.vectorize(noise.pnoise2)(world_x/scale,
                        world_y/scale,
                        octaves=octaves,
                        persistence=persistence,
                        lacunarity=lacunarity,
                        repeatx=1024,
                        repeaty=1024,
                        base=seed)

# here was the error: one needs to normalize the image first. Could be done without copying the array, though
img = np.floor((world + .5) * 255).astype(np.uint8) # <- Normalize world first
Image.fromarray(img, mode='L').show()

2
如果有人跟随我,使用Noise Library时你应该进行规范化处理。
img = np.floor((world + 1) * 127).astype(np.uint8)

这样做就不会出现与应该相反的异常颜色斑点。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接