How to find description/caption of a given image

Microsoft had recently exposed Computer Vision API. This feature returns information about visual content found in an image. Use tagging, descriptions and domain-specific models to identify content and label it with confidence.

This is the Java code to access this 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;
 
public class MicrosoftImageCaption {
	public static void main(String[] args) throws Exception {
 
		HttpClient httpclient = new DefaultHttpClient();
 
		try {
			URIBuilder builder = new URIBuilder(
					"https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze");
 
			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("Ocp-Apim-Subscription-Key",
					"YOUR_KEY_HERE");
 
			// Request body. Replace the example URL with the URL for the JPEG
			// image of a celebrity.
			StringEntity reqEntity = new StringEntity(
					"{\"url\":\"https://scontent.fblr1-1.fna.fbcdn.net/v/t1.0-9/17951456_1786485384698844_6758752912486809777_n.jpg?oh=9fd489b43def3d7661cb5090799466a9&oe=59B82B36\"}");
			request.setEntity(reqEntity);
 
			HttpResponse response = httpclient.execute(request);
			HttpEntity entity = response.getEntity();
 
			if (entity != null) {
				String resp = EntityUtils.toString(entity);
				String text = Json.createReader(
						new StringReader(resp)).readObject().getJsonObject("description").getJsonArray("captions").getJsonObject(0).getString("text");
				System.out.println(text);
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
}

You can get your keys by subscribing to Microsoft APIs here : Microsoft API

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 *