python 判斷圖片相似度一個十分簡單的示例
http://www.thinksaas.cn/topics/0/399/399804.html
python 判斷圖片相似度一個十分簡單的示例,只是個例子,精度可能不是很高。主要介紹一下原理:先將圖片轉為 12x12像素的灰度圖片--獲取圖片平均灰度--遍歷圖片內部10x10像素(去掉周圍1像素)--比較每一個像素與平均值大小--如果大則字符串加1不然加0(這里我選用字符串保存,其實方法很多的)--接下去就是遍歷文件夾中圖片了,比較相似度,返回相似度了
from PIL import Image import os #import hashlib def getGray(image_file): tmpls=[] for h in range(0, image_file.size[1]):#h for w in range(0, image_file.size[0]):#w tmpls.append( image_file.getpixel((w,h)) ) return tmpls def getAvg(ls):#獲取平均灰度值 return sum(ls)/len(ls) def getMH(a,b):#比較64個字符有幾個字符相同 dist = 0; for i in range(0,len(a)): if a[i]==b[i]: dist=dist+1 return dist def getImgHash(fne): image_file = Image.open(fne) # 打開 image_file=image_file.resize((12, 12))#重置圖片大小我12px X 12px image_file=image_file.convert("L")#轉256灰度圖 Grayls=getGray(image_file)#灰度集合 avg=getAvg(Grayls)#灰度平均值 bitls=''#接收獲取0或1 #除去變寬1px遍歷像素 for h in range(1, image_file.size[1]-1):#h for w in range(1, image_file.size[0]-1):#w if image_file.getpixel((w,h))>=avg:#像素的值比較平均值 大於記為1 小於記為0 bitls=bitls+'1' else: bitls=bitls+'0' return bitls ''' m2 = hashlib.md5() m2.update(bitls) print m2.hexdigest(),bitls return m2.hexdigest() ''' a=getImgHash("./Test/測試圖片.jpg")#圖片地址自行替換 files = os.listdir("./Test")#圖片文件夾地址自行替換 for file in files: b=getImgHash("./Test/"+str(file)) compare=getMH(a,b) print file,u'相似度',str(compare)+'%'