Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

python实现生成2D柏林噪声

  1. User

    python实现生成2D柏林噪声

  2. Assistant

    以下是一个Python程序,用于生成2D柏林噪声。它使用Python的NumPy和Matplotlib库。

    import numpy as np
    import matplotlib.pyplot as plt
    
    def generate_noise(width, height, scale):
        noise = np.zeros((width, height))
        for i in range(width):
            for j in range(height):
                noise[i][j] = np.random.uniform(-1, 1)
        return noise
    
    def interpolate(a, b, x):
        ft = x * np.pi
        f = (1 - np.cos(ft)) * 0.5
        return a * (1 - f) + b * f
    
    def smooth_noise(noise, octave):
        width, height = noise.shape
        smooth_noise = np.zeros((width, height))
    
        period = 2 ** octave
        frequency = 1 / period
    
        for i in range(width):
            x_min = int(i / period) * period
            x_max = (x_min + period) % width
            x_offset = (i - x_min) * frequency
            for j in range(height):
                y_min = int(j / period) * period
                y_max = (y_min + period) % height
                y_offset = (j - y_min) * frequency
    
                top = interpolate(noise[x_min][y_min], noise[x_max][y_min], x_offset)
                bottom = interpolate(noise[x_min][y_max], noise[x_max][y_max], x_offset)
                smooth_noise[i][j] = interpolate(top, bottom, y_offset)
    
        return smooth_noise
    
    def generate_perlin_noise(width, height, octave_count):
        noise = generate_noise(width, height, 1)
        smooth_noise = np.zeros((octave_count, width, height))
    
        for i in range(octave_count):
            smooth_noise[i] = smooth_noise(noise, i)
    
        perlin_noise = np.zeros((width, height))
        amplitude = 1
        total_amplitude = 0
    
        for octave in range(octave_count - 1, -1, -1):
            amplitude *= 0.5
            total_amplitude += amplitude
    
            for i in range(width):
                for j in range(height):
                    perlin_noise[i][j] += smooth_noise[octave][i][j] * amplitude
    
        perlin_noise /= total_amplitude
    
        return perlin_noise
    
    perlin_noise = generate_perlin_noise(512, 512, 7)
    plt.imshow(perlin_noise, cmap='gray')
    plt.show()
    

    这个程序首先定义了三个帮助函数:generate_noise、interpolate和smooth_noise。generate_noise函数用于生成随机噪声,interpolate函数用于计算两个值之间的插值,smooth_noise函数用于对噪声进行平滑处理。这三个函数都是实现柏林噪声算法的关键。接下来,使用generate_perlin_noise函数生成柏林噪声并显示它。该函数使用smooth_noise函数对随机噪声进行多次平滑处理,用于生成不同频率的噪声图像。最终,所有频率的噪声图像被组合在一起,得到最终的柏林噪声图像。