[GIS] How to convert vector format (geopackage, shapefile) to raster format (geotiff) using rasterio without template raster

geocubepythonrasterrasteriovector

I'm looking to create a raster given just a geopackage (or shapefile, or other vector format). I don't have a template raster, and all I wish to do is burn the shapes into a raster using rasterio. Without the template raster, I'm uncertain how to generate the required inputs (transform, mainly). I'd rather not construct it by hand.

Best Answer

Rasterio provides a from_bounds method that generates an affine transform for you.

import rasterio
from rasterio.features import rasterize
from rasterio.transform import from_bounds
import geopandas as gpd

# Load some sample data
#  ECOWAS region (West Africa) - Hydropower potential and River network 
df = gpd.read_file('https://energydata.info/dataset/303a502d-ab18-42ee-a795-f50934c8887c/resource/b7dfd123-e167-4afb-a062-1f64111fd626/download/rivernetworkhydropowerstudyecowas.gpkg')
# lose a bit of resolution, but this is a fairly large file, and this is only an example.
shape = 1000, 1000
transform = rasterio.transform.from_bounds(*df['geometry'].total_bounds, *shape)
rasterize_rivernet = rasterize(
    [(shape, 1) for shape in df['geometry']],
    out_shape=shape,
    transform=transform,
    fill=0,
    all_touched=True,
    dtype=rasterio.uint8)

with rasterio.open(
    'rasterized-results.tif', 'w',
    driver='GTiff',
    dtype=rasterio.uint8,
    count=1,
    width=shape[0],
    height=shape[1],
    transform=transform
) as dst:
    dst.write(rasterize_rivernet, indexes=1)

vector-input raster-output

Related Question