Vector Features

Rasterio’s features module provides functions to extract shapes of raster features and to create new features by “burning” shapes into rasters: shapes() and rasterize(). These functions expose GDAL functions in a general way, using iterators over GeoJSON-like Python objects instead of GIS layers.

Extracting shapes of raster features

Consider the Python logo.

The shapes of the foreground features can be extracted like this:

import pprint
import rasterio
from rasterio import features

with'13547682814_f2e459f7a5_o_d.png') as src:
    blue =

mask = blue != 255
shapes = features.shapes(blue, mask=mask)

# Output
# pprint.pprint(next(shapes))
# ({'coordinates': [[(71.0, 6.0),
#                    (71.0, 7.0),
#                    (72.0, 7.0),
#                    (72.0, 6.0),
#                    (71.0, 6.0)]],
#   'type': 'Polygon'},
# 253)

The shapes iterator yields geometry, value pairs. The second item is the value of the raster feature corresponding to the shape and the first is its geometry. The coordinates of the geometries in this case are in pixel units with origin at the upper left of the image. If the source dataset was georeferenced, you would get similarly georeferenced geometries like this:

shapes = features.shapes(blue, mask=mask, transform=src.transform)

Burning shapes into a raster

To go the other direction, use rasterize() to burn values into the pixels intersecting with geometries.

image = features.rasterize(
            ((g, 255) for g, v in shapes),

By default, only pixels whose center is within the polygon or that are selected by Bresenham’s line algorithm will be burned in. You can specify all_touched=True to burn in all pixels touched by the geometry. The geometries will be rasterized by the “painter’s algorithm” - geometries are handled in order and later geometries will overwrite earlier values.

Again, to burn in georeferenced shapes, pass an appropriate transform for the image to be created.

image = features.rasterize(
            ((g, 255) for g, v in shapes),

The values for the input shapes are replaced with 255 in a generator expression. Areas not covered by input geometries are replaced with an optional fill value, which defaults to 0. The resulting image, written to disk like this,

        '/tmp/rasterized-results.tif', 'w',
        height=src.height) as dst:
    dst.write(image, indexes=1)

has a black background and white foreground features.