我正在使用 ImageHash获取图像哈希的模块。我有这段代码:
hashSize = 8
imghash3 = []
image = "pic1.jpg"
imghash1 = imagehash.phash(Image.open(image))
print(imghash1)
>>>d1d1f1f3f3737373
imghash2 = str(imagehash.phash(Image.open(image), hashSize))
print(imghash2)
>>>11b97c7eb158ac
imghash3.append(bin( int(imghash2, 16))[2:].zfill(64))
print(imghash3)
>>>['0000000000010001101110010111110001111110101100010101100010101100']
所以imagehash1就是模块的基本用法。
现在我不明白的是 hashSize 对 imagehash2 中的原始字符串做了什么样的转换,以及第三个函数如何转换 imagehash2 转换为 64 位字符串。
请您参考如下方法:
在 phash 计算过程中,原始图像被调整大小。 hashSize 参数主要控制调整后图像的高度和宽度。
算法可以查here .第一步(缩小尺寸)的实现:
image = image.convert("L").resize((hash_size, hash_size), Image.ANTIALIAS)
查看 imagehash.phash 的来源
让我们看看行 imghash3.append(bin( int(imghash2, 16))[2:].zfill(64)) 做了什么。
In [16]: imghash2 = '11b97c7eb158ac'
首先它将十六进制字符串转换为整数
In [17]: int(imghash2, 16)
Out[17]: 4989018956716204
内置 bin应用函数将整数转换为二进制字符串
In [18]: bin( int(imghash2, 16))
Out[18]: '0b10001101110010111110001111110101100010101100010101100'
使用 list slice 删除前两个字符
In [19]: bin( int(imghash2, 16))[2:]
Out[19]: '10001101110010111110001111110101100010101100010101100'
Adds 0在左边做一个总共有 64 个字符的字符串
In [20]: bin( int(imghash2, 16))[2:].zfill(64)
Out[20]: '0000000000010001101110010111110001111110101100010101100010101100'
