运营的同事提了个需求:货源审核人员天天要审核货源的照片,查看一个照片,检查其是不是之前货源已经使用过的,这个工做机械、高度重复,但愿能作个程序自动比对,把可能重复/类似的图片找出来。html
对这个需求作了分析后,有一下结论:python
作这个程序不是要百分百找出重复图片,只须要找出大部分可能重复图片便可大幅度减小重复劳动。git
使用different hash算法,计算两张图片的hash距离,若是距离小于一个阈值,则认为其类似度过高。github
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
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))
dhash的说明 https://github.com/Jetsetter/dhashhtm
一个有深度解决办法 老司机带你检测类似图片blog