Age detection of photos in Java
Automatic age detection has become quite accurate in recent years, and can be applied to anything from gathering user demographics to sorting photos. Today we will be skipping the difficult programming and AI training required to set this functionality up from scratch. Instead, we will have everything ready to go in under 5 minutes using an API.
First, add a repository and dependency reference for Jitpack in your Maven POM file so we can compile the library that we will need to use.
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>
Once that’s done, all that we need to do is call the function faceDetectAge.
// 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 {AgeDetectionResult result = apiInstance.faceDetectAge(imageFile);System.out.println(result);} catch (ApiException e) {System.err.println("Exception when calling FaceApi#faceDetectAge");e.printStackTrace();}
That’s it! Supply it with a file and you will be provided with the age of each person in the photo, along with location. Here’s an example output for this image:
{
"Successful": true,
"PeopleWithAge": [
{
"FaceLocation": {
"LeftX": 164,
"TopY": 198,
"RightX": 443,
"BottomY": 528
},
"AgeClassificationConfidence": 0.9,
"AgeClass": "25-32",
"Age": 26.44205093383789
}
],
"PeopleIdentified": 1
}
As you can see, we are given a general age range, confidence rating for that range, and a best guess at the exact age.