aHash算法

    Hash算法进行图片相似度识别的本质,就是将图片进行Hash转化,生成一组二进制数字,然后通过比较不同图片的Hash值距离找出相似图片。aHash中文叫平均哈希算法,顾名思义,在进行转化过程中将用到像素均值。

基本原理

  1. 缩小尺寸。这样做会去除图片的细节,只保留结构、明暗等基本信息,目的统一图片大小,保证后续图片都有相同长度的哈希值,方便距离计算。网上看到的案例基本都将尺寸缩小为8*8,64个像素点,暂时不清楚缩小为这个尺寸的原因,但如果觉得损失的信息太多,个人认为可以将尺寸适当调大,当然像素点多了后续计算就会稍慢一些。

  2. 灰度化处理。将图片全部转换为统一的灰度图。

  3. 计算像素均值。计算像素的灰度平均值此处均值出现

  4. 哈希值计算将每个像素的灰度,与平均值进行比较。大于或等于平均值,记为1,小于平均值,记为0,由此生成二进制数组。

  5. 图片配对,计算汉明距离。距离越近,越相似。当图片缩小为8*8时,通常认为汉明距离小于10的一组图片为相似图片。

2

Python实现

本例中将计算以下两张图片的相似度:

图片相似度识别:aHash算法_java

(image1)

图片相似度识别:aHash算法_java_02

(image2)

  • 图像处理库

图像处理可以用opencv包或者PIL包。如要使用opencv,需要在terminal中输入下面代码,先安装brew,再通过brew安装opencv。



$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"$ brew install opencv
  • 完整算法


from PIL import Image #用PIL处理图像import osimport 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)

最终结果:

图片相似度识别:aHash算法_java_03

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

3

优缺点

优点:速度快

缺点:精确度较差,对均值敏感