Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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 to [0, 1] perlin_map = (perlin_map - np.min(perlin_map)) / np.ptp(perlin_map) 

This code generates a 2D perlin noise map of size (512, 512) and scales it by 64. The result is then normalized to the range [0, 1].