title: Finding Variance of an image in OpenCV -Python
body: <p>I am trying to find the variance of a greyscale image in OpenCV -Python. I first take the image read in and split it into sub-images, I want to calculate the variance of these sub-images (<code>cropped_img</code>).</p>
  
  <p>I'm not sure how to calculate variance in python, I assumed that I could calculate the covariance matrix to find the variance using the rule:</p>
  
  <p>Var(X) = Cov(X,X)  </p>
  
  <p>The thing is I can't get my head around how to use <code>cv2.calcCovarMatrix()</code>, and I can't find any examples in python. </p>
  
  <p>I did find this example in C++ but I have never used the language and im struggling to convert it into python: <a href="https://stackoverflow.com/questions/9795634/calccovarmatrix-in-multichannel-image-and-unresolved-assertion-error">calcCovarMatrix in multichannel image and unresolved assertion error</a> </p>
  
  <p>Here is my code:</p>
  
  <pre><code>#import packages
  import numpy as np
  import cv2
  
  #Read in image as grey-scale
  img = cv2.imread('images/0021.jpg', 0)
  
  #Set scale of grid 
  scale = 9
  
  #Get x and y components of image
  y_len,x_len = img.shape
  
  covar = []
  for y in range(scale):
      for x in range(scale):
          #Crop image 9*9 windows
          cropped_img=img[(y*y_len)/scale:((y+1)*y_len)/scale,
                            (x*x_len)/scale:((x+1)*x_len)/scale]
  
          #Here is where I need to calc variance
          cv2.calcCovarMatrix(cropped_img, covar, meanBGR, cv2.cv.CV_COVAR_NORMAL)
          #???
          cropped_img[:] = covar
  
  cv2.imshow('output_var',img)
  cv2.waitKey(0)
  cv2.destroyAllWindows()
  </code></pre>
  
  <p>If anyone has any ideas or if you have a better way to calculate variance then I would be extremely grateful.</p>
  
  <p>Thanks.</p>
  
  <p>EDIT: I also found this example in c; <a href="https://stackoverflow.com/questions/2608782/mean-and-variance-of-image-in-single-pass">mean and variance of image in single pass</a>, but it doesn't seem too efficient.</p>