用python 加opencv计算两张图像的hu矩和皮尔逊相关系数,输出其相似度。
import cv2
import math
import numpy as np
from PIL import Image
im1 = cv2.imread('xuetaggujia.png',cv2.IMREAD_GRAYSCALE)
im2 = cv2.imread('xuegengujia.png',cv2.IMREAD_GRAYSCALE)
_,im1 = cv2.threshold(im1, 128, 255, cv2.THRESH_BINARY)
_,im2 = cv2.threshold(im2, 128, 255, cv2.THRESH_BINARY)
# Calculate Moments
moments1 = cv2.moments(im1)
# Calculate Hu Moments
huMoments1 = cv2.HuMoments(moments1)
for i in range(0,7):
huMoments1[i] = -1 * math.copysign(1.0, huMoments1[i]) * math.log10(abs(huMoments1[i]))
huMoments1 = np.array(huMoments1)
huMoments1 = huMoments1.astype(int)
print(huMoments1)
# Calculate Moments
moments2 = cv2.moments(im2)
# Calculate Hu Moments
huMoments2 = cv2.HuMoments(moments2)
for i in range(0,7):
huMoments2[i] = -1 * math.copysign(1.0, huMoments2[i]) * math.log10(abs(huMoments2[i]))
huMoments2 = np.array(huMoments2 )
huMoments2 = huMoments2.astype(int)
print(huMoments2)
def calcMean(x,y):
sum_x = sum(x)
sum_y = sum(y)
n = len(x)
x_mean = float(sum_x+0.0)/n
y_mean = float(sum_y+0.0)/n
return x_mean,y_mean
#计算Pearson系数
def calcPearson(x,y):
x_mean= np.mean(x,axis=0) #计算x,y向量平均值
y_mean = np.mean(y,axis=0)
n = len(x)
sumTop = 0.0
sumBottom = 0.0
x_pow = 0.0
y_pow = 0.0
for i in range(n):
sumTop += (x[i]-x_mean)*(y[i]-y_mean)
for i in range(n):
x_pow += math.pow(x[i]-x_mean,2)
for i in range(n):
y_pow += math.pow(y[i]-y_mean,2)
sumBottom = math.sqrt(x_pow*y_pow)
p = sumTop/sumBottom
return p
k = calcPearson(huMoments1,huMoments2)
print(k)



