Using Kairos API for face detection

There are many face detection/verification APIs available in the market. I have already covered Microsoft’s APIs for face detection here : Microsoft API for extracting image description.

But apart from few free API calls they are quite expensive, almost 1.5 dollars for every 1000 calls. Recently I found a cheap yet reliable API from Kairos where you can make almost 1 million free API calls per month.

So here is the sample code for face detection using Kairos API :

package images;
 
import java.io.StringReader;
import java.net.URI;
 
import javax.json.Json;
 
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.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
 
import com.restfb.json.JsonObject;
 
public class KairosFaceDetection {
	public static void main(String[] args) throws Exception {
 
		HttpClient httpclient = new DefaultHttpClient();
 
		try {
			String url = "https://api.kairos.com/detect?selector=FRONTAL";
			URIBuilder builder = new URIBuilder(url);
 
			builder.setParameter("visualFeatures", "Description,Tags");
			builder.setParameter("details", "Celebrities");
			builder.setParameter("language", "en");
 
			URI uri = builder.build();
			HttpPost request = new HttpPost(uri);
 
			// Request headers - replace this example key with your valid
			// subscription key.
			request.setHeader("Content-Type", "application/json");
			request.setHeader("app_id",
					"YOUR_APP_ID");
			request.setHeader("app_key",
					"YOUR_APP_KEY");
 
			// Request body. Replace the example URL with the URL for the JPEG
			// image of a celebrity.
			String u = "http://createurapp.com/sachin.jpg";
			StringEntity reqEntity = new StringEntity(
					"{\"image\":\""  + u +    "\"}");
			request.setEntity(reqEntity);
 
			HttpResponse response = httpclient.execute(request);
			HttpEntity entity = response.getEntity();
 
			if (entity != null) {
				String resp = EntityUtils.toString(entity);
				javax.json.JsonObject face= Json.createReader(
						new StringReader(resp)).readArray().getJsonObject(0).getJsonArray("faces").getJsonObject(0);
				int facex = face.getInt("topLeftX");
				int facey = face.getInt("topLeftY");
				int facewid = face.getInt("width");
				int facehei = face.getInt("height");
 
				//System.out.println(text);
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
}

You can easily get your app_id and app_key by signing up on their website here : Kairos

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *