Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def perlin_noise(width, height, scale=100):
- # Generate random gradient vectors
- gradient_vectors = np.random.randn(height, width, 2)
- # Generate coordinate grid
- x = np.linspace(0, 1, width, endpoint=False)
- y = np.linspace(0, 1, height, endpoint=False)
- x_grid, y_grid = np.meshgrid(x, y)
- # Scale the grid to the desired frequency
- x_grid_scaled = x_grid * scale
- y_grid_scaled = y_grid * scale
- # Compute integer coordinates for the corners of the grid cell
- x0 = x_grid_scaled.astype(int)
- y0 = y_grid_scaled.astype(int)
- x1 = x0 + 1
- y1 = y0 + 1
- # Compute fractional part of the coordinates
- dx = x_grid_scaled - x0
- dy = y_grid_scaled - y0
- # Compute dot products between gradient vectors and offsets
- dot_top_left = np.sum(gradient_vectors[y0, x0] * np.dstack((dx, dy)), axis=2)
- dot_top_right = np.sum(gradient_vectors[y0, x1] * np.dstack((dx - 1, dy)), axis=2)
- dot_bottom_left = np.sum(gradient_vectors[y1, x0] * np.dstack((dx, dy - 1)), axis=2)
- dot_bottom_right = np.sum(gradient_vectors[y1, x1] * np.dstack((dx - 1, dy - 1)), axis=2)
- # Interpolate along x-axis
- weight_x = 6 * dx**5 - 15 * dx**4 + 10 * dx**3
- dot_top = dot_top_left + weight_x * (dot_top_right - dot_top_left)
- dot_bottom = dot_bottom_left + weight_x * (dot_bottom_right - dot_bottom_left)
- # Interpolate along y-axis
- weight_y = 6 * dy**5 - 15 * dy**4 + 10 * dy**3
- dot_interp = dot_top + weight_y * (dot_bottom - dot_top)
- return dot_interp
- # Example usage
- width, height = 100, 100
- scale = 10
- noise = perlin_noise(width, height, scale)
- # Example visualization using Matplotlib
- import matplotlib.pyplot as plt
- plt.imshow(noise, cmap='gray', origin='lower')
- plt.colorbar()
- plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement