Advertisement
pacho_the_python

perlin

Mar 27th, 2024
23
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. def perlin_noise(width, height, scale=100):
  2. # Generate random gradient vectors
  3. gradient_vectors = np.random.randn(height, width, 2)
  4.  
  5. # Generate coordinate grid
  6. x = np.linspace(0, 1, width, endpoint=False)
  7. y = np.linspace(0, 1, height, endpoint=False)
  8. x_grid, y_grid = np.meshgrid(x, y)
  9.  
  10. # Scale the grid to the desired frequency
  11. x_grid_scaled = x_grid * scale
  12. y_grid_scaled = y_grid * scale
  13.  
  14. # Compute integer coordinates for the corners of the grid cell
  15. x0 = x_grid_scaled.astype(int)
  16. y0 = y_grid_scaled.astype(int)
  17. x1 = x0 + 1
  18. y1 = y0 + 1
  19.  
  20. # Compute fractional part of the coordinates
  21. dx = x_grid_scaled - x0
  22. dy = y_grid_scaled - y0
  23.  
  24. # Compute dot products between gradient vectors and offsets
  25. dot_top_left = np.sum(gradient_vectors[y0, x0] * np.dstack((dx, dy)), axis=2)
  26. dot_top_right = np.sum(gradient_vectors[y0, x1] * np.dstack((dx - 1, dy)), axis=2)
  27. dot_bottom_left = np.sum(gradient_vectors[y1, x0] * np.dstack((dx, dy - 1)), axis=2)
  28. dot_bottom_right = np.sum(gradient_vectors[y1, x1] * np.dstack((dx - 1, dy - 1)), axis=2)
  29.  
  30. # Interpolate along x-axis
  31. weight_x = 6 * dx**5 - 15 * dx**4 + 10 * dx**3
  32. dot_top = dot_top_left + weight_x * (dot_top_right - dot_top_left)
  33. dot_bottom = dot_bottom_left + weight_x * (dot_bottom_right - dot_bottom_left)
  34.  
  35. # Interpolate along y-axis
  36. weight_y = 6 * dy**5 - 15 * dy**4 + 10 * dy**3
  37. dot_interp = dot_top + weight_y * (dot_bottom - dot_top)
  38.  
  39. return dot_interp
  40.  
  41. # Example usage
  42. width, height = 100, 100
  43. scale = 10
  44. noise = perlin_noise(width, height, scale)
  45.  
  46. # Example visualization using Matplotlib
  47. import matplotlib.pyplot as plt
  48. plt.imshow(noise, cmap='gray', origin='lower')
  49. plt.colorbar()
  50. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement