Search code examples
pythonapiattributesgdalrasterize

How to specify burn values by attribute using GDAL rasterize (python API)?


I'm using gdal.RasterizeLayer() to convert a shapefile to a GeoTiff using a GeoTiff template while burning the output values by ATTRIBUTE. What I want to output is a .tif where the burn value corresponds to the value of a given attribute. What I find is that gdal.RasterizeLayer() is burning to strange values that do not correspond to the values in my attribute field. Here's what I have currently:

    gdalformat = 'GTiff'
    datatype = gdal.GDT_Byte

    # Open Shapefile
    shapefile = ogr.Open(self.filename)
    shapefile_layer = shapefile.GetLayer()
    # Get projection info from reference image
    image = gdal.Open(ref_image, gdal.GA_ReadOnly)
    output = gdal.GetDriverByName(gdalformat).Create(output_tif, image.RasterXSize, image.RasterYSize, 1, datatype,
                                                     options=['COMPRESS=DEFLATE'])
    output.SetProjection(image.GetProjectionRef())
    output.SetGeoTransform(image.GetGeoTransform())

    # Write data to band 1
    band = output.GetRasterBand(1)
    band.SetNoDataValue(0)
    gdal.RasterizeLayer(output, [1], shapefile_layer, options=['ATTRIBUTE=FCode'])

    # Close datasets
    band = None
    output = None
    image = None
    shapefile = None

    # Build image overviews
    subprocess.call("gdaladdo --config COMPRESS_OVERVIEW DEFLATE " + output_tif + " 2 4 8 16 32 64", shell=True)

What occurs is that the output .tif correctly assigns different burn values for each attribute, but the value does not correspond to the attribute value. For example, the input attribute value FCode=46006 turns into a burn value of 182 (and it's not clear why!). I tried adding and removing the 'COMPRESS=DEFLATE' option, and adding and removing the '3D' option for gdal.RasterizeLayer(). None affect the output burn values.

You can see the input shapefile and attribute values here: input .shp

And the output, with the incorrect values, here: output raster


Solution

  • I fixed this myself by changing the type to gdal.GDT_Int32.