I've been stuck trying to find a clean way to use a vector directly as a mask on a rasampled array. This code won't run because one mask is resampled and the other is in the raster's native resolution.

import rasterio
from rasterio.fill import fillnodata
from rasterio.mask import raster_geometry_mask
import numpy.ma as ma

downscale_factor = .5
with rasterio.open(input_path) as raster:
        if downscale_factor:
            out_shape = (int(raster.height * downscale_factor), int(raster.width * downscale_factor))
            transform = raster.transform * raster.transform.scale((raster.width / out_shape[1]), (raster.height / out_shape[0]))
            out_shape = raster.shape
            transform = raster.transform
        array = raster.read(1, out_shape=out_shape, resampling=Resampling.nearest, masked=True)
        mask = raster_geometry_mask(raster, country_mask.difference(lake_mask), invert=True)
        mask = mask[0] & ~ma.getmask(array)
array = fillnodata(array, max_search_distance=2, mask=mask, smoothing_iterations=2)

As far as I know there isn't any documented way of calling rasterio's resampling methods in the enums module directly. There also doesn't seem to be a way to specify an input shape when creating a mask from a vector. Is there a way of directly using rasterio's enums module to make sure the two masks are resampled to the output size using the same algorithms?


1 Answer 1


The Resampling enum is just a group of named integer values. There's no methods to actually do any resampling in the enum.

You can use the resampled out_shape and transform to create your mask from your vector data using rasterio.features.geometry_mask

You would need to read in your vector data and access the geometry using geopandas or fiona.

  • Thanks! I did not realize there'd be other masking methods in the features module. That works. Thank you!
    – Corey
    Commented Feb 10, 2023 at 23:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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