Search code examples
pythongeopandaspython-xarrayshapelyrasterizing

How can I rasterize vector data (line) and interpolate values along line in python?


I would like to rasterize a line vector. The raster values must be interpolated between a "from" and "to" value.

The example is down here. I would like to rasterize the line in the GeoDataFrame and the values of the raster should go from 5 to 2 (interpolated).

import geopandas as gpd
from shapely.geometry import LineString

# example line
line = LineString([(10.00, 20.00), (20.00, 50.00)])
line_gdf = gpd.GeoDataFrame([line], geometry=[line])
line_gdf['from'] = 5
line_gdf['to'] = 2

The expected outcome is like this: example raster

The line is visible in black. The raster should only have values where the line crossing the cells. The values should be interpolated from a "from-value" to a "to-value", as is shown in the example raster (cells marked with a red outline). Preferably a DataArray (xarray).


Solution

  • You need to use Bresenham’s algorithm: https://en.wikipedia.org/wiki/Bresenham_line_algorithm

    You’ll find a Python implementation here: https://pypi.org/project/bresenham/