Convert between rasters and shapes#

Segmentation models produce raster masks; the rest of the pipeline works with vector shapes. Every shape type converts in both directions with from_mask / to_mask, georeferenced by the raster the mask came from.

Mask → shapes#

import rasterio
from shapelib import Lines, Points, Polygons

orto = rasterio.open("orthomosaic.tif")

# mask is a binary numpy array aligned with the raster
fields = Polygons.from_mask(mask, dataset_reader=orto)
lines = Lines.from_mask(mask, dataset_reader=orto)
plants = Points.from_mask(mask, dataset_reader=orto)

The result is a regular shapelib object — same CRS as the raster, ready for any other operation:

fields.calculate_area()
fields.save("fields.fgb")

Shapes → mask#

The other direction rasterizes the geometries into a mask aligned with the raster grid:

mask = fields.to_mask(dataset_reader=orto)
mask = lines.to_mask(dataset_reader=orto)

Useful to feed shapes back into an image pipeline or compare a prediction with a ground truth.

See also

Raster converters explains the conversion functions behind these methods and their extra parameters.