1

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

2
  • 3
    Did you try to put the geometry in an iterable object ? For examle : out_image,out_transform=rasterio.mask.mask(img,[bbox.geometry],crop=True)
    – Atm
    Dec 6, 2021 at 10:15
  • @Atm that worked, please consider to write it as answer
    – Reut
    Dec 29, 2021 at 13:00

1 Answer 1

3

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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