Alpacaboy
Alpacaboy

Reputation: 21

Microsoft cognitive services face API call

I've build an application on the Azure (microsoft) emotion API, but that was just merged with their cognitive services face API. I'm using a webcam to send an image (in binary data) to their server for analysis, and used to get an xml in return. (I've already commented out some old code, in this example. Trying to get it fixed).

function saveSnap(data){
    // Convert Webcam IMG to BASE64BINARY to send to EmotionAPI
    var file = data.substring(23).replace(' ', '+');
    var img = Base64Binary.decodeArrayBuffer(file);


    var ajax = new XMLHttpRequest();

    // On return of data call uploadcomplete function.
    ajax.addEventListener("load", function(event) {
      uploadcomplete(event);
    }, false);

    // AJAX POST request
    ajax.open("POST", "https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=emotion","image/jpg");
      ajax.setRequestHeader("Content-Type","application/json");
      //ajax.setRequestHeader("Accept","text/html,application/xhtml+xml,application/xml");
      ajax.setRequestHeader("Ocp-Apim-Subscription-Key","subscription_key");
      ajax.send(img);
}

now I understood from their website the call returns a JSON. But I just can't get it to work. I can see there is data coming back, but how do I even get the JSON out of it. I'm probably missing something essential, and hope someone can help me out. :) the program was working when I could still use the Emotion API.

function uploadcomplete(event){
  console.log("complete");
  console.log(event);
    //var xmlDoc = event.target.responseXML;
    //var list = xmlDoc.getElementsByTagName("scores");
  console.log(JSON.stringify(event));

Upvotes: 0

Views: 458

Answers (1)

cthrash
cthrash

Reputation: 2973

A few issues to address:

  1. You'll want to wait for the POST response, not just for the upload completion.
  2. You'll want to set the content type to be application/octet-stream if you are uploading a binary as you are.
  3. You'll want to set the subscription key to the real value (you probably did before pasting your code here.)

.

function saveSnap(data) {
  // Convert Webcam IMG to BASE64BINARY to send to EmotionAPI
  var file = data.substring(23).replace(' ', '+');
  var img = Base64Binary.decodeArrayBuffer(file);

  ajax = new XMLHttpRequest();

  ajax.onreadystatechange = function() {
    if (ajax.readyState == XMLHttpRequest.DONE) {
      console.log(JSON.stringify(ajax.response));
    }
  }

  ajax.open('post', 'https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=emotion');
  ajax.setRequestHeader('Content-Type', 'application/octet-stream');
  ajax.setRequestHeader('Ocp-Apim-Subscription-Key', key);
  ajax.send(img);
}

Upvotes: 0

Related Questions