I'm working on a project in which need to get the variance of an image. Currently I'm taking 2 approaches (both work but are very slow):
- Calculating the variance for each pixel individually:
This is the code using numpy, varianceMatrix is the output
varianceMatrix = np.zeros(im.shape,np.uint8)
w = 1 # the radius of pixels neighbors
ny = len(im)
nx = len(im[0])
for i in range(w,nx-w):
for j in range(w,ny-w):
sampleframe = im[j-w:j+w, i-w:i+w]
variance = np.var(sampleframe)
varianceMatrix[j][i] = int(variance)
return varianceMatrix
- Using an existing scipy function:
This is the scipy function:
from scipy import ndimage
varianceMatrix = ndimage.generic_filter(im, np.var, size = 3)
The scipy function is faster, but not so much. I'm looking for a better alternative to calculate the variance.
Any ideas???