I want to calculate the mean and standard deviation of a raster image. In QGIS zonal statistics, we can calculate it within a polygon or a vector. But I want to calculate for the whole image. In Python, I'm getting the same value for an image that I'm giving as input. How can I resolve this one...?

import numpy as np
from osgeo import gdal
g = gdal.Open('ndvi.tif')
ndvi = g.ReadAsArray()
ndvi = np.array(ndvi, dtype = float)
M_ndvi = ndvi.mean()
Std_ndvi = ndvi.std()

I tried this for different images, but the mean and standard deviation output is same for all.

  • If you get the same statistics for all images, have you considered that you may do it wrong with your code?
    – user30184
    Jun 8 '16 at 6:24
  • 1
    Confirmed that the band.ComputeStatistics(0) method from gis.stackexchange.com/questions/54150/… works. You must have a problem with your Python code.
    – user30184
    Jun 8 '16 at 7:12

These lines of code are working:

import optparse, warnings,sys,os
import numpy as np
import pandas as pd
from PIL import *
from osgeo import gdal,ogr,osr
import osgeo
import gdal

g_red = gdal.Open(r'band4.tif')
g_nir = gdal.Open(r'band5.tif')
red = g_red.ReadAsArray()
nir = g_nir.ReadAsArray()
red = np.array(red, dtype = float)
nir = np.array(nir, dtype = float)
check = np.logical_and ( red > 1, nir > 1 )
ndvi = np.where ( check,  (nir - red ) / ( nir + red ), -999 )

noDataVal = ndvi.GetNoDataValue(); print('no data value:',noDataVal)
scaleFactor = ndvi.GetScale(); print('scale factor:',scaleFactor)
ndvi_stats = ndvi.GetStatistics(True,True)

print('NDVI Statistics: Minimum=%.2f, Maximum=%.2f, Mean=%.3f, StDev=%.3f' %(ndvi_stats[0], ndvi_stats[1], ndvi_stats[2], ndvi_stats[3]))

In QGIS, Go to Raster -> Miscellaneous -> Information. In the drop down list select the image you want and click OK. Among the information you will receive from the image, you will also get the minimum, maximum, mean and standard deviation of the image as a whole.

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.