Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError: module 'rasterio' has no attribute 'mask'

I am trying to learn sentinelsat by following some tutorials. Part of the codes goes like this.

import rasterio as rio
import geopandas as gpd

nReserve = gpd.read_file('NReserve/NaturalReserve_Polygon.shp')

nReserve_proj = nReserve.to_crs({'init': 'epsg:32633'})

with rio.open("RGB.tiff") as src:
    out_image, out_transform = rio.mask.mask(src, nReserve_proj.geometry,crop=True)
    out_meta = src.meta.copy()
    out_meta.update({"driver": "GTiff",
                 "height": out_image.shape[1],
                 "width": out_image.shape[2],
                 "transform": out_transform})
    
with rio.open("RGB_masked.tif", "w", **out_meta) as dest:
    dest.write(out_image)

The line out_image, out_transform = rio.mask.mask(src, nReserve_proj.geometry,crop=True) is giving me error. The error goes like this --

AttributeError                            Traceback (most recent call last)
<ipython-input-45-c1fc22fa2c5d> in <module>()
      2 
      3 with rio.open("RGB.tiff") as src:
----> 4     out_image, out_transform = rio.mask.mask(src, nReserve_proj.geometry,crop=True)
      5     out_meta = src.meta.copy()
      6     out_meta.update({"driver": "GTiff",

AttributeError: module 'rasterio' has no attribute 'mask'

But rasterio's documentation it shows rasterio.mask.mask() exists. from doc --

rasterio.mask.mask(dataset, shapes, all_touched=False, invert=False, nodata=None, filled=True, crop=False, pad=False, pad_width=0.5, indexes=None)

What went wrong here? I am new so I am not understanding what to check.

like image 369
mir abir hossain Avatar asked Aug 05 '26 00:08

mir abir hossain


1 Answers

You need to import mask from rasterio.mask. You will also need to change the line where you call the function so it says mask instead of rio.mask.mask.

import rasterio as rio
import geopandas as gpd
from rasterio.mask import mask

nReserve = gpd.read_file('NReserve/NaturalReserve_Polygon.shp')

nReserve_proj = nReserve.to_crs({'init': 'epsg:32633'})

with rio.open("RGB.tiff") as src:
    out_image, out_transform = mask(src, nReserve_proj.geometry,crop=True)
    out_meta = src.meta.copy()
    out_meta.update({"driver": "GTiff",
                 "height": out_image.shape[1],
                 "width": out_image.shape[2],
                 "transform": out_transform})
    
with rio.open("RGB_masked.tif", "w", **out_meta) as dest:
    dest.write(out_image)
like image 139
T-rex Avatar answered Aug 07 '26 14:08

T-rex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!