有史以来最全的图像相似度算法

使用四种方法计算图片相似度:

MD5、直方图、PSNR、SSIM

import numpy as np
from PIL import Image
from skimage.metrics import structural_similarity
import cv2
import os
import hashlib
import math

'''
    粗暴的md5比较 返回是否完全相同
'''
def md5_similarity(img1_path, img2_path):
    file1 = open(img1_path, "rb")
    file2 = open(img2_path, "rb")
    md = hashlib.md5()
    md.update(file1.read())
    res1 = md.hexdigest()
    md = hashlib.md5()
    md.update(file2.read())
    res2 = md.hexdigest()
    return res1 == res2

def normalize(data):
    return data / np.sum(data)

'''
    直方图相似度
    相关性比较 cv2.HISTCMP_CORREL:值越大,相似度越高
    相交性比较 cv2.HISTCMP_INTERSECT:值越大,相似度越高
    卡方比较 cv2.HISTCMP_CHISQR:值越小,相似度越高
    巴氏距离比较 cv2.HISTCMP_BHATTACHARYYA:值越小,相似度越高

'''
def hist_similarity(img1, img2, hist_size=256):
    imghistb1 = cv2.calcHist([img1], [0], None, [hist_size], [0, 256])
    imghistg1 = cv2.calcHist([img1], [1], None, [hist_size], [0, 256])
    imghistr1 = cv2.calcHist([img1], [2], None, [hist_size], [0, 256])

    imghistb2 = cv2.calcHist([img2], [0], None, [hist_size], [0, 256])
    imghistg2 = cv2.calcHist([img2], [1], None, [hist_size], [0, 256])
    imghistr2 = cv2.calcHist([img2], [2], None, [hist_size], [0, 256])

    distanceb = cv2.compareHist(normalize(imghistb1), normalize(imghistb2), cv2.HISTCMP_CORREL)
    distanceg = cv2.compareHist(normalize(imghistg1), normalize(imghistg2), cv2.HISTCMP_CORREL)
    distancer = cv2.compareHist(normalize(imghistr1), normalize(imghistr2), cv2.HISTCMP_CORREL)
    meandistance = np.mean([distanceb, distanceg, distancer])
    return meandistance

def PSNR(img1, img2):
    mse = np.mean((img1/255. - img2/255.) ** 2)
    if mse == 0:
        return 100
    PIXEL_MAX = 1
    return 20 * math.log10(PIXEL_MAX / math.sqrt(mse))

def SSIM(img1, img2):
    gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
    gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
    # 计算两个灰度图像之间的结构相似度
    score, diff = structural_similarity(gray1, gray2, win_size=101, full=True)
    # diff = (diff * 255).astype("uint8")
    # print("SSIM:{}".format(score))
    return score, diff

if __name__ == '__main__':
    img1_path = 'dui/1.png'
    img2_path = 'dui/2.png'
    img1 = cv2.imread(img1_path)
    img2 = cv2.imread(img2_path)

    # 1.粗暴的md5比较 返回是否完全相同
    print('md5_similarity:', md5_similarity(img1_path, img2_path))
    # 2.直方图相似度
    print('hist_similarity:', hist_similarity(img1, img2))
    # 3.PSNR
    print('PSNR:', PSNR(img1, img2))
    # 4.SSIM
    print('SSIM:', SSIM(img1, img2))

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小殊小殊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值