之前已经把31景DEM数据拼接完成,这篇文章,利用shapefile文件实现对山东DEM数据的裁剪。
Python、GIS基础教程:https://www.osgeo.cn/pygis/ogr-ogrintro.html
1.代码
from osgeo import gdal, gdalnumeric, ogr,gdal_array
from PIL import Image, ImageDraw
import os
import operator
gdal.UseExceptions()
# This function will convert the rasterized clipper shapefile
# to a mask for use within GDAL.
def imageToArray(i):
"""
Converts a Python Imaging Library array to a
gdalnumeric image.
"""
a = gdalnumeric.fromstring(i.tobytes(), 'b')
a.shape = i.im.size[1], i.im.size[0]
return a
def arrayToImage(a):
"""
Converts a gdalnumeric array to a
Python Imaging Library Image.
"""
i = Image.frombytes('L', (a.shape[1], a.shape[0]),
(a.astype('b')).tobytes())
return i
def world2Pixel(geoMatrix, x, y):
"""
Uses a gdal geomatrix (gdal.GetGeoTransform()) to calculate
the pixel location of a geospatial coordinate
"""
# GetGeoTransform返回值:左上角x坐标, 水平分辨率,旋转参数, 左上角y坐标,旋转参数,竖直分辨率。
ulX = geoMatrix[0]
ulY = geoMatrix[3]
xDist = geoMatrix[1] # 水平分辨率
pixel = int((x - ulX) / xDist)
line = int((ulY - y) / xDist)
return (pixel, line)
#
# EDIT: this is basically an overloaded
# version of the gdal_array.