How to compare and match faces in Java

Facial matching is an excellent way to implement photo sorting or face unlock features in an app. Normally this technology is locked behind some tedious coding and time-consuming AI training. However, an easy shortcut exists, which we will be looking at in this post. We will be using one of our APIs to instantly unlock this functionality and begin using it immediately. Altogether it should take 5 minutes.

Add two references in Maven POM so that Jitpack can set up our library.

First reference:


Second reference:


Now we need to use the function faceCompare and provide it with two images. matchFace is our starting image, and inputImage is the face that will be compared.

// Import classes://import com.cloudmersive.client.invoker.ApiClient;//import com.cloudmersive.client.invoker.ApiException;//import com.cloudmersive.client.invoker.Configuration;//import com.cloudmersive.client.invoker.auth.*;//import com.cloudmersive.client.FaceApi;ApiClient defaultClient = Configuration.getDefaultApiClient();// Configure API key authorization: ApikeyApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");Apikey.setApiKey("YOUR API KEY");// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)//Apikey.setApiKeyPrefix("Token");FaceApi apiInstance = new FaceApi();File inputImage = new File("/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.File matchFace = new File("/path/to/file"); // File | Image of a single face to compare and match against.try {FaceCompareResponse result = apiInstance.faceCompare(inputImage, matchFace);System.out.println(result);} catch (ApiException e) {System.err.println("Exception when calling FaceApi#faceCompare");e.printStackTrace();}

Done! Let’s take a look at an example output for these two images:

Image for post
Image for post
Image for post
Image for post

Here is our output:

"Successful": true,
"Faces": [
"LeftX": 229,
"TopY": 69,
"RightX": 301,
"BottomY": 141,
"HighConfidenceMatch": true,
"MatchScore": 0.7701233476400375
"FaceCount": 1,
"ErrorDetails": null

As you can see, the faces were given a high confidence match, despite the lightning conditions of each photo being very different. Note that the inputImage can have multiple faces, each of which will be given a rating.

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