How to Calculate the Similarity Between Image Hashes in Python

Cloudmersive
2 min readApr 20, 2021

Looking for a simple way to calculate the similarity between image hashes? In this brief tutorial, we will provide example code on how to use an API in Python to calculate the similarity between two perceptual image hashes by evaluating the Hamming Distance between them. To clarify, Hamming Distance (named after Richard Hamming) measures the minimum number of substitutions required to change one string into the other. This can be helpful when organizing, analyzing, and comparing images in a database.

Let’s kick things off by running this command to install the Python SDK:

pip install cloudmersive-image-api-client

Now we’re set up to call the function with the following code:

from __future__ import print_function
import time
import cloudmersive_image_api_client
from cloudmersive_image_api_client.rest import ApiException
from pprint import pprint
# Configure API key authorization: Apikey
configuration = cloudmersive_image_api_client.Configuration()
configuration.api_key['Apikey'] = 'YOUR_API_KEY'
# create an instance of the API class
api_instance = cloudmersive_image_api_client.RecognizeApi(cloudmersive_image_api_client.ApiClient(configuration))
request = cloudmersive_image_api_client.ImageSimilarityHashDistanceRequest() # ImageSimilarityHashDistanceRequest |
try:
# Calculates the similarity between two perceptual image hashes
api_response = api_instance.recognize_similarity_hash_distance(request)
pprint(api_response)
except ApiException as e:
print("Exception when calling RecognizeApi->recognize_similarity_hash_distance: %s\n" % e)

Process complete! All you need to input for the operation are the two image hashes and your API key. To retriever your API key, simply head to the Cloudmersive website to register for a free account.

--

--

Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.