One of Microsoft Azure Cognitive Services, it reads emotions from people's faces such as photos. For more information here As of June 24, 2017, you can use it for free to some extent.
There is no particular reason. There is officially a sample implementation in Java, but since there was only one that sends the URL with the image, I tried the implementation of the method of sending the image directly.
Javaļ¼1.8.0_131 Emotion Api : 1.0
Register a subscription. Official site You can register by pressing Create from the tag "Trial version", and a 32-digit key will be issued. So save it.
Add the following:
pom.xml
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
Almost the same as the sample source, but implemented as follows. The method argument is a byte array of the image file. The result is returned as JSON to the caller.
EmotionApiClient.java
import java.net.URI;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class EmotionApiClient {
private final String KEY = "32-digit key issued above";
String postApi(byte[] image) {
HttpClient httpClient = HttpClientBuilder.create().build();
try
{
URIBuilder uriBuilder = new URIBuilder("https://westus.api.cognitive.microsoft.com/emotion/v1.0/recognize");
URI uri = uriBuilder.build();
HttpPost request = new HttpPost(uri);
request.setHeader("Content-Type", "application/octet-stream");
request.setHeader("Ocp-Apim-Subscription-Key", KEY);
ByteArrayEntity reqEntity = new ByteArrayEntity(image);
request.setEntity(reqEntity);
HttpResponse response = httpClient.execute(request);
//You should check the status.
HttpEntity entity = response.getEntity();
if (entity != null)
{
return EntityUtils.toString(entity);
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
return "";
}
}
It was easier than I imagined to implement. I would like to try to see how much it can be recognized in bright and dark places.
Recommended Posts