Read Polygon-shaped regions

Starting with rio-tiler v2, a .feature() method exists on rio-tiler's readers (e.g Reader) which enables data reading for GeoJSON defined (polygon or multipolygon) shapes.

from rio_tiler.io import Reader
from rio_tiler.models import ImageData

with Reader("my-tif.tif") as cog:
    # Read data for a given geojson polygon
    img: ImageData = cog.feature(geojson_feature, max_size=1024)  # we limit the max_size to 1024

Under the hood, the .feature method uses GDALWarpVRT's cutline option and the .part() method. The below process is roughly what .feature does for you.

from rio_tiler.io import Reader
from rio_tiler.utils import create_cutline
from rasterio.features import bounds as featureBounds

# Use Reader to open and read the dataset
with Reader("my_tif.tif") as cog:
    # Create WTT Cutline
    cutline = create_cutline(cog.dataset, feat, geometry_crs="epsg:4326")

    # Get BBOX of the polygon
    bbox = featureBounds(feat)

    # Read part of the data (bbox) and use the cutline to mask the data
    data, mask = cog.part(bbox, vrt_options={'cutline': cutline}, max_size=1024)

Another interesting fact about the cutline option is that it can be used with other methods:

bbox = featureBounds(feat)

# Use Reader to open and read the dataset
with Reader("my_tif.tif") as cog:
    # Create WTT Cutline
    cutline = create_cutline(cog.dataset, feat, geometry_crs="epsg:4326")

    # Get a preview of the whole geotiff but use the cutline to mask the data
    data, mask = cog.preview(vrt_options={'cutline': cutline})

    # Read a mercator tile and use the cutline to mask the data
    data, mask = cog.tile(1, 1, 1, vrt_options={'cutline': cutline})