Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

用python实现一个可传参frequency、lacunarity、persistence、octaves、seed的2D柏林噪声

  1. User

    用python实现一个可传参frequency、lacunarity、persistence、octaves、seed的2D柏林噪声

  2. Assistant

    下面是一个使用Python实现可传参频率、空洞、持续性、八度、种子的2D柏林噪声的示例代码:

    import numpy as np
    from numpy.random import default_rng
    
    def interpolate(x0, x1, alpha):
        return (1 - alpha) * x0 + alpha * x1
    
    def perlin_noise_2d(size, frequency, lacunarity, persistence, octaves, seed=0):
        rng = default_rng(seed)
        coords = np.mgrid[0:size[0], 0:size[1]].astype(float)
        x_scale = size[0] * frequency
        y_scale = size[1] * frequency
        noise = np.zeros(size)
        for i in range(octaves):
            x = coords[0] / x_scale
            y = coords[1] / y_scale
            xi = x.astype(int)
            yi = y.astype(int)
            x_alpha = x - xi
            y_alpha = y - yi
            
            # 以下计算四个角点的随机值
            nw = rng.random((size[0], size[1]))
            ne = rng.random((size[0], size[1]))
            sw = rng.random((size[0], size[1]))
            se = rng.random((size[0], size[1]))
            
            # 以下计算插值因子
            n = interpolate(nw, ne, x_alpha)
            s = interpolate(sw, se, x_alpha)
            interp = interpolate(n, s, y_alpha)
            
            # 以下应用改变频率、lacunarity和persistence的幂函数
            x_scale *= lacunarity
            y_scale *= lacunarity
            noise += interp * persistence ** i
        
        # 将噪声值缩放到[0, 1]之间
        return np.interp(noise, (noise.min(), noise.max()), (0, 1))
    

    运行以下代码将生成一个256x256的大小、种子为1、频率为0.02、空洞为2、持续性为0.5、八度为5的2D柏林噪声图像,可以根据需要调整参数:

    import matplotlib.pyplot as plt
    
    noise = perlin_noise_2d((256, 256), frequency=0.02, lacunarity=2, persistence=0.5, octaves=5, seed=1)
    plt.imshow(noise, cmap='gray')
    

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.