How to detect faces in photo in Java

Cloudmersive
2 min readJan 20, 2020

Determining face locations in photos can have useful applications for anything from photo editing apps to web photo sorting systems. Normally this would be quite a process to set up from scratch, requiring hours of AI training and coding. Luckily, this is Cloudmersive, and we have an API for that. Let’s trim that work down to about 5 minutes instead.

First we need to use Jitpack to dynamically compile the library that we will need. To do this, we must set up references in Maven POM.

Repository:

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

Dependency:

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

Now we call the function faceLocate and let the API do our work for us:

// 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 imageFile = new File("/path/to/file"); // File | Image file to perform the operation on.  Common file formats such as PNG, JPEG are supported.try {FaceLocateResponse result = apiInstance.faceLocate(imageFile);System.out.println(result);} catch (ApiException e) {System.err.println("Exception when calling FaceApi#faceLocate");e.printStackTrace();}

That’s it! You’re done. Sure beats hours of setting this up from scratch, huh? Let’s examine a sample output for the following image:

Our response body:

{
"Successful": true,
"Faces": [
{
"LeftX": 1229,
"TopY": 745,
"RightX": 1333,
"BottomY": 849
},
{
"LeftX": 492,
"TopY": 722,
"RightX": 595,
"BottomY": 826
},
{
"LeftX": 1418,
"TopY": 410,
"RightX": 1504,
"BottomY": 496
},
{
"LeftX": 1888,
"TopY": 515,
"RightX": 1974,
"BottomY": 601
},
{
"LeftX": 676,
"TopY": 768,
"RightX": 780,
"BottomY": 872
},
{
"LeftX": 957,
"TopY": 745,
"RightX": 1043,
"BottomY": 832
},
{
"LeftX": 1197,
"TopY": 557,
"RightX": 1269,
"BottomY": 629
},
{
"LeftX": 688,
"TopY": 423,
"RightX": 791,
"BottomY": 526
}
],
"FaceCount": 8,
"ErrorDetails": null
}

As you can see, the function correctly identified and located all 8 faces in the photo.

--

--

Cloudmersive

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