Wote用python语言写的imgHash.py
#!/usr/bin/python
#encoding:utf-8
import sys
import glob
import os
from PIL import Image
EXTS = 'jpg','jpeg','JPG','JPEG','gif','GIF','png','PNG'
def avhash(im):
if not isinstance(im,Image.Image):
im = Image.open(im)
im = im.resize((8,8),Image.ANTIALIAS) #resize image with high-quality
im = im.convert('L') #L表示灰度
ida = im.getdata() #return the contents of an image as a sequence objectcontaining pixel values
#for index,item in enumerate(ida):
# print index,item
avg = reduce(lambda x,y:x+y,ida)/64 #遍历ida序列求平均数
mp = map(lambda i:0 if i<avg else 1,im.getdata())
'''
reduce函数
reduce函数,reduce函数会对参数序列中元素进行累积。
reduce函数的定义:
reduce(function, sequence[, initial]) -> value
function参数是一个有两个参数的函数,reduce依次从sequence中取一个元素,和上一次调用function的结果做参数再次调用function。
第一次调用function时,如果提供initial参数,会以sequence中的第一个元素和initial作为参数调用function,否则会以序列sequence中的前两个元素做参数调用function。
reduce(lambda x, y: x + y, [2, 3, 4, 5, 6], 1)
结果为21( (((((1+2)+3)+4)+5)+6) )
reduce(lambda x, y: x + y, [2, 3, 4, 5, 6])
结果为20
注意function函数不能为None。
'''
#ret = reduce(lambda x,(y,z):x|(z<<y),enumerate(mp),0)
print ret
return ret
#im.save("aaa.jpg")
# im = im.resize
'''
11011 i=0
11010 &
------
11010 i=1
11001 &
------
11000 i=2
10111 &
------
10000 i=3
01111 &
-------
0 i=4
11010 i=0
11001 &
-----
11000 i=1
10111 &
-----
10000 i=2
01111 &
-----
0 i=3
'''
def hamming(h1,h2):
h,d = 0,h1^h2
while d: #判断h里面有几个1 也就是判断h1,h2中有多少位是不同的
h+=1
d&=d-1
return h
if __name__=='__main__':
if len(sys.argv)<=1 or len(sys.argv) >3:
print "Usage: %s image.jpg [dir]" % sys.argv[0]
else:
im,wd = sys.argv[1],'.' if len(sys.argv) <3 else sys.argv[2]
h = avhash(im)
os.chdir(wd)
images = []
for ext in EXTS:
images.extend(glob.glob('*.%s'%ext))
#print images
seq = []
prog = int (len(images)>50 and sys.stdout.isatty())
print prog
for f in images:
seq.append((f,hamming(avhash(f),h)))
if prog:
perc=100. *prog/len(images)
x=int(2*prec/5)
print '\rcalculating...['+'#'*x+' ' *(40-x)+']'
print '%.2f%%'%prec,'(%d/%d)'%(prog,len(images))
sys.stdout.flush
prog+=1
if prog:print
for f,ham in sorted(seq,key=lambda i:i[1]):
print "%d\t%s" %(ham,f)

本文介绍如何使用Python语言编写图像哈希算法的代码,包括图像预处理、计算平均值、二值化等步骤,并通过哈明距离比较不同图像的相似度。
138

被折叠的 条评论
为什么被折叠?



