Rasterio – Solving Mask Doesn’t Work with Shapely Polygon Issue

clipmaskingpythonrasterioshapely

I have raster which I want to mask with shapely polygon.According the rasterio documentation, rasterio.mask can work with shapely geometry.However, in this case, it doesn't work.
enter image description here

whenever I use my shapely polygon, I get error:

TypeError: 'Polygon' object is not iterable

I have seen this error before in this post, but couldn't fix it based on this post.
The Rasterio version I'm using is 1.1.7

This i show I tried to mask the image:

from sentinelhub import BBox,bbox_to_dimensions
import pandas as pd
import numpy as np
import geopandas as gpd 
import rasterio
import fiona
import rasterio.mask


img=rasterio.open('path/to/img/my_img.tiff')

polygon=gpd.read_file('shapes/polyg.shp')

#create bounding box using sentinel hub ,the result is shapely geometry item
bbox_size,bbox,bbox_coords_wgs84=get_bbox_from_shape(plots,10)

type(bbox.geometry)

>>>shapely.geometry.polygon.Polygon

#mask the raster:
out_image,out_transform=rasterio.mask.mask(img,bbox.geometry,crop=True)

>>>
TypeError: 'Polygon' object is not iterable

My end goal : to mask the raster with the boundig box- shapely geometry item

Best Answer

The rasterio documentation for the mask function is not very clear here. The shape parameter must be an iterable of geometries, not a simple geometrie.

The documentation of the shape parameter (i.e. "The values must be a GeoJSON-like dict or an object that implements the Python geo interface protocol...") describes the nature of the values contained in the insertable, not the iterable itself, hence the confusion.

So, this line:

out_image, out_transform=rasterio.mask.mask(img, bbox.geometry, crop=True)

should be replaced by this one:

out_image, out_transform=rasterio.mask.mask(img, [bbox.geometry], crop=True)

NB: I use a list, but you can use any other type of iterable (e.g. tuple or set)