sábado, 18 de noviembre de 2017

Rasterizando con el modulo GDAL/OGR de Python modificando el valor por defecto para los nodata values

En el post anterior se consideró la rasterización de capas vectoriales, con uno o varios rasgos, donde el valor por defecto más allá de éstos era cero. Para modificarlo hay que emplear el método 'Fill' del módulo gdal y posteriormente el método 'SetNoDataValue' para fijar los nodata values.

El código a continuación emplea estos aspectos.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from osgeo import gdal, ogr

tileHdl = "/home/zeito/pyqgis_data/aleatorio.tif"
tempRasterPath = "/home/zeito/pyqgis_data/"
tileName = "aleatorio"

vector_layer = "/home/zeito/pyqgis_data/buildingPolys.shp"

# open the raster layer and get its relevant properties
tileHdl = gdal.Open(raster_layer, gdal.GA_ReadOnly)

tileGeoTransformationParams = tileHdl.GetGeoTransform()
projection = tileHdl.GetProjection()

rasterDriver = gdal.GetDriverByName('GTiff')

buildingPolys_ds = ogr.Open(vector_layer)
buildingPolys = buildingPolys_ds.GetLayer()

# Create the destination data source
tempSource = rasterDriver.Create(tempRasterPath + tileName + "_Building.tif", 
                                 tileHdl.RasterXSize, 
                                 tileHdl.RasterYSize,
                                 1, #missed parameter (band)
                                 gdal.GDT_Float32)

tempSource.SetGeoTransform(tileGeoTransformationParams)
tempSource.SetProjection(projection)
tempTile = tempSource.GetRasterBand(1)
tempTile.Fill(-999)
tempTile.SetNoDataValue(-999)

gdal.RasterizeLayer(tempSource, [1], buildingPolys, options=["ATTRIBUTE=value"])
tempSource = None

Se probó con las capas vectorial y ráster de la imagen siguiente:


y cuando se ejecutó el resultado esperado puede observarse en la imagen a continuación. En la Metadata de la "Layers Properties" del ráster se visualiza que los nodata values fueron establecidos al valor requerido de -999.

No hay comentarios: