How to copy the spatial reference from a shapefile to a geotiff raster?

Question:

I have constructed a python script that constructs a geotiff raster from a shapefile. At present the geotiff produced does not contain the spatial reference of the shapefile. How do I copy the spatial reference from the shapefile to the geotiff? I have tried copying the spatial reference of the shapefile to the geotiff via the command: target_ds.SetProjection(source_layer.GetSpatialRef())
I think that the spatial reference object associated with the shapefile is different to the geotiff, but, don’t know how to go from one to the other.

# 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:UserspipiDocumentsRogaineTarlogpx')  #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.
Asked By: Philip Whitten

||

Answers:

The GDAL dataset.SetProjection() method expects well-known text (WKT) or PROJ4 strings, as per the docs: "The string should be in OGC WKT or PROJ.4 format".

You can achieve this by doing one of the following:

source_layer.GetSpatialRef().ExportToWkt()
source_layer.GetSpatialRef().ExportToProj4()
Answered By: Benjamin
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.