2

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 (cropped_img).

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:

Var(X) = Cov(X,X)

The thing is I can't get my head around how to use cv2.calcCovarMatrix(), and I can't find any examples in python.

I did find this example in C++ but I have never used the language and im struggling to convert it into python: calcCovarMatrix in multichannel image and unresolved assertion error

Here is my 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()

If anyone has any ideas or if you have a better way to calculate variance then I would be extremely grateful.

Thanks.

EDIT: I also found this example in c; mean and variance of image in single pass, but it doesn't seem too efficient.

1
  • 2
    if you're looking for the stdev, it's a one-liner Commented Mar 14, 2015 at 16:24

1 Answer 1

4

To get the variance of gray scale image in python you can use numpy.

import numpy as np

var = np.var(img)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.