Python 差异哈希和理解这些代码行在做什么?

Python 差异哈希和理解这些代码行在做什么?,python,opencv,hash,Python,Opencv,Hash,我是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

我是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)
我指的两行是差异行和散列值行。据我所知,第一行检查左像素的强度是否大于右像素。它是如何对整个阵列执行此操作的?数组上没有for循环来检查每个索引。至于第二行,我认为它正在检查该值是否为真,如果为真,它将5^I的值相加到sum,然后将其分配给image\u hash


我是Python新手,这里的语法有点混乱有人能解释一下上面这两行在做什么吗?有没有一种更具可读性的方法来写这篇文章,可以帮助我理解算法在做什么,并在将来更具可读性?

要分解它,第一行
pixel\u difference=image\u resized[0:,1:]>image\u 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)

检查python(和numpy)slice操作符,它创建类似列表的对象的切片(也在1维以上),请向我们显示所用变量的来源<代码>类型(图像大小调整)请接受,请阅读并相应更新您的帖子。