[Python] Rasterio mask result is 1 pixel larger in each dimension than the masking input

Discussão em 'Python' iniciado por Stack, Março 18, 2025.

  1. Stack

    Stack Membro Participativo

    I have 2 rasters of different sizes and I want to clip the larger raster so it matches the smaller raster's dimensions (not just lat/long, but x/y shape too). The code almost works, i.e., the larger raster is almost clipped/masked to the smaller raster, except it is still 1 pixel larger in each dimension (754x879 instead of 753x878, the latter of which is the size of the smaller raster).

    Why aren't the masked raster's dimensions the same as the masking raster?

    Here's my code:

    import rasterio
    import geopandas as gpd
    from shapely.geometry import box
    from rasterio.mask import raster_geometry_mask
    import json

    masking_raster = rasterio.open(path/to/file)
    raster_to_mask = rasterio.open(path/to/file)

    bbox = box(*masking_raster.bounds)
    geo = gpd.GeoDataFrame({'geometry': bbox}, index=[0], crs=val_file.crs)
    bbox_json = json.loads(gdf.to_json())['features'][0]['geometry']

    masked_array, out_transform, window = raster_geometry_mask(val_file, shapes=[bbox_json], crop=True, all_touched=False)
    print("masking raster shape: ", masking_raster.shape)
    # masking raster shape: (753, 878)
    print("resulting masked array shape: ", masked_array.shape)
    # resulting masked array shape: (754, 879)


    One other thing I checked is the transform of each input raster and I did notice they were slightly different. Could that be resulting in the masked raster having the same geometry bounds as the masking raster, but have different x/y dimensions?

    Continue reading...

Compartilhe esta Página