My understanding so far is that 'gdal' is used for raster data and 'ogr' for vector data. Given this I have been trying to rasterize a polygon data set (output raster metadata is given by a raster template). I have tried with the following piece of code, but I am afraid that there are quite a few things that are probably wrong.
from osgeo import gdal
from osgeo import ogr
#Geodatabase and Polygon Feature Class name
path_gdb = r'Z:\......\Flood_Defences.gdb'
fc = r'FloodDefences'
#Reading polygons with ogr
driver = ogr.GetDriverByName("OpenFileGDB")
gdb = driver.Open(path_gdb, 0)
flood_def = gdb.GetLayer(fc)
sr = flood_def.GetSpatialRef()
#Path to the tif file where the rasterized polygons will be stored
out_path = r'Z:\.....\raster.tif'
#Template raster and its information
template_path = r'Z:\.......template.tif'
raster = gdal.Open(template_path)
gt = raster.GetGeoTransform()
ndv = raster.GetRasterBand(1).GetNoDataValue()
proj = raster.GetProjection()
driver = raster.GetDriver().ShortName
cols = raster.RasterXSize
rows = raster.RasterYSize
count = raster.RasterCount
dtype = gdal.GetDataTypeName(raster.GetRasterBand(1).DataType)
#Rasterize polygons
gdal.Rasterize(out_path, gdb, format=driver, outputType=gdal.gdalconst.GDT_Float32,
creationOptions=['COMPRESS=LZW', 'BIGTIFF=YES', 'blockxsize=256', 'blockysize=256'],
outputSRS='EPSG:29902', layers=fc, width=cols, height=rows, xRes=gt[1], yRes=gt[5],
noData=ndv, targetAlignedPixels=True, allTouched='YES', burnValues=1)
I get the following error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-177-7fcf99466a93> in <module>
3 outputSRS='EPSG:29902', layers=fc,
4 width=cols, height=rows, xRes=gt[1], yRes=gt[5], noData=ndv,
----> 5 targetAlignedPixels=True, allTouched='YES', burnValues=1)
C:\ProgramData\Anaconda3\envs\env1\lib\site-packages\osgeo\gdal.py in Rasterize(destNameOrDestDS, srcDS, **kwargs)
1137
1138 if _is_str_or_unicode(destNameOrDestDS):
-> 1139 return wrapper_GDALRasterizeDestName(destNameOrDestDS, srcDS, opts, callback, callback_data)
1140 else:
1141 return wrapper_GDALRasterizeDestDS(destNameOrDestDS, srcDS, opts, callback, callback_data)
C:\ProgramData\Anaconda3\envs\env1\lib\site-packages\osgeo\gdal.py in wrapper_GDALRasterizeDestName(*args)
3488 def wrapper_GDALRasterizeDestName(*args):
3489 """wrapper_GDALRasterizeDestName(char const * dest, Dataset srcDS, GDALRasterizeOptions options, GDALProgressFunc callback=0, void * callback_data=None) -> Dataset"""
-> 3490 return _gdal.wrapper_GDALRasterizeDestName(*args)
3491 class GDALBuildVRTOptions(_object):
3492 """Proxy of C++ GDALBuildVRTOptions class."""
TypeError: in method 'wrapper_GDALRasterizeDestName', argument 2 of type 'GDALDatasetShadow *'
Also, neither sr nor proj seems to give the information I need about the reference system. In the end I had to hard-code it in the function call ('EPSG:29902').