利用直方图特征计算图像之间的相似度,得到相关矩阵
# -*- coding: utf-8 -*-
import cv2
import os
import math
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
#获取图片地址
def get_imlist(path):
return [os.path.join(path,f) for f in os.listdir(path) if f.endswith('.jpg')]
def transferimgsize(imlist):
#转换图片成相同尺寸
for img in imlist:
pic=cv2.imread(img)
pic = cv2.resize(pic, (200, 80), interpolation=cv2.INTER_CUBIC)
cv2.imwrite(img, pic)
def get_hsv_hist_feature(image_name):
# 获取图像hsv直方图特征,返回h,s,v三个维度各自的直方图
img = cv2.imread(image_name)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
arr_h=hsv[:,:,0].flatten()
arr_s=hsv[:,:,1].flatten()
arr_v=hsv[:,:,2].flatten()
nh, bins, patches= plt.hist(arr_h, bins=256, normed=1)
ns, bins, patches = plt.hist(arr_s, bins=256, normed=1)
nv, bins, patches = plt.hist(arr_v, bins=256, normed=1)
return [nh,ns,nv]
def cal_his_intersection(image_name1,image_name2):
# 计算2张图片的颜色特征的相似度
value=0
feature1=get_hsv_hist_feature(image_name1)
feature2=get_hsv_hist_feature(image_name2)
for i in range(2):
count1=feature1[i]
count2=feature2[i]
Sum1=sum(count1);Sum2=sum(count2)
Sumup = [math.sqrt(a*b) for a,b in zip(count1,count2)]
SumDown = math.sqrt(Sum1*Sum2)
Sumup = sum(Sumup)
HistDist=1-math.sqrt(1-Sumup/SumDown)
value+=HistDist
return value/3
def cal_Euclidean_Distance(image_name1,image_name2):
# 计算2张图片的形状、质感等特征的相似度
img1 = cv2.imread(image_name1)
img2 = cv2.imread(image_name2)
img1 = cv2.cvtColor(img1, cv2.COLOR_RGB2GRAY)
img2 = cv2.cvtColor(img2, cv2.COLOR_RGB2GRAY)
dist=np.linalg.norm(img1-img2)
return dist
if __name__ == "__main__":
imlist = get_imlist('D:/mywork/python/Images/image66')
final=pd.DataFrame(data=None,index=imlist, columns=imlist)
for img_i in imlist:
for img_j in imlist:
#记录相似度矩阵数据
final.loc[img_i,img_j]=cal_Euclidean_Distance(img_i,img_j)
网友评论