Skip to content

Instantly share code, notes, and snippets.

@Azadehkhojandi
Created June 14, 2017 02:36
Show Gist options
  • Save Azadehkhojandi/1a5fc606419e33427293f3fd41b63d52 to your computer and use it in GitHub Desktop.
Save Azadehkhojandi/1a5fc606419e33427293f3fd41b63d52 to your computer and use it in GitHub Desktop.
how to call Microsoft cognitive services face api in unity
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Assets.Scripts.Models;
using UnityEngine;
//https://www.packtpub.com/books/content/using-rest-api-unity-part-1-what-rest-and-basic-queries
namespace Assets.Scripts.Services
{
public class FaceApiService
{
private readonly MonoBehaviour _caller;
private readonly string _queryString =
"returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=age,gender,facialhair,glasses,emotion"; //,
private string _faceApiUrl;
private string _results;
private Dictionary<string, string> _headers;
public FaceApiResultItemCollection Results
{
get
{
if (string.IsNullOrEmpty(_results) || _results == "[]")
{
return null;
}
FaceApiResultItemCollection resultObject = null;
try
{
//it's a hack there should be a better way
var temp = "{\"FaceApiResultItems\":" + _results + "}";
//add objects
resultObject = JsonUtility.FromJson<FaceApiResultItemCollection>(temp);
}
catch (Exception e)
{
Debug.Log(e.Message);
}
return resultObject;
}
}
public FaceApiService(MonoBehaviour caller, string faceApiUrl, string subscriptionKey)
{
_faceApiUrl = faceApiUrl;
if (!string.IsNullOrEmpty(_faceApiUrl) && !_faceApiUrl.EndsWith("/"))
{
_faceApiUrl = _faceApiUrl + "/";
}
_caller = caller;
_headers =
new Dictionary<string, string>
{
{"Ocp-Apim-Subscription-Key", subscriptionKey},
{"Content-Type", "application/octet-stream"}
};
}
internal WWW Detect(byte[] imageByteData, Action onCompleteCallback)
{
var requesturi = _faceApiUrl + "detect?" + _queryString;
var www = new WWW(requesturi, imageByteData, _headers);
_caller.StartCoroutine(WaitForRequest(www, onCompleteCallback));
return www;
}
public WWW Detect(string imageFilePath, Action onCompleteCallback)
{
var requesturi = _faceApiUrl + "detect?" + _queryString;
var byteData = GetImageAsByteArray(imageFilePath);
var www = new WWW(requesturi, byteData, _headers);
_caller.StartCoroutine(WaitForRequest(www, onCompleteCallback));
return www;
}
private byte[] GetImageAsByteArray(string imageFilePath)
{
var fileStream = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read);
var binaryReader = new BinaryReader(fileStream);
return binaryReader.ReadBytes((int)fileStream.Length);
}
private IEnumerator WaitForRequest(WWW www, Action onComplete)
{
yield return www;
// check for errors
if (string.IsNullOrEmpty(www.error))
{
_results = www.text;
if (!string.IsNullOrEmpty(www.error))
{
Debug.Log(_results);
Debug.Log(www.error);
}
onComplete();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment