相似图片搜索的原理

时间:2022-02-09 17:06:07

具体内容可以看:点击打开链接


我自己写的代码:

import os
from PIL import Image
from functools import reduce
import matplotlib.pyplot as plt # plt 用于显示图片

#分割图片
def splitimage(src, rownum, colnum):
    img = Image.open(src)
    w, h = img.size
    res = []
    rowheight = h // rownum
    colwidth = w // colnum
    for r in range(rownum):
        for c in range(colnum):
            box = (c * colwidth, r * rowheight, (c + 1) * colwidth, (r + 1) * rowheight)
            res.append(img.crop(box))
    return res

#hash
def avhash(im, rotate = 0):
    if not isinstance(im, Image.Image):
        im = Image.open(im)
    im = im.rotate(rotate)
#    plt.imshow(im) # 显示图片
#    plt.show()
    im = im.resize((8, 8), Image.ANTIALIAS).convert('L')
    avg = reduce(lambda x, y: x + y, im.getdata()) / 64.
    h = 0
    for i in im.getdata():
        h *= 2
        if i >= avg:
            h += 1
    return h
    #return reduce(lambda x, (y, z): x | (z << y), enumerate(map(lambda i: 0 if i < avg else 1, im.getdata())), 0)

#求距离
def hamming(h1, h2):
    h, d = 0, h1 ^ h2
    while d:
        h += 1
        d &= d - 1
    return h