Ask Your Question
2

How to use numpy to generate 2D perlin noise?

asked 2023-05-18 09:31:32 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-05-18 09:44:02 +0000

david gravatar image

To use numpy to generate 2D perlin noise, you can follow these steps:

Step 1: Install numpy If you do not have numpy installed, you can install it using pip:

pip install numpy

Step 2: Define the gradient vectors In Perlin noise, gradient vectors are needed to calculate the dot product of the distance and gradient. You can generate gradient vectors using numpy.random.rand() and normalize them using numpy.linalg.norm().

Here's an example of generating gradient vectors for a 2D grid:

import numpy as np def generate_gradient(shape): return np.random.rand(*shape, 2) * 2 - 1 gradient = generate_gradient((128, 128)) 

Step 3: Define the interpolation function Perlin noise uses a smooth interpolation function to create a smooth transition between values. You can use the cubic interpolation function for this purpose:

def smoothstep(x): return 6*x**5 - 15*x**4 + 10*x**3 def interp(x, a, b): return a + smoothstep(x) * (b-a) 

Step 4: Calculate the dot product of distance and gradient vectors For each point in the 2D grid, calculate the dot product of the distance vector and the gradient vector at the nearby grid points. The dot product can be calculated using numpy.tensordot() function.

def perlin(x, y, gradient): x0, y0 = int(x), int(y) x1, y1 = x0 + 1, y0 + 1 dx0, dy0 = x - x0, y - y0 dx1, dy1 = dx0 - 1, dy0 - 1 # Dot products of distance vectors and gradient vectors dot00 = np.tensordot(gradient[y0, x0], [dx0, dy0], axes=(-1)) dot01 = np.tensordot(gradient[y1, x0], [dx0, dy1], axes=(-1)) dot10 = np.tensordot(gradient[y0, x1], [dx1, dy0], axes=(-1)) dot11 = np.tensordot(gradient[y1, x1], [dx1, dy1], axes=(-1)) return interp(dy0, interp(dx0, dot00, dot10), interp(dx0, dot01, dot11)) 

Step 5: Generate the noise map You can generate the 2D perlin noise map by looping through each point in the grid and calling the perlin() function. Here's an example:

size = 512 scale = 64 gradient = generate_gradient((size + 1, size + 1)) perlin_map = np.zeros((size, size)) for y in range(size): for x in range(size): perlin_map[y, x] = perlin(x/scale, y/scale, gradient) # Normalize ...
(more)
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-18 09:31:32 +0000

Seen: 16 times

Last updated: May 18 '23