I am trying to extract the pixel values of a raster from a polygon that has several features. My raster is a rasterstack with 4 bands. I have found how to do it for a whole raster, but I need the info PER BAND. Any hints?
from rasterstats import zonal_stats
import os
import numpy as np
import statistics
shapefile = Class1.shp
geotiff = tile_105.tif
# calculate all zonal stats
stats = zonal_stats(shapefile, geotiff)
# extract the mean and store it
single_mean = [f['mean'] for f in stats]
val_list = []
# only store the positive values.
for val in single_mean:
if val != None :
val = [float(val)]
val_list.append(val[0])
all_mean = statistics.mean(val_list)
rasterio to read a [multi-band raster]!
https://rasterio.readthedocs.io/en/latest/topics/reading.html
You may also want to define the extent of your AOI by defining the cropping window ((row_start, row_stop), (col_start, col_stop))