在OpenCV -Python中查找图像的方差

时间:2015-03-14 12:39:52

标签: python c++ opencv image-processing computer-vision

我试图在OpenCV -Python中找到灰度图像的方差。我首先将图像读入并将其拆分为子图像,我想计算这些子图像的方差(cropped_img)。

我不确定如何计算python中的方差,我假设我可以使用规则计算协方差矩阵来找出方差:

Var(X)= Cov(X,X)

问题是我无法理解如何使用cv2.calcCovarMatrix(),我在python中找不到任何示例。

我确实在C ++中找到了这个例子,但是我从未使用过该语言而且我正在努力将其转换为python:calcCovarMatrix in multichannel image and unresolved assertion error

这是我的代码:

#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()

如果有人有任何想法,或者你有更好的方法来计算方差,那么我将非常感激。

感谢。

编辑:我也在c中找到了这个例子; mean and variance of image in single pass,但效果似乎不太高。

1 个答案:

答案 0 :(得分:2)

要在python中获得灰度图像的方差,可以使用numpy。

import numpy as np

var = np.var(img)