1 year ago

#217760

test-img

Red Wizard

Perlin noise generator isn't working, doesn't look smooth

I watched some tutorials and tried to create a Perlin noise generator in python. It takes in a tuple for the number of vectors in the x and y directions and a scale for the distance in pixels between the arrays, then calculates the dot product between each pixel and each of the 4 arrays surrounding it, It then interpolates them bilinearly to get the pixel's value.

here's the code:

from PIL import Image
import numpy as np

scale = 16
size = np.array([8, 8])
vectors = []

for i in range(size[0]):
    for j in range(size[1]):
        rand = np.random.rand() * 2 * np.pi
        vectors.append(np.array([np.cos(rand), np.sin(rand)]))

interpolated_map = np.zeros(size * scale)

def interpolate(x1, x2, w):
    t = (w % scale) / scale
    return (x2 - x1) * t + x1

def dot_product(a, b):
    return a[0] * b[0] + a[1] * b[1]

for i in range(size[1] * scale):
    for j in range(size[0] * scale):
        dot_products = []
        for m in range(4):
            corner_vector_x = round(i / scale) + (m % 2)
            corner_vector_y = round(j / scale) + int(m / 2)
            x = i - corner_vector_x * scale
            y = j - corner_vector_y * scale
            if corner_vector_x >= size[0]:
                corner_vector_x = 0
            if corner_vector_y >= size[1]:
                corner_vector_y = 0
            corner_vector = vectors[corner_vector_x + corner_vector_y * (size[0])]
            distance_vector = np.array([x, y])
            dot_products.append(dot_product(corner_vector, distance_vector))
        x1 = interpolate(dot_products[0], dot_products[1], i)
        x2 = interpolate(dot_products[2], dot_products[3], i)
        interpolated_map[i][j] = (interpolate(x1, x2, j) / 2 + 1) * 255

img = Image.fromarray(interpolated_map)

img.show()

I'm getting this image: enter image description here

but I should be getting this: enter image description here

I don't know what's going wrong, I've tried watching multiple different tutorials, reading a bunch of different articles, but the result is always the same.

python

noise

perlin-noise

noise-generator

0 Answers

Your Answer

Accepted video resources