How to Compare Two Images for Similarity in Python

Cloudmersive
2 min readApr 20, 2021

--

Identifying similarities in images can be an incredibly beneficial element of a company website or application. For example, if you have a retail website, the feature could provide product suggestions for users by comparing them to a previously purchased or viewed product. In order to automate the process and avoid the headache that normally accompanies manual identification, you can use an API in Python to generate an image similarity score. This score will be between 0 and 1 and will provide you with an informed perspective, thanks to Deep Learning AI.

We will begin the process by running this command to install the client:

pip install cloudmersive-image-api-client

Now we are ready to call our comparison 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))
base_image = '/path/to/inputfile' # file | Image file to compare against. Common file formats such as PNG, JPEG are supported.
comparison_image = '/path/to/inputfile' # file | Image to compare to the base image.
recognition_mode = 'recognition_mode_example' # str | Optional, specify the recognition mode; possible values are Normal, Basic and Advanced. Default is Normal. (optional)
try:
# Compare two images for similarity
api_response = api_instance.recognize_similarity_compare(base_image, comparison_image, recognition_mode=recognition_mode)
pprint(api_response)
except ApiException as e:
print("Exception when calling RecognizeApi->recognize_similarity_compare: %s\n" % e)

Note that you will need to input the base image, comparison image, recognition mode (optional — default is Normal), and API key in order for the operation to run smoothly. If you need to retrieve your API key, you can visit the Cloudmersive website to register for a free account; this will give you access to 800 calls/month across our entire library of APIs.

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

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

No responses yet