Wednesday, 16 January 2019

Extracting EPSG from a raster using gdal bindings in Python



My goal is to check that a shapefile and raster have the same projection and datum using EPSG number.


One can easily extract EPSG number from a shapefile by the following:



ds=ogr.Open(r'....satates48.shp')
utm_sr=ds.GetSpatialReference()
utm_sr.GetAttrValue('AUTHORITY',1)

This works great but how does one do the same for a raster file, you cannot, to my knowledge get a spatial reference of a raster.


One can get projection, or projecitonref (I am not sure if there is any difference), but you cannot do more, like:


fn_raster=gdal.open(r'raster_file.tif')
raster_sr=fn_raster.GetProjection().GetAttrValue('AUTHORITY',1)

This does not work. Perhaps there is an alternative way to do this?




Answer



I found the following workaround. I am unsure if it is the most efficient, but it does work for me.


import gdal
import osr

path = r"C:\temp\test2.tif"
d = gdal.Open(path)
proj = osr.SpatialReference(wkt=d.GetProjection())
print(proj.GetAttrValue('AUTHORITY',1))


EDIT: Slightly more condensed


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...