首页 > 解决方案 > 将位哈希转换为十六进制,然后再转换回位哈希

问题描述

我正在构建一个帮助查找重复图像的工具。要使用 bktree,我需要使用位散列,但是,最好将较大的位散列压缩成较小的十六进制散列进行存储。

位哈希如下所示: dhash_bits = 19965419413067491224447942902196404479

位哈希的十六进制哈希如下所示: dhash_hex = 0f05332d4d0b471500007722dc7300ff

我尝试使用bin(int(dhash_hex,16))将十六进制哈希转换回位,但我知道这不是正确的方法。

将十六进制哈希转换回位哈希的正确方法是什么?

这是将位转换为十六进制的函数:

def format_hex(row_hash, col_hash, size=8):
    hex_length = size * size // 4
    return '{0:0{2}x}{1:0{2}x}'.format(row_hash, col_hash, hex_length)

标签: pythonpython-3.ximage-processinghashbit-manipulation

解决方案


Your dhash_bits is just a single integer; the corresponding dhash_hex value is also achievable with

dhash_hex = format(dhash_bits, '032x')

Presumably you used the dhash_int() function to obtain it.

The inverse operation then is to just convert the hex back to an integer:

dhash_bits = int(dhash_hex, 16)

Your format_hex() function combines the two numbers for the row and column hashes into a single string; you'd get the two separate numbers again by applying int() to each half:

row_hash = int(dhash_hex[:len(dhash_hex) // 2], 16)
col_hash = int(dhash_hex[len(dhash_hex) // 2:], 16)

推荐阅读