Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want a local variance image with a 3x3 of a geospatial raster image using python. My approach so far was to read in the raster band as an array, then using matrix notation to run a moving window and write the array into a new raster image. This approach worked well for a high pass filter as described in this tutorial:

Then I tried to calculate the variance with several approaches, the last one using numpy (as np), but I just get a gray image with the same value everywhere. I am open to any kind of solution. If it gives me the average local variance in the end, that would be even better Thanks, Mace

  rows = srcDS.RasterYSize
  #read in as array
  data = srcBand.ReadAsArray(0,0, cols, rows).astype(

  #calculate the variance for a 3x3 window
  outVariance = np.zeros((rows, cols), np.float)
  outVariance[1:rows-1,1:cols-1] = np.var([(data[0:rows-2,0:cols-2]),
    (data[0:rows-2,2:cols]  ),
    (data[1:rows-1,2:cols]  ),
    (data[2:rows,0:cols-2]  ),
    (data[2:rows,1:cols-1]  ),
    (data[2:rows,2:cols]    )])
  outDS = driver.Create(outFN, cols, rows, 1, GDT_Float32)
  outBand = outDS.GetRasterBand(1)
share|improve this question
up vote 1 down vote accepted

This trick from another user on Stackoverflow solved the problem:

from scipy import ndimage
outVariance = ndimage.generic_filter(data, np.var, size=3)

See here for a detailed description of the answer:

share|improve this answer
If this solved your question, please mark this as the accepted answer by clicking on the grayed out check mark below the answer vote up/down arrows. – Chad Cooper May 23 '13 at 13:54

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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