1

The zonal statistics tool within QGIS is able to calculate the average raster variance within an area of interest. I am now trying to automate this in Python.

I typically use zonal_stats from the rasterstats library for calculating zonal statistics in Python, but zonal_stats is only able to calculate min, max, mean, count, sum, std, median, majority, minority, unique, range, nodata, and percentile.

How would I calculate raster variance over an area of interest in Python?

1 Answer 1

2

I figured it out- instead of using rasterstats, you can use rasterio and numpy together to calculate raster variance. Below is the code I ended up using.

import numpy as np
import rasterio


def calculate_raster_variance(raster_path: str):
    raster = rasterio.open(raster_path)
    arr = raster.read()
    out = np.var(arr)
    return out
2
  • 1
    Here you are not using any AOI isn't it ? Otherwise, you could have computed the square of std from rasterstats or use a window in rasterio :)
    – remi.braun
    Commented Apr 12, 2023 at 16:07
  • Ah, wonderful! That is actually a better solution! I have now switched to use the square of std using rasterstats.
    – user2031
    Commented Apr 13, 2023 at 14:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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