gpt4 book ai didi

python - 如何找到两个图像之间的相关性

转载 作者:行者123 更新时间:2023-11-30 08:52:49 25 4
gpt4 key购买 nike

我需要使用 numpy 找到两个图像之间的相关性,但仅使用基本数学。我遇到问题:“*IndexError:索引 5434 超出了尺寸为 5434* 的轴 0 的范围”。我有一个代码。请告诉我该怎么做。

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

最佳答案

这是函数的矢量化版本:

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

关于python - 如何找到两个图像之间的相关性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59608470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com