You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python计算两张虹膜阈值图像的汉明距离

计算两张虹膜阈值图像汉明距离的方法

虹膜识别场景下的汉明距离指两张二值虹膜图像对应像素值不同的数量占总有效像素的比例,数值越小代表两张虹膜相似度越高,通常小于0.32即可判定为同一虹膜。计算前需保证两张待对比图像经过完全相同的预处理流程,尺寸完全一致。

计算步骤

  • 读取两张已经处理完成的二值阈值图像,以灰度模式加载避免多通道干扰
  • 将像素值标准化为0/1矩阵:255值转换为1,0保持为0,方便后续异或计算
  • 对两个0/1矩阵做异或操作,结果中值为1的位置就是两张图像素不一致的位置
  • 统计异或结果中1的总数量,除以图像总像素数得到最终汉明距离

实现代码

import cv2 as cv
import numpy as np

# 读取两张预处理完成的阈值图像
img1 = cv.imread("foreground1.png", cv.IMREAD_GRAYSCALE)
img2 = cv.imread("foreground2.png", cv.IMREAD_GRAYSCALE)

# 校验图像尺寸一致性
if img1.shape != img2.shape:
    raise ValueError("两张图像尺寸不一致,请检查预处理流程参数")

# 转换为0/1二值矩阵
binary1 = img1 // 255
binary2 = img2 // 255

# 计算汉明距离
diff_pixel = np.bitwise_xor(binary1, binary2)
hamming_distance = np.sum(diff_pixel) / diff_pixel.size

print(f"两张虹膜图像的汉明距离为:{hamming_distance:.4f}")

可选优化:适配头部轻微旋转偏移

实际采集时用户头部轻微倾斜会导致极坐标展开的虹膜图像出现水平偏移,可加入循环偏移匹配取最小汉明距离,提升识别准确率:

min_hamming = 1.0
# 偏移范围±15像素可覆盖绝大多数正常旋转场景
for offset in range(-15, 16):
    shifted_binary2 = np.roll(binary2, offset, axis=1)
    current_diff = np.bitwise_xor(binary1, shifted_binary2)
    current_dist = np.sum(current_diff) / current_diff.size
    if current_dist < min_hamming:
        min_hamming = current_dist

print(f"角度匹配后的最小汉明距离为:{min_hamming:.4f}")

问题附带材料

阈值图像示例
以下为极坐标变换前的原始图像:
极坐标变换前原始图像

原有预处理代码参考:

img_crop1 = cv.imread('crop_1.png')
polar_img = cv.warpPolar(
    img_crop1, (256, 1024), (self.iris_1[0], self.iris_1[1]), self.iris_1[2] * 2, cv.WARP_POLAR_LINEAR)
# 逆时针旋转90度以提升视觉观感
polar_img = cv.rotate(polar_img, cv.ROTATE_90_COUNTERCLOCKWISE)

# 裁剪图像
polar_img = polar_img[int(polar_img.shape[0] / 2)
                      : polar_img.shape[0], 0: polar_img.shape[1]]
polar_img = cv.cvtColor(polar_img, cv.COLOR_BGR2GRAY)

_, threshold = cv.threshold(polar_img, 100, 255, cv.THRESH_BINARY)
cv.imwrite("foreground.png", threshold)

内容的提问来源于stack exchange,提问作者Mathis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 18:27:06