[Python] What can I do to make this Perlin noise generator more efficient?

Discussão em 'Python' iniciado por Stack, Julho 19, 2025.

  1. Stack

    Stack Membro Participativo

    from PIL import Image
    import math
    import numpy
    import random

    random.seed(10)

    a = 2000

    br = 200

    grad = []

    for i in range(int(a/br)+1):
    row = []
    for j in range(int(a/br)+1):
    row.append([random.randint(-1,1),random.randint(-1,1)])
    grad.append(row)

    def wt(a,b,w):

    return (b - a) * ((w * (w * 6.0 - 15.0) + 10.0) * w * w * w) + a

    #return (b - a) * w + a

    #return (b - a) * (3.0 - w * 2.0) * w * w + a

    def graddotproduct(x,y,dx,dy):

    return( ( grad[y][x][0] * dx) + (grad[y][x][1] * dy) )

    def perlin(x,y,numpix):

    x0 = int(math.floor(x))
    x1 = x0 + 1
    y0 = int(math.floor(y))
    y1 = y0 + 1

    sx0 = x - x0
    sx1 = x - x1
    sy0 = y - y0
    sy1 = y - y1

    d1 = [sx0,sy0]
    d2 = [sx1,sy0]
    d3 = [sx0,sy1]
    d4 = [sx1,sy1]

    dot1 = graddotproduct(x0,y0,sx0,sy0)
    dot2 = graddotproduct(x1,y0,sx1,sy0)
    dot3 = graddotproduct(x0,y1,sx0,sy1)
    dot4 = graddotproduct(x1,y1,sx1,sy1)

    ix0 = wt(dot1,dot2,sx0)
    ix1 = wt(dot3,dot4,sx0)

    avrg = wt(ix0,ix1,sy0)

    return avrg

    img = Image.new( 'RGB', (a,a), "black")
    pixels = img.load()

    for x in range(a):
    for y in range(a):
    perll = perlin(x/br,y/br,a)
    pixels[x,y] = (int((perll+1)*128),int((perll+1)*128),int((perll+1)*128))

    img.show()
    img.save("vector.png")


    I made this by following a Wiki article about Perlin noise that implemented it in C. The creator of the wiki article implemented their own random number generation, but I didn't understand it well enough to replicate it in Python, so I resorted to using Python's 'Random' module.

    The Wiki article: https://en.wikipedia.org/wiki/Perlin_noise

    The code usually takes around 10-15 seconds to produce the image. Which is quite slow compared to noise generators used by other applications such as Blender or Unity.

    Continue reading...

Compartilhe esta Página