如何计算两张图像之间的协方差?

2 投票
3 回答
8572 浏览
提问于 2025-04-18 18:50

我正在用Python进行图像处理。具体来说,我想实现一个叫做结构相似性指数(SSIM)的算法,用来比较两张图片(x和y)。这两张图片是我从一篇文章中提取的,链接在这里:这篇文章。 在这个公式中,我需要计算这两张图片之间的协方差。我知道怎么计算两个向量之间的协方差,但我不知道怎么计算两个矩阵之间的协方差(我假设每张图片都是一个像素矩阵)。有没有人能帮我一下?我试过用numpy的函数numpy.cov(x,y) [文档],但我的数据是一个大的三维矩阵,而我实际上需要的是一个标量值。

3 个回答

0

当然可以!请看下面的内容:

在编程中,有时候我们需要让程序做一些特定的事情,比如在某个条件满足时执行某段代码。这就像给程序设定了一些规则,让它知道什么时候该行动。

比如说,如果你想让程序在用户输入一个数字时,检查这个数字是否大于10,如果是,就打印“这个数字很大!”;如果不是,就打印“这个数字不大。”这就是一个简单的条件判断。

在代码中,这种判断通常用“if”语句来实现。它的基本结构就像这样:

import cv2 
import numpy as np
from PIL import Image, ImageOps #PIL = pillow
from numpy import asarray

'''read image via PIL -- in opencv it equals to img1 = cv2.imread("c1.jpg") '''
img1 = Image.open('c1.jpg')
img2 = Image.open('d1.jpg')

gimg1 = ImageOps.grayscale(img1) #convert to grayscale PIL 
gimg2 = ImageOps.grayscale(img2)

#asarray() class is used to convert PIL images into NumPy arrays
numpydata1 = asarray(gimg1) 
numpydata2 = asarray(gimg2) 

print("Array of image 1: ", numpydata1.shape)
print("Array of image 2: ", numpydata2.shape)

#grayscale images are saved as 2D ndarray of rows(height) x columns(width)
height = int(numpydata2.shape[0] * 
         (numpydata1.shape[0]/numpydata2.shape[0] ) ) 
width = int(numpydata2.shape[1] * (numpydata1.shape[1]/ 
         numpydata2.shape[1] ) )

#print(width)
#print(height)

#when using resize(), format should be width x height therefore, create a new image called new and set it to w x h
 
new = (width, height)

#resize image so dimensions of both images are same
resized = cv2.resize(numpydata2, new, interpolation = cv2.INTER_AREA)

print("Array of resized image 2: ", resized.shape)

def Covariance(x, y):

    xbar, ybar = x.mean(), y.mean()

    return np.sum((x - xbar)*(y - ybar))/(len(x) - 1)

print( Covariance(numpydata1, resized))



'''#Alternative Method - convert grayscale image to array using np.array 
np_img1 = np.array(gimg1)
np_img2 = np.array(gimg2) 
'''

在这个结构中,“if”后面跟着一个条件,程序会检查这个条件是否为真。如果条件成立,程序就会执行大括号内的代码;如果不成立,程序就会跳过这部分代码,继续执行后面的内容。

通过这种方式,我们可以让程序根据不同的情况做出不同的反应,这样就能更灵活地处理各种任务了。

2

我们可以用Python来计算两张图片之间的协方差,方法如下:

import numpy as np

def Covariance(x, y):
    xbar, ybar = x.mean(), y.mean()
    return np.sum((x - xbar)*(y - ybar))/(len(x) - 1)

现在拿两张图片 img1img2,然后调用这个函数并按照给定的方式打印结果。

print( Covariance(img1,img2))
1

看看这个库:pyssim。这可能正是你需要的东西。

撰写回答