1.cosin相似度(余弦相似度)

from PIL import Image
from numpy import average, linalg, dot


def get_thumbnail(image, size=(30, 30), greyscale=False):
    image = image.resize(size, Image.ANTIALIAS)
    if greyscale:
        image = image.convert('L')
    return image


def image_similarity_vectors_via_numpy(image1, image2):
    image1 = get_thumbnail(image1)
    image2 = get_thumbnail(image2)
    images = [image1, image2]
    vectors = []
    norms = []
    for image in images:
        vector = []
        for pixel_tuple in image.getdata():
            vector.append(average(pixel_tuple))
        vectors.append(vector)
        norms.append(linalg.norm(vector, 2))
    a, b = vectors
    a_norm, b_norm = norms
    res = dot(a / a_norm, b / b_norm)
    return res

import os
path = './duibi/凭证/'
path2 = './duibi/印泥/'
files2 = os.listdir(path2)
# print(files2)
lst_data = []
for root, dirs, files in os.walk(path):
    for file in files:
        image1 = Image.open(os.path.join(root, file))
        for f in files2:
            image2 = Image.open(os.path.join(path2, f))
            cosin = image_similarity_vectors_via_numpy(image1, image2)
            lst_data.append(cosin)
            # print(cosin)
print(lst_data)
print(min(lst_data))
print(max(lst_data))

图片1:

比较两张照片相似度python 博客园 对比两张照片的相似度_python


shape:(26, 86)

图片2:

比较两张照片相似度python 博客园 对比两张照片的相似度_Image_02


shape:(25, 85)

两张图片大小差一个像素,对比结果为 0.9991

2. SSIM(结构相似性度量)

这是一种全参考的图像质量评价指标,分别从亮度、对比度、结构三个方面度量图像相似性。

SSIM取值范围[0, 1],值越大,表示图像失真越小。

在实际应用中,可以利用滑动窗将图像分块,令分块总数为N,考虑到窗口形状对分块的影响,采用高斯加权计算每一窗口的均值、方差以及协方差,然后计算对应块的结构相似度SSIM,最后将平均值作为两图像的结构相似性度量,即平均结构相似性SSIM。

from skimage.measure import compare_ssim
from scipy.misc import imread
import numpy as np
 
img1 = imread('1.jpg')
img2 = imread('2.jpg')
 
img2 = np.resize(img2, (img1.shape[0], img1.shape[1], img1.shape[2]))
 
print(img2.shape)
print(img1.shape)
ssim = compare_ssim(img1, img2, multichannel=True)
 
print(ssim)

如果skimage版本比较高的话,用下面代码,

import cv2

from skimage.metrics import structural_similarity
import time

# 读取图像
img1 = cv2.imread(r'C:\Users\86182\Desktop\11\182.jpg')  
img2 = cv2.imread(r'C:\Users\86182\Desktop\11\1000.jpg')

img1 = img1[265:299, 866:909]
img2 = img2[265:299, 866:909]
img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)

ssim = structural_similarity(img1, img2)
print(ssim)

使用上面两张图片:结果为:0.146
看似结果比上面结果差很多

3. 基于直方图

直方图能够描述一幅图像中颜色的全局分布,是一种入门级的图像相似度计算方法。

from PIL import Image
 
def make_regalur_image(img, size = (256, 256)):
    return img.resize(size).convert('RGB')
 
 
def hist_similar(lh, rh):
    assert len(lh) == len(rh)
    return sum(1 - (0 if l == r else float(abs(l - r))/max(l, r)) for l, r in zip(lh, rh))/len(lh)
 
 
def calc_similar(li, ri):
    return hist_similar(li.histogram(), ri.histogram())
 
 
if __name__ == '__main__':
    img1 = Image.open('1.jpg')
    img1 = make_regalur_image(img1)
    img2 = Image.open('2.jpg')
    img2 = make_regalur_image(img2)
    print(calc_similar(img1, img2))

结果为:0.845
直方图过于简单,只能捕捉颜色信息的相似性,捕捉不到更多的信息。只要颜色分布相似,就会判定二者相似度较高,显然不合理。

4. 基于互信息(Mutual Information)

通过计算两个图片的互信息来表征他们之间的相似度。

from sklearn import metrics as mr
from scipy.misc import imread
import numpy as np
 
img1 = imread('1.jpg')
img2 = imread('2.jpg')
 
img2 = np.resize(img2, (img1.shape[0], img1.shape[1], img1.shape[2]))
 
img1 = np.reshape(img1, -1)
img2 = np.reshape(img2, -1)
print(img2.shape)
print(img1.shape)
mutual_infor = mr.mutual_info_score(img1, img2)
 
print(mutual_infor)

结果:2.163
如果两张图片尺寸相同,还是能在一定程度上表征两张图片的相似性的。但是,大部分情况下图片的尺寸不相同,如果把两张图片尺寸调成相同的话,又会让原来很多的信息丢失,所以很难把握。经过实际验证,此种方法的确很难把握。