How to compare and match faces in Python

Let’s look at how to quickly harness machine learning to compare and match photographs of people’s faces. First, install with pip installer.

pip install git+https://github.com/Cloudmersive/Cloudmersive.APIClient.Python.ImageRecognition.git

Now we call face_compare. We enter a match_face image that we will be using for the comparison, as well as an input_image.

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'
# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# configuration.api_key_prefix['Apikey'] = 'Bearer'
# create an instance of the API class
api_instance = cloudmersive_image_api_client.FaceApi(cloudmersive_image_api_client.ApiClient(configuration))
input_image = '/path/to/file' # file | Image file to perform the operation on; this image can contain one or more faces which will be matched against face provided in the second image. Common file formats such as PNG, JPEG are supported.
match_face = '/path/to/file' # file | Image of a single face to compare and match against.
try:
# Compare and match faces
api_response = api_instance.face_compare(input_image, match_face)
pprint(api_response)
except ApiException as e:
print("Exception when calling FaceApi->face_compare: %s\n" % e)

Here is an example using the following match_face:

Image for post
Image for post

And this input_image:

Image for post
Image for post

Our results:

{
"ErrorDetails": null,
"Successful": true,
"Faces": [
{
"LeftX": 217,
"TopY": 217,
"RightX": 342,
"BottomY": 342,
"HighConfidenceMatch": true,
"MatchScore": 0.7541523724794388
}
],
"FaceCount": 1
}

As you can see, the function supports multiple faces in the input_image, and provides you with the location of each face and its score.

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store