python 计算 图片的dhash (different hash)

需求背景

运营的同事提了个需求:货源审核人员天天要审核货源的照片,查看一个照片,检查其是不是之前货源已经使用过的,这个工做机械、高度重复,但愿能作个程序自动比对,把可能重复/类似的图片找出来。html

需求分析

对这个需求作了分析后,有一下结论:python

  1. 图片多是彻底同样的,只是格式不一样,png,jpeg, gif几种格式
  2. 图片多是类似的,只是通过了放缩、剪裁
  3. 图片多是类似的,通过了简单的涂鸦
  4. 图片多是类似/同样的,可是作了旋转

作这个程序不是要百分百找出重复图片,只须要找出大部分可能重复图片便可大幅度减小重复劳动。git

解决办法

使用different hash算法,计算两张图片的hash距离,若是距离小于一个阈值,则认为其类似度过高。github

安装PIL

yum install -y python-devel
wget http://effbot.org/downloads/Imaging-1.1.7.tar.gz
tar xvfz Imaging-1.1.7.tar.gz
cd Imaging-1.1.7

找到 setup.py 这个文件,修改下面几行代码(默认TCL_ROOT的设置为NONE,这里要传到系统库的路径才行):算法

TCL_ROOT = "/usr/lib64/"
JPEG_ROOT = "/usr/lib64/"
ZLIB_ROOT = "/usr/lib64/"
TIFF_ROOT = "/usr/lib64/"
FREETYPE_ROOT = "/usr/lib64/"
LCMS_ROOT = "/usr/lib64/"

执行安装:shell

python setup.py install

安装dhash

pip install dhash

使用PIL 计算dhashcode

import dhash
from PIL import Image

image = Image.open('dhash-test.jpg')
row, col = dhash.dhash_row_col(image)
print(dhash.format_hex(row, col))

使用 ImageMagick 计算dhash (须要安装ImageMagick)orm

import dhash
from wand.image import Image

with Image(filename='dhash-test.jpg') as image:
    row, col = dhash.dhash_row_col(image)
print(dhash.format_hex(row, col))

相关文章
相关标签/搜索