
戳蓝色字关注我们哟!
aHash、pHash、dHash是常用的图像相似度识别算法,原理简单,实现方便,个人把这三个算法作为学习图片相似度识别的入门算法。本次起,从aHash开始,对三个算法的基本原理和实践代码进行梳理。
1
aHash算法
Hash算法进行图片相似度识别的本质,就是将图片进行Hash转化,生成一组二进制数字,然后通过比较不同图片的Hash值距离找出相似图片。aHash中文叫平均哈希算法,顾名思义,在进行转化过程中将用到像素均值。
基本原理:
2
Python实现
本例中将计算以下两张图片的相似度:

(image1)

(image2)
图像处理可以用opencv包或者PIL包。如要使用opencv,需要在terminal中输入下面代码,先安装brew,再通过brew安装opencv。
$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
$ brew install opencvfrom PIL import Image #用PIL处理图像
import os
import numpy as np
#import cv2 ——如果要用opencv时需导入
#均值哈希算法
def aHash(image):
image_new=image
#计算均值
avreage = np.mean(image_new)
hash = []
for i in range(image.shape[0]):
for j in range(image.shape[1]):
if image[i,j] > avreage:
hash.append(1)
else:
hash.append(0)
return hash
#计算汉明距离
def Hamming_distance(hash1,hash2):
num = 0
for index in range(len(hash1)):
if hash1[index] != hash2[index]:
num += 1
return num
if __name__ == "__main__":
#PIL
image1 = Image.open('image1.png')
image2 = Image.open('image2.png')
#缩小尺寸并灰度化
image1=np.array(image1.resize((8, 8), Image.ANTIALIAS).convert('L'), 'f')
image2=np.array(image2.resize((8, 8), Image.ANTIALIAS).convert('L'), 'f')
#opencv
#img1 = cv2.imread('image1')
#img2 = cv2.imread('image2')
#缩小尺寸并灰度化
#image1=cv2.cvtColor(cv2.resize(img1,(8,8),interpolation=cv2.INTER_CUBIC),cv2.COLOR_BGR2GRAY)
#image2=cv2.cvtColor(cv2.resize(img2,(8,8),interpolation=cv2.INTER_CUBIC),cv2.COLOR_BGR2GRAY)
hash1 = aHash(image1)
hash2 = aHash(image2)
dist = Hamming_distance(hash1, hash2)
#将距离转化为相似度
similarity = 1 - dist * 1.0 / 64
print('dist is '+'%d' % dist)
print('similarity is ' +'%d' % similarity)最终结果:

可见两张图片相似度非常低。