【问题标题】:How to find correlation between two images如何找到两个图像之间的相关性
【发布时间】:2020-04-23 18:46:45
【问题描述】:

我需要使用 numpy 找到两个图像之间的相关性,但仅限于基本数学。我有问题:"* IndexError: index 5434 is out of bounds for axis 0 with size 5434*"。我有一个代码。告诉我该怎么做,请告诉我。

img = PIL.Image.open("SR1.png").convert("L")
im = numpy.array(img)
img2 = PIL.Image.open("SR61.png").convert("L")
im2 = numpy.array(img2)
np.array(im,dtype=float)
np.array(im2,dtype=float)
import math
import cmath
def correlationCoefficient(X, Y, n) : 
    sum_X = 0
    sum_Y = 0
    sum_XY = 0
    squareSum_X = 0
    squareSum_Y = 0


    i = 0
    for i in range(n) : 
        sum_X = sum_X + X[i]
        sum_Y = sum_Y + Y[i] 
        sum_XY = sum_XY + X[i] * Y[i] 
        squareSum_X = squareSum_X + X[i] * X[i] 
        squareSum_Y = squareSum_Y + Y[i] * Y[i] 

        i = i + 1

    corr = (n * sum_XY - sum_X * sum_Y)/(cmath.sqrt((n * squareSum_X - sum_X * sum_X)* (n * squareSum_Y - sum_Y * sum_Y))) 
    return corr


X = im.flatten()
Y = im2.flatten()


n = len(X) 


print ('{0:.6f}'.format(correlationCoefficient(X, Y, n))) 

【问题讨论】:

  • 好的。我改变了一些东西
  • len(X) == len(Y)?
  • 首先去掉i=0i = i + 1,因为你有for循环。
  • @AndreasK。 @MykolaZotko 谢谢,伙计们但是知道“RuntimeWarning:ubyte_scalars 中遇到溢出”因此我有 corr coef -243,.. 这不好))你有什么想法吗?
  • 你从哪里得到 corr 的公式?可以显示出处吗?

标签: python python-3.x numpy machine-learning computer-vision


【解决方案1】:

你可以使用numpy中的函数corrcoef来查找Peason相关性。首先你需要flatten两个图像数组:

np.corrcoef(im1.flatten(), im2.flatten())

【讨论】:

  • 现在我有另一个问题:)
【解决方案2】:

这是您的函数的矢量化版本:

import numpy as np

def correlationCoefficient(X, Y):
    n = X.size
    sum_X = X.sum()
    sum_Y = Y.sum()
    sum_XY = (X*Y).sum()
    squareSum_X = (X*X).sum()
    squareSum_Y = (Y*Y).sum()
    corr = (n * sum_XY - sum_X * sum_Y)/(np.sqrt((n * squareSum_X - sum_X * sum_X)* (n * squareSum_Y - sum_Y * sum_Y))) 
    return corr

标准化图像数组以避免溢出也很重要:

from PIL import Image

img1 = Image.open("1.jpg").convert("L")
im1 = np.array(img1)/255

img2 = Image.open("2.jpg").convert("L")
im2 = np.array(img2)/255

print ('{0:.6f}'.format(correlationCoefficient(im1, im2))) 

【讨论】:

  • 所以,现在是“不能与形状一起广播的操作数 (96,124) (38,143)”
  • @Антон Тугусов 您的图片大小相同吗?它们应该具有相同的形状。如果没有,那么可能会调整它们的大小。
  • 但是,如果我想在大小不同的图像之间找到 corr coef。有没有可能?
  • mb 你知道,如何在图像上描绘 corr coef 这将是我的输出:具有相关性的 png 图像你知道吗?
  • 嗯,我不这么认为。您给出的公式适用于相同大小的 x 和 y。所以也许你需要别的东西。
猜你喜欢
  • 2014-02-27
  • 1970-01-01
  • 1970-01-01
  • 2017-12-29
  • 2014-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-11
相关资源
最近更新 更多