I have several hundred tif files of ~50mb each where I need to read only a few hundred pixels within a polygon. I currently do this by loading each tif into memory and using
rasterio.features.geometry_mask to get the pixels of interest. But reading in the large tifs takes a very long time.
import fiona import rasterio with fiona.open('polygon.geojson') as f: geom=f['geometry'] all_data= for tif_filename in tif_file_list: with rasterio.open(tif_filename) as raster_obj: polygon_mask = rasterio.features.geometry_mask(geometries=[geom], out_shape=(raster_obj.height, raster_obj.width), transform=raster_obj.transform, all_touched=False, invert=True) all_data.append(raster_obj.read()[polygon_mask])
Is there any way I can use the Window option to only read the portion of the raster I want? For example I can read just the extent of the area of interest:
with fiona.open('polygon.geojson') as f: b = f.bounds polygon_window = rasterio.windows.from_bounds(left=b, bottom=b, right=b, top=b, transform = raster_obj.transform) extent_data = raster_obj.read(1, window=polygon_window)
This takes a fraction of the time, but I can't figure out how to then get the pixel data from only within the polygon.