Reputation: 5
I am new to Python and am writing an application to identify matching images. I am using the dHash algorithm to compare the hashes of images. I have seen in a tutorial the following lines of code:
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)
The two lines I am referring to are the difference line and the hash_Value line. As far as I understand, the first line checks to see if the left pixel has a greater intensity then the right pixel. How does it do this for the whole array? There is no for loop over the array to check each index. As for the second line, I think it is checking to see if the value is true and if it is, it is adding the value of 5^i to sum and then assigning that to image_hash.
I am new to Python and the syntax here is a little confusing. Can someone explain what the two lines above are doing? Is there a more readable way of writing this that will help me understand what the algorithm is doing and be more readable in future?
Upvotes: 0
Views: 167
Reputation: 156
To break it down, the first line pixel_difference = image_resized[0:, 1:] > image_resized[0:, :-1]
is basically doing the following:
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)
And the second line is doing this:
image_hash = 0
for i, value in enumerate(pixel_difference.flatten()):
if value:
image_hash += 5**i
print(image_hash)
Upvotes: 1