How to find correlation between two images

I need to find correlation between two images, using numpy, but basic math only. I have the problem:"* IndexError: index 5434 is out of bounds for axis 0 with size 5434*". And i have a code. Tell me what to do, pls.

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

Corr coef

Upvotes: 3

Views: 2997

Answers (2)

Mykola Zotko
Mykola Zotko

Reputation: 17804

You can use the function corrcoef in numpy to find Pearson correlation. First you need to flatten both image arrays:

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

Upvotes: 3

kuzand
kuzand

Reputation: 9806

Here's a vectorized version of your function:

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

It is also important to normalize your image arrays to avoid overflow:

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

Upvotes: 2

Related Questions