我需要使用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 mathimport cmathdef 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 corrX = im.flatten()Y = im2.flatten()n = len(X) print ('{0:.6f}'.format(correlationCoefficient(X, Y, n)))
回答:
这是您函数的向量化版本:
import numpy as npdef 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 Imageimg1 = Image.open("1.jpg").convert("L")im1 = np.array(img1)/255img2 = Image.open("2.jpg").convert("L")im2 = np.array(img2)/255print ('{0:.6f}'.format(correlationCoefficient(im1, im2)))