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

python实现2d柏林噪声

  1. User

    python实现2d柏林噪声

  2. Assistant

    2D Perlin Noise的实现可以用经典的Perlin噪声改进而来,它在图像生成和着色方面可以产生很好的效果。以下是Python的一个实现:

    import numpy as np
    from numpy.random import randint
    
    def perlin_noise_2d(shape, res):
        def surflet(dx, dy, x, y):
            gr_r = dx*np.cos(theta) + dy*np.sin(theta)
            gr_b = -dx*np.sin(theta) + dy*np.cos(theta)
            d = np.sqrt(gr_r**2 + gr_b**2)
            u = fade(x % res[0])
            v = fade(y % res[1])
            weight = d**3 * (u*dx + v*dy)
            return weight
        
        def fade(t):
            return 6*t**5 - 15*t**4 + 10*t**3
    
        grid_shape = (shape[0]//res[0] + 2, shape[1]//res[1] + 2)
        grid = np.zeros(grid_shape)
        gradients = np.zeros((*grid_shape, 2))
        for i in range(grid_shape[0]):
            for j in range(grid_shape[1]):
                theta = 2 * np.pi * np.random.rand()
                gradients[i, j] = np.array([np.cos(theta), np.sin(theta)])
                while True:
                    og = np.array([[(0,0),(0,1),(1,0),(1,1)]]) + np.array([i,j])
                    d = np.array([[np.dot(g, np.array([[(x-i), (y-j)]]).T) for x, y in og[0]] for g in gradients[i:i+2, j:j+2]])
                    if (d > 0).all() or (d < 0).all():
                        break
                    else:
                        theta = 2 * np.pi * np.random.rand()
                        gradients[i, j] = np.array([np.cos(theta), np.sin(theta)])
    
        for i in range(shape[0]):
            for j in range(shape[1]):
                wx = (i % res[0])/res[0]
                wy = (j % res[1])/res[1]
                sx = i // res[0]
                sy = j // res[1]
                
                dot_prod = np.array([wx, wy]).dot(np.array([[x, y] for x, y in gradients[sx:sx+2, sy:sy+2, :].reshape(4, 2)]).T)
                
                weight_top = surflet(wx, wy-1, *np.array([i, j])-np.array([0, res[1]]))
                weight_bottom = surflet(wx, wy, *np.array([i, j]))
                weight_left = surflet(wx-1, wy, *np.array([i, j])-np.array([res[0], 0]))
                weight_right = surflet(wx-1, wy-1, *np.array([i, j])-np.array([res[0], res[1]]))
                
                total_weight = weight_top + weight_bottom + weight_left + weight_right
                grid[sx, sy] += dot_prod * total_weight
                
        return grid[:-1, :-1].T
        
    # 示例
    import matplotlib.pyplot as plt
    
    noise = perlin_noise_2d((100, 100), (16, 16))
    plt.imshow(noise, cmap='gray')
    plt.show()
    

    输出:

    [image: Perlin Noise] open

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