TransWikia.com

Rasterizing by attribute in rasterio

Geographic Information Systems Asked by user32882 on February 22, 2021

According to Rasterizing shapefiles with GDAL and Python? it seems that gdal allows rasterization of a layer according to a certain attribute

ds = gdal.RasterizeLayer(target_ds, [1], source_layer, options = ["ATTRIBUTE=ID"])

I would like to rasterize a layer with small square polygon geometries using rasterio

enter image description here

rasterio has a features.rasterize method (see docs), but it seems to only be able to output numpy arrays with 1’s where the polygons occur. Since rasterio is a higher level library than gdal I am a bit surprised that selecting an attribute to burn the raster with is not supported functionality.

Is there any built-in method in rasterio to burn a raster by an attribute from the original vector layer?

2 Answers

The inputs to features.rasterize include

shapes (iterable of (geometry, value) pairs or iterable over) – geometries. geometry can either be an object that implements the geo interface or GeoJSON-like object.

So you can just pass tuples of (geom, value), where value is the attribute value you wish to burn into the raster.

Correct answer by Jon on February 22, 2021

To give an example if you have col set to the column you want to rasterize

if col:
    shapes = ((geom,value) for geom, value in zip(dataframe.geometry, dataframe[col]))
else: 
    shapes = dataframe.geometry.values
    
varray = rasterize(shapes,
                   out_shape=(dst_height, dst_width),
                   transform=dst_transform,
                   fill=fill,
                   default_value=default_value,
                   all_touched=all_touched,
                   dtype=dtype)

Answered by mmann1123 on February 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP