dem数据生成地形图python
时间: 2023-09-23 21:07:11 浏览: 155
基于DEM的数字地形建模
4星 · 用户满意度95%
生成地形图的方法有很多种,其中一种比较常见的方法是使用Perlin噪声算法。
Perlin噪声算法是一种生成连续、自然的随机数序列的算法,它可以用来生成地形高度图。以下是一个利用Perlin噪声算法生成地形高度图的Python代码示例:
```python
import numpy as np
from PIL import Image
def perlin_noise_2d(shape, res):
def f(t):
return 6*t**5 - 15*t**4 + 10*t**3
delta = (res[0] / shape[0], res[1] / shape[1])
d = (shape[0] // res[0], shape[1] // res[1])
grid = np.mgrid[0:res[0]:delta[0],0:res[1]:delta[1]].transpose(1, 2, 0) % 1
# Gradients
angles = 2*np.pi*np.random.rand(res[0]+1, res[1]+1)
gradients = np.dstack((np.cos(angles), np.sin(angles)))
g00 = gradients[0:-1,0:-1].repeat(d[0], 0).repeat(d[1], 1)
g10 = gradients[1: ,0:-1].repeat(d[0], 0).repeat(d[1], 1)
g01 = gradients[0:-1,1: ].repeat(d[0], 0).repeat(d[1], 1)
g11 = gradients[1: ,1: ].repeat(d[0], 0).repeat(d[1], 1)
# Ramps
n00 = np.sum(np.dstack((grid[:,:,0] , grid[:,:,1] )) * g00, 2)
n10 = np.sum(np.dstack((grid[:,:,0]-1, grid[:,:,1] )) * g10, 2)
n01 = np.sum(np.dstack((grid[:,:,0] , grid[:,:,1]-1)) * g01, 2)
n11 = np.sum(np.dstack((grid[:,:,0]-1, grid[:,:,1]-1)) * g11, 2)
# Interpolation
t = f(grid)
n0 = n00*(1-t[:,:,0]) + t[:,:,0]*n10
n1 = n01*(1-t[:,:,0]) + t[:,:,0]*n11
return np.sqrt(2)*((1-t[:,:,1])*n0 + t[:,:,1]*n1)
# Generate terrain height map
terrain = perlin_noise_2d((512, 512), (64, 64))
# Scale values to range [0, 255]
terrain = (terrain - terrain.min()) / (terrain.max() - terrain.min()) * 255
# Convert terrain height map to image
terrain_image = Image.fromarray(terrain.astype('uint8'), mode='L')
# Save image
terrain_image.save('terrain.png')
```
该代码会生成一个大小为512x512的地形高度图,分辨率为64x64。你可以调整`shape`和`res`参数来生成不同大小、分辨率的地形高度图。
阅读全文