差异散列和理解这些代码行在做什么?

Difference hashing and understanding what these lines of code are doing?

我是 Python 的新手,正在编写一个应用程序来识别匹配的图像。我正在使用 dHash 算法来比较图像的哈希值。我在教程中看到了以下代码行:

import cv2 as cv
import numpy as np
import sys

hashSize = 8

img = cv.imread("Resources\test_image.jpg",0)

image_resized = cv.resize(img, (hashSize + 1, hashSize))
difference = image_resized[0:, 1:] > image_resized[0:, :-1]
hash_Value = sum([5**i for i, value in enumerate(difference.flatten())if value == True])

print(hash_Value)

我指的两条线是差异线和hash_Value线。据我了解,第一行检查左侧像素是否比右侧像素具有更大的强度。它是如何为整个阵列做到这一点的?数组上没有 for 循环来检查每个索引。至于第二行,我认为它正在检查该值是否为真,如果是,它会将 5^i 的值添加到 sum,然后将其分配给 image_hash.

我是 Python 的新手,这里的语法有点令人困惑。 谁能解释一下上面两行是做什么的?是否有更易读的方式来编写此代码,以帮助我理解算法的作用并在将来更具可读性?

为了分解它,第一行 pixel_difference = image_resized[0:, 1:] > image_resized[0:, :-1] 基本上是做以下事情:

import numpy as np # I assume you are using numpy.

# Suppose you have the following 2D arrays:
arr1 = np.array([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ])
arr2 = np.array([ [3, 1, 2], [5, 5, 4], [7, 7, 7] ])

# pixel_difference = image_resized[0:, 1:] > image_resized[0:, :-1]
# can be written as following:
m, n = arr1.shape # This will assign m = 3, n = 3.
pixel_difference = np.ndarray(shape=(m, n-1), dtype=bool) # Initializes m x (n-1) matrix.

for row in range(m):
    for col in range(n-1):
        pixel_difference[row, col] = arr1[row, col+1] > arr2[row, col]

print(pixel_difference)

第二行是这样做的:

image_hash = 0
for i, value in enumerate(pixel_difference.flatten()):
    if value:
        image_hash += 5**i

print(image_hash)