How to Detect the Age or Gender of People in an Image using Java

Cloudmersive
2 min readMay 10, 2022

--

If you’re looking to incorporate some useful facial recognition features into a Java application, we’ve got you covered. This article will highlight two useful iterations of our Facial Recognition API capable of detecting the gender and age range of identified human faces within an image. Below, instructions are included to easily call either API using code examples in Java.

Begin by installing the Maven SDK. First add a reference to the pom.xml repository:

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

After that, add one to the dependency in pom.xml:

<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v4.25</version>
</dependency>
</dependencies>

Once that’s done, it’s time to include the import classes and API key authentication snippet. An API key can be easily obtained by registering for a free account on our website (Home — Cloudmersive APIs).

// 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: Apikey
ApiKeyAuth 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");

Finally, it’s time to include either the gender or age-detecting functions. To detect gender, include the below:

FaceApi apiInstance = new FaceApi();
File imageFile = new File("/path/to/inputfile"); // File | Image file to perform the operation on. Common file formats such as PNG, JPEG are supported.
try {
GenderDetectionResult result = apiInstance.faceDetectGender(imageFile);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling FaceApi#faceDetectGender");
e.printStackTrace();
}

To detect age, use this instead:

FaceApi apiInstance = new FaceApi();
File imageFile = new File("/path/to/inputfile"); // File | Image file to perform the operation on. Common file formats such as PNG, JPEG are supported.
try {
AgeDetectionResult result = apiInstance.faceDetectAge(imageFile);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling FaceApi#faceDetectAge");
e.printStackTrace();
}

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

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

No responses yet