python - 如何制作更平滑的 Perlin 噪声发生器?

标签 python random perlin-noise

我正在尝试使用 Perlin 噪声发生器来制作 map 的图 block ,但我注意到我的噪声太尖锐了,我的意思是,它有太多的高程,没有平坦的地方,而且它们看起来不像像山脉、岛屿、湖泊或任何东西;它们看起来过于随机并且有很多峰值。

在问题的末尾,需要进行更改才能修复它。

问题的重要代码是:

一维:

def Noise(self, x):     # I wrote this noise function but it seems too random
    random.seed(x)
    number = random.random()
    if number < 0.5:
        final = 0 - number * 2
    elif number > 0.5:
        final = number * 2
    return final

 def Noise(self, x):     # I found this noise function on the internet
    x = (x<<13) ^ x
    return ( 1.0 - ( (x * (x * x * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0)

二维:

def Noise(self, x, y):     # I wrote this noise function but it seems too random
    n = x + y
    random.seed(n)
    number = random.random()
    if number < 0.5:
        final = 0 - number * 2
    elif number > 0.5:
        final = number * 2
    return final

def Noise(self, x, y):     # I found this noise function on the internet
    n = x + y * 57
    n = (n<<13) ^ n
    return ( 1.0 - ( (x * (x * x * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0)

我在代码中留下了 1D 和 2D Perlin 噪声,因为也许有人对此感兴趣: (我花了很长时间才找到一些代码,所以我想有人会很乐意在这里找到一个例子)。
您不需要 Matplotlib 或 NumPy 来制造噪音;我只是用它们来制作图表并更好地查看结果。

import random
import matplotlib.pyplot as plt              # To make graphs
from mpl_toolkits.mplot3d import Axes3D      # To make 3D graphs
import numpy as np                           # To make graphs

class D():     # Base of classes D1 and D2
    def Cubic_Interpolate(self, v0, v1, v2, v3, x):
        P = (v3 - v2) - (v0 - v1)
        Q = (v0 - v1) - P
        R = v2 - v0
        S = v1
        return P * x**3 + Q * x**2 + R * x + S

class D1(D):
    def __init__(self, lenght, octaves):
        self.result = self.Perlin(lenght, octaves)
    
    def Noise(self, x):     # I wrote this noise function but it seems too random
        random.seed(x)
        number = random.random()
        if number < 0.5:
            final = 0 - number * 2
        elif number > 0.5:
            final = number * 2
        return final

    def Noise(self, x):     # I found this noise function on the internet
        x = (x<<13) ^ x
        return ( 1.0 - ( (x * (x * x * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0)
        
    def Perlin(self, lenght, octaves):
        result = []
        for x in range(lenght):
            value = 0
            for y in range(octaves):
                frequency = 2 ** y
                amplitude = 0.25 ** y            
                value += self.Interpolate_Noise(x * frequency) * amplitude
            result.append(value)
            print(f"{x} / {lenght} ({x/lenght*100:.2f}%): {round(x/lenght*10) * '#'} {(10-round(x/lenght*10)) * ' '}. Remaining {lenght-x}.")     # I don't use `os.system('cls')` because it slow down the code.
        return result

    def Smooth_Noise(self, x):
        return self.Noise(x) / 2 + self.Noise(x-1) / 4 + self.Noise(x+1) / 4

    def Interpolate_Noise(self, x):
        round_x = round(x)
        frac_x  = x - round_x
        v0 = self.Smooth_Noise(round_x - 1)
        v1 = self.Smooth_Noise(round_x)
        v2 = self.Smooth_Noise(round_x + 1)
        v3 = self.Smooth_Noise(round_x + 2)
        return self.Cubic_Interpolate(v0, v1, v2, v3, frac_x)
            
    def graph(self, *args):
        plt.plot(np.array(self.result), '-', label = "Line")
        for x in args:
            plt.axhline(y=x, color='r', linestyle='-')    
        plt.xlabel('X')
        plt.ylabel('Y')
        plt.title("Simple Plot")
        plt.legend()
        plt.show()

class D2(D):
    def __init__(self, lenght, octaves = 1):
        
        self.lenght_axes = round(lenght ** 0.5)
        self.lenght = self.lenght_axes ** 2
        
        self.result = self.Perlin(self.lenght, octaves)

    def Noise(self, x, y):     # I wrote this noise function but it seems too random
        n = x + y
        random.seed(n)
        number = random.random()
        if number < 0.5:
            final = 0 - number * 2
        elif number > 0.5:
            final = number * 2
        return final

    def Noise(self, x, y):     # I found this noise function on the internet
        n = x + y * 57
        n = (n<<13) ^ n
        return ( 1.0 - ( (x * (x * x * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0)
    
    def Smooth_Noise(self, x, y):
        corners = (self.Noise(x - 1, y - 1) + self.Noise(x + 1, y - 1) + self.Noise(x - 1, y + 1) + self.Noise(x + 1, y + 1) ) / 16
        sides   = (self.Noise(x - 1, y) + self.Noise(x + 1, y) + self.Noise(x, y - 1)  + self.Noise(x, y + 1) ) /  8
        center  =  self.Noise(x, y) / 4
        return corners + sides + center
    
    def Interpolate_Noise(self, x, y):

        round_x = round(x)
        frac_x  = x - round_x

        round_y = round(y)
        frac_y  = y - round_y

        v11 = self.Smooth_Noise(round_x - 1, round_y - 1)
        v12 = self.Smooth_Noise(round_x    , round_y - 1)
        v13 = self.Smooth_Noise(round_x + 1, round_y - 1)
        v14 = self.Smooth_Noise(round_x + 2, round_y - 1)
        i1 = self.Cubic_Interpolate(v11, v12, v13, v14, frac_x)

        v21 = self.Smooth_Noise(round_x - 1, round_y)
        v22 = self.Smooth_Noise(round_x    , round_y)
        v23 = self.Smooth_Noise(round_x + 1, round_y)
        v24 = self.Smooth_Noise(round_x + 2, round_y)
        i2 = self.Cubic_Interpolate(v21, v22, v23, v24, frac_x)
        
        v31 = self.Smooth_Noise(round_x - 1, round_y + 1)
        v32 = self.Smooth_Noise(round_x    , round_y + 1)
        v33 = self.Smooth_Noise(round_x + 1, round_y + 1)
        v34 = self.Smooth_Noise(round_x + 2, round_y + 1)
        i3 = self.Cubic_Interpolate(v31, v32, v33, v34, frac_x)

        v41 = self.Smooth_Noise(round_x - 1, round_y + 2)
        v42 = self.Smooth_Noise(round_x    , round_y + 2)
        v43 = self.Smooth_Noise(round_x + 1, round_y + 2)
        v44 = self.Smooth_Noise(round_x + 2, round_y + 2)
        i4 = self.Cubic_Interpolate(v41, v42, v43, v44, frac_x)
        
        return self.Cubic_Interpolate(i1, i2, i3, i4, frac_y)
    
    def Perlin(self, lenght, octaves):
        result = []
        for x in range(lenght):
            value = 0
            for y in range(octaves):
                frequency = 2 ** y
                amplitude = 0.25 ** y            
                value += self.Interpolate_Noise(x * frequency, x * frequency) * amplitude
            result.append(value)
            print(f"{x} / {lenght} ({x/lenght*100:.2f}%): {round(x/lenght*10) * '#'} {(10-round(x/lenght*10)) * ' '}. Remaining {lenght-x}.")     # I don't use `os.system('cls')` because it slow down the code.
        return result

    def graph(self, color = 'viridis'):
        # Other colors: https://matplotlib.org/examples/color/colormaps_reference.html
        fig = plt.figure()
        Z = np.array(self.result).reshape(self.lenght_axes, self.lenght_axes)

        ax = fig.add_subplot(1, 2, 1, projection='3d')
        X = np.arange(self.lenght_axes)
        Y = np.arange(self.lenght_axes)
        X, Y = np.meshgrid(X, Y)        
        d3 = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=color, linewidth=0, antialiased=False)
        fig.colorbar(d3)

        ax = fig.add_subplot(1, 2, 2)
        d2 = ax.imshow(Z, cmap=color, interpolation='none')
        fig.colorbar(d2)
               
        plt.show()

问题是输出似乎不适合 map 。

使用以下命令查看此输出:

test = D2(1000, 3)
test.graph()

enter image description here

我正在寻找更流畅的东西。

也许在 2D 噪声中很难注意到我在说什么,但在 1D 中就容易多了:

test = D1(1000, 3)
test.graph()

enter image description here

来自互联网的噪声函数的峰值略小且频率较低,但仍然太多。我正在寻找更流畅的东西。

可能是这样的:
enter image description here

或者这个:
enter image description here

P.S:我根据this pseudocode做了这个.

编辑:

皮卡莱克:

enter image description here

即使值很低,它也有峰值,没有曲线或平滑/平坦的线条。

geza:解决方案

感谢geza's suggestions我找到了解决问题的方法:

def Perlin(self, lenght_axes, octaves, zoom = 0.01, amplitude_base = 0.5):
    result = []
    
    for y in range(lenght_axes):
        line = []
        for x in range(lenght_axes):
            value = 0
            for o in range(octaves):
                frequency = 2 ** o
                amplitude = amplitude_base ** o
                value += self.Interpolate_Noise(x * frequency * zoom, y * frequency * zoom) * amplitude
            line.append(value)
        result.append(line)
        print(f"{y} / {lenght_axes} ({y/lenght_axes*100:.2f}%): {round(y/lenght_axes*20) * '#'} {(20-round(y/lenght_axes*20)) * ' '}. Remaining {lenght_axes-y}.")
    return result

其他修改是:

  • Z = np.array(self.result) 而不是这个 Z = np.array(self.result).reshape(self.lenght_axes, self.lenght_axes)在图形函数中。
  • Interpolate_Noise 中使用 math.floor()(记住 import math)而不是 round()round_xround_y 变量中运行。
  • Noise(第二个)中的 return 行修改为 return ( 1.0 - ( (n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff)/1073741824.0)D2(10000, 10) enter image description here 现在唯一奇怪的是山脉(黄色)总是靠近同一个地方,但我认为这是改变 Noise 函数中的数字的问题。

最佳答案

我在您的代码中发现了这些错误:

  • 您需要乘以 Interpolate_Noise 参数,以“放大” map (例如,将 x 乘以 0.01)。如果您在 1D 情况下执行此操作,您会发现生成的函数已经好得多了
  • 将 Octave 数从 3 增加到更大(3 个 Octave 不会产生太多细节)
  • 使用振幅 0.5^octave,而不是 0.25^octave(但你可以使用这个参数,所以 0.25 本质上并不坏,但它没有提供太多细节)
  • 对于 2D 情况,您需要有 2 个外部循环(一个用于水平,一个用于垂直。当然,您仍然需要有 Octave 循环)。因此,您需要使用水平和垂直位置正确地“索引”噪声,而不仅仅是 xx
  • 完全去除平滑。 Perlin 噪声不需要它。
  • 2D 噪声函数有一个错误:它在返回表达式中使用 x 而不是 n
  • 在三次插值中,您使用 round 而不是 math.floor

这是我的一个答案,带有类似 Perlin 的简单 (C++) 实现(它不是正确的 perlin)噪声:https://stackoverflow.com/a/45121786/8157187

关于python - 如何制作更平滑的 Perlin 噪声发生器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47837968/

相关文章:

c++ - 来自两个列表的随机对

algorithm - 为什么单纯形噪声似乎比经典的 Perlin 噪声具有*更多*伪像?

python - 从 python 生成 MATLAB 代码

python - 在 xpath 中转义引号(python 脚本)

python - 按住一个键并释放另一个

python - 为什么 setup.py 安装旧文件?

java - 在java中用随机值填充矩阵的空单元

JavaScript .onchange?

GLSL 的随机/噪声函数

algorithm - 如何在球面上生成 Perlin 噪声?