我构建了一个python脚本,用于从shapefile构造geotiff栅格。目前生成的geotiff不包含shapefile的空间参考。如何将shapefile中的空间参考复制到geotiff?我尝试通过以下命令将shapefile的空间参考复制到geotiff:target_ds.SetProjection(source_layer.GetSpatialRef())
我认为与shapefile相关联的空间参考对象与geotiff不同,但是,不知道如何从一个到另一个。
# This code creates a raster from a shapefile.
# Every feature in the shapefile is included in the raster.
import os
import gdal
import ogr
os.chdir(r'C:\Users\pipi\Documents\Rogaine\Tarlo\gpx') #folder containing gpx files
vector_fn = 'gpxcollection.shp' #filename of input shapefile
pixel_size = 25 #same unit as coordinates
raster_fn = 'test.tif' # Filename of the raster Tiff that will be created
#______Open's the data source and reads the extent________
source_ds = ogr.Open(vector_fn)
source_layer = source_ds.GetLayer() #returns the first layer in the data source
x_min, x_max, y_min, y_max = source_layer.GetExtent()
#______Create the destination raster file__________
x_res = int((x_max - x_min) / pixel_size)
y_res = int((y_max - y_min) / pixel_size)
# create the target raster file with 1 band
target_ds = gdal.GetDriverByName('GTiff').Create(raster_fn, x_res, y_res, 1, gdal.GDT_Byte)
target_ds.SetGeoTransform((x_min, pixel_size, 0, y_max, 0, -pixel_size))
band = target_ds.GetRasterBand(1)
#______Populates the raster file with the data from the shapefile____
gdal.RasterizeLayer(target_ds, [1], source_layer, burn_values=[1])
del target_ds #flushes data from memory. Without this you often get an empty raster.
答案 0 :(得分:0)
根据the docs,GDAL dataset.SetProjection()
方法需要众所周知的文本(WKT)或PROJ4字符串:“字符串应为OGC WKT或PROJ.4格式”。
您可以通过执行以下操作之一来实现此目的:
source_layer.GetSpatialRef().ExportToWkt()
source_layer.GetSpatialRef().ExportToProj4()