python 创建图片指纹

安装:

pip install Pillow
pip install ImageHash

创建索引库:

def createDatabase(path):
    db = shelve.open(dataPath, writeback=True)
    pool = glob.glob(path+'*.jpg')+glob.glob(path+'*.png')
    for index, imagePath in enumerate(pool):
        image = Image.open(imagePath)
        h = str(imagehash.dhash(image))
        filename = imagePath[imagePath.rfind('/')+1:]
        try:
            findFiles = db[h]
        except:
            findFiles = None
        if findFiles!=None:
            continue
        else:
            image = Image.open(imagePath)
            image.show()
            db[h] = db.get(h,[])+[filename]
            print(index)
    db.close()

查相同图片:

def checkSame(path):
    db = shelve.open(dataPath, writeback=False)
    pool = glob.glob(path+'*.jpg')+glob.glob(path+'*.png')
    for index, imagePath in enumerate(pool):
        query = Image.open(imagePath)
        h = str(imagehash.dhash(query))
        filename = imagePath[imagePath.rfind('/')+1:]
        if db[h]:
            image = Image.open(imagePath)
            image.show()
            image = Image.open(imgPath+val[0])
            image.show()
    db.close()

查相似:

相似度查询:1 - (hash1 - hash2)/len(hash1.hash)**2,当两个图片越相似,此公式得到的值越趋近于0

def checkSimilar(path):
    db = shelve.open(dataPath, writeback=False)
    pool = glob.glob(path+'*.jpg')+glob.glob(path+'*.png')
    for index, imagePath in enumerate(pool):
        query = Image.open(imagePath)
        h = str(imagehash.dhash(query))
        filename = imagePath[imagePath.rfind('/')+1:]
        for key,val in db.items():
            h1 = imagehash.hex_to_hash(key)
            h2 = imagehash.hex_to_hash(h)
            similar = (h1 - h2)/len(h1.hash)**2
            if similar<.1 and val[0]!=filename:
                image = Image.open(imagePath)
                image.show()
                image = Image.open(imgPath+val[0])
                image.show()
    db.close()

参考:
shelveimage hashblog

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容