-1

import of packages:

from rasterio.mask import mask
import geopandas as gpd

opened a shapefile:

gdf = gpd.read_file(shpfilepath+clipshape)

and opened a rasterfile:

img = rasterio.open(f'{rstfilepath}raw_immutable/SuperView/{SV_filename}{ext}')

then perform action:

for poly_gon in gdf.geometry:
    out_image, out_transform = mask(img, poly_gon, crop=True)

but this failes:

TypeError: 'Polygon' object is not iterable

I cannot find how to handle every polygon in the shapefile (5 in my case) to be the polygon to clip the raster image.

  • take a look at this answer https://stackoverflow.com/questions/71873178/how-to-extracts-the-different-land-use-areas-from-tif-file-within-different-dist/71897580#71897580. It is clipping based on all geometries in a **GeoDataFrame** – Rob Raymond Apr 20 '22 at 13:02

1 Answers1

0

Update

How about going into nesting your results. First create an empty object like an empty dict then fill it like:

empt_dict1=dict()
for i in range(len(gdf.geometry)):
   empt_dict1[i] = dict()
   empt_dict1[i][0], empt_dict1[i][1] = mask(img, gdf.geometry[i], crop=True)

Your expected clips are in each sub-object of the empt_dict list.

I don't have a working gdf right now so I'm not sur if you can index it that way or if you should use something like .loc.

Old answer

If I understand correctly you seek to use the whole area of all the polygons at the same time. How about merging them into a single one using a temporary layer, like below. PS: I tried to use your names given that you don't provide any data.

gdf["dummy"]=[0 for i in range(5)]
gdf_tempo = gdf.dissolve(by=dummy)

out_image, out_transform = mask(img, gdf_tempo , crop=True)
CharlesN
  • 1
  • 1
  • 1
    basic idea is to clip parts of satellite images using defined polygons in a shapefile. Every polygon in the shapefile should return a clipped image with the polygon as boundary. But it can occur that a polygon is outside the raster image... – Allian Python Apr 19 '22 at 14:48
  • Then I did not understand correctly your question. What you need is a different object /instance per clip. I will detail it in the post. – CharlesN Apr 19 '22 at 20:21