rasterizing vector, where output raster should contain vector's attribute as its unique values

43 Views Asked by At

I am trying to rasterize a Shapefile using a particular attribute 'ID' of shapefile using python. My Shapefile consists of polygons have different ID. I am able to rasterize but outcome what I want should come with unique discrete values as per polygons ID values.

Code what I am using is as below:

    input_shp = ogr.Open(vector)
    source_layer = input_shp.GetLayer()
    defn = source_layer.GetLayerDefn()
    column_names = []

    for n in range(defn.GetFieldCount()):
        fdefn = defn.GetFieldDefn(n)
        column_names.append(fdefn.name)
         
    out_tif = "test_mask2" + "\\" + os.path.basename(vector).replace(".shp", ".tif")
    pixel_size = 0.059960938
    xmin, xmax, ymin, ymax = source_layer.GetExtent()
    print(source_layer.GetExtent())
    x_res = int(round((xmax-xmin)/pixel_size))
    y_res = int(round((ymax-ymin)/pixel_size))
    print(x_res, y_res)
    
    target_ds = gdal.GetDriverByName(str('GTiff')).Create(out_tif,x_res,y_res,1,gdal.GDT_Float32,['COMPRESS=LZW'])
    spatial_reference = source_layer.GetSpatialRef()
    target_ds.SetProjection(spatial_reference.ExportToWkt())
    target_ds.SetGeoTransform((xmin,pixel_size,0.0,ymax,0.0,-pixel_size))
    gdal.RasterizeLayer(target_ds, [1], source_layer, None, None, [1], options = ['ALL_TOUCHED=TRUE', 'ATTRIBUTE=Id'])
    target_ds.FlushCache()

here is one shapefile for example to make my question clear

shapefile with ID 1, 0, 1

output raster, it has all the ID values but still looks like this

this is what I want to generate using python, a raster with unique ID values (this I have generated through ArcMap)

0

There are 0 best solutions below