1

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.

3

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

0

A great tool for this is geocube. It will rasterize each of the columns in your geopackage (or a subset if you specify it).

Some examples of usage are listed here

It can be as simple to use as:

from geocube.api.core import make_geocube

input_geopackage = "path_to_file.gpkg"

out_grid = make_geocube(
    vector_data=input_geopackage,
    resolution=(-0.0001, 0.0001),
)

out_grid["column_name"].rio.to_raster("my_rasterized_column.tif")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.