简体   繁体   English

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

[英]Finding Variance of an image in OpenCV -Python

I am trying to find the variance of a greyscale image in OpenCV -Python. 我试图在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 ). 我首先读取读入的图像并将其拆分为子图像,我想计算这些子图像的差异( 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: 我不确定如何在python中计算方差,我假设我可以使用以下规则计算协方差矩阵以找到方差:

Var(X) = Cov(X,X) 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. 关键是我无法理解如何使用cv2.calcCovarMatrix() ,也无法在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 我确实在C ++中找到了此示例,但我从未使用过这种语言,并且一直在努力将其转换为python: 多通道图像中的calcCovarMatrix和未解决的断言错误

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; 编辑:我也在c中找到了这个例子; mean and variance of image in single pass , but it doesn't seem too efficient. 单次通过图像的均值和方差 ,但似乎效率不高。

To get the variance of gray scale image in python you can use numpy. 要获取python中灰度图像的方差,可以使用numpy。

import numpy as np

var = np.var(img)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM