How to compare and match faces in Java

Cloudmersive
2 min readJan 21, 2020

--

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:

<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>

Second reference:

<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v2.75</version>
</dependency>
</dependencies>

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:

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.

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

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

No responses yet