Contents Focused On

What is Cognitive Services (Project Oxford)

Microsoft Cognitive Services, formerly known as Project Oxford, is a set of machine-learning application programming interfaces (REST APIs), SDKs, and services that helps developers to make smarter application by add intelligent features – such as, emotion and video detection; facial, speech, and vision recognition; and speech and language understanding.

Get more details from website.

What is Face API?

In Microsoft Cognitive Services, there are four main components.

  1. Face recognition recognizes faces in photos; groups faces that look alike; and verifies whether two faces are the same.
  2. Speech processing recognizes speech and translates it into text, and vice versa.
  3. Visual tools analyze visual content to look for things like inappropriate content or a dominant color scheme, and
  4. Language Understanding Intelligent Service (LUIS) understands what users mean when they say or type something using natural, everyday language.

Get more details from the Microsoft blog. We will implement Face recognition API in our sample application. So what is Face API?

Face API, is a cloud-based service that provides the most advanced face algorithms to detect and recognize human faces in images.

Face API has,

  1. Face Detection
  2. Face Verification
  3. Similar Face Searching
  4. Face Grouping
  5. Face Identification

Get a detailed overview here.

Face Detection

In this post, we are focusing on detecting faces so before we deal with the sample application, let’s take a closer look on API Reference (Face API - V1.0). To enable the services, we need to get an authorization key (API Key) by signing up with the service for free. Go to the link for signup.

Sign Up for Face API

Sign up using anyone by clicking on it.

After successfully joining, it will redirect to subscriptions page. Request new trials for any of the products by selecting the checkbox.

Process: Click on Request new trials > Face - Preview > Agree Term > Subscribe

Here, you can see that I have attached a screenshot of my subscription. In the Keys column, from Key 1, click on “Show” to preview the API Key. Then, click “Copy” to copy the key for further use.

Key can be regenerated by clicking on “Regenerate”.


So far, we are done with the subscription process. Now, let’s get started with the ASP.NET MVC sample application.

Create Sample Application

Before starting the experiment, let’s make sure that Visual Studio 2015 is installed on the development machine.

Now, let’s open Visual Studio 2015. From the File menu, click on New > Project.


Select ASP.NET Web application, name it as you like, I just named it “FaceAPI_MVC”. Click OK button to proceed for next step.

Choose empty template for the sample application, select “MVC” check box, then click OK.


In our empty template, let’s now create MVC Controller and generate views by scaffolding.



Add AngularJS

We need to add packages in our sample application. To do that, go to Solution Explorer and right click on Project > Manage NuGet Package.


In "Package Manager", search by typing “angularjs”, select package, then click "Install".


After installing “angularjs” package, we need to reference it in our layout page. Also, we need to define app root using “ng-app” directive.


If you are new to AngularJS, please get a basic overview on AngularJS with MVC application from here.

Install & Configure the Face API

We need to add “Microsoft.ProjectOxford.Face” library in our sample application. Type and search like below screen, then select and Install.


Web.Config

In application Web.Config, add a new configuration setting in appSettings section with our previously generated API Key.

  1. <add key="FaceServiceKey" value="XXXXXXXXXXXXXXXXXXXXXXXXXXX" />

Finally, appSettings

  1. <appSettings>
  2. <add key="webpages:Version" value="3.0.0.0" />
  3. <add key="webpages:Enabled" value="false" />
  4. <add key="PreserveLoginUrl" value="true" />
  5. <add key="ClientValidationEnabled" value="true" />
  6. <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  7. <add key="FaceServiceKey" value="xxxxxxxxxxxxxxxxxxxxxxxxxxx" /> <!--replace with API Key-->
  8. </appSettings>

MVC Controller

This is where we are performing our main operation. First of all, get FaceServiceKey Value from web.config by ConfigurationManager.AppSettings.

  1. private static string ServiceKey = ConfigurationManager.AppSettings["FaceServiceKey"];

Here, in MVC Controller, we have two main methods to perform the face detection operation. One is HttpPost method, which is used for uploading the image file to folder and the other one is HttpGet method, used to get uploaded image and detecting faces by calling API Service.

Both the methods are getting called from client script while uploading image to detect faces. Let’s explain the steps.

Image Upload

This method is responsible for uploading images.

  1. [HttpPost]
  2. public JsonResult SaveCandidateFiles()
  3. {
  4. //Create Directory if Not Exist
  5. //Requested File Collection
  6. //Clear Folder
  7. //Save File in Folder
  8. }

Image Detect

This method is responsible for detecting the faces from uploaded images.

  1. [HttpGet]
  2. public async Task<dynamic> GetDetectedFaces()
  3. {
  4. // Open an existing file for reading
  5. // Create Instance of Service Client by passing Servicekey as parameter in constructor
  6. // Call detection REST API
  7. // Create & Save Cropped Detected Face Images
  8. // Convert detection result into UI binding object
  9. }

This is the code snippet where the Face API is getting called to detect the face from uploaded image.

  1. // Open an existing file for reading
  2. var fStream = System.IO.File.OpenRead(FullImgPath)
  3. // Create Instance of Service Client by passing Servicekey as parameter in constructor
  4. var faceServiceClient = new FaceServiceClient(ServiceKey);
  5. // Call detection REST API
  6. Face[] faces = await faceServiceClient.DetectAsync(fStream, true, true, new FaceAttributeType[] { FaceAttributeType.Gender, FaceAttributeType.Age, FaceAttributeType.Smile, FaceAttributeType.Glasses });

Create & Save Cropped detected face images.

  1. var croppedImg = Convert.ToString(Guid.NewGuid()) + ".jpeg" as string;
  2. var croppedImgPath = directory + '/' + croppedImg as string;
  3. var croppedImgFullPath = Server.MapPath(directory) + '/' + croppedImg as string;
  4. CroppedFace = CropBitmap(
  5. (Bitmap)Image.FromFile(FullImgPath),
  6. face.FaceRectangle.Left,
  7. face.FaceRectangle.Top,
  8. face.FaceRectangle.Width,
  9. face.FaceRectangle.Height);
  10. CroppedFace.Save(croppedImgFullPath, ImageFormat.Jpeg);
  11. if (CroppedFace != null)
  12. ((IDisposable)CroppedFace).Dispose();

Method that is cropping images according to face values.

  1. public Bitmap CropBitmap(Bitmap bitmap, int cropX, int cropY, int cropWidth, int cropHeight)
  2. {
  3. // Crop Images
  4. }

Finally Full MVC Controller

  1. public class FaceDetectionController : Controller
  2. {
  3. private static string ServiceKey = ConfigurationManager.AppSettings["FaceServiceKey"];
  4. private static string directory = "../UploadedFiles";
  5. private static string UplImageName = string.Empty;
  6. private ObservableCollection<vmFace> _detectedFaces = new ObservableCollection<vmFace>();
  7. private ObservableCollection<vmFace> _resultCollection = new ObservableCollection<vmFace>();
  8. public ObservableCollection<vmFace> DetectedFaces
  9. {
  10. get
  11. {
  12. return _detectedFaces;
  13. }
  14. }
  15. public ObservableCollection<vmFace> ResultCollection
  16. {
  17. get
  18. {
  19. return _resultCollection;
  20. }
  21. }
  22. public int MaxImageSize
  23. {
  24. get
  25. {
  26. return 450;
  27. }
  28. }
  29. // GET: FaceDetection
  30. public ActionResult Index()
  31. {
  32. return View();
  33. }
  34. [HttpPost]
  35. public JsonResult SaveCandidateFiles()
  36. {
  37. string message = string.Empty, fileName = string.Empty, actualFileName = string.Empty; bool flag = false;
  38. //Requested File Collection
  39. HttpFileCollection fileRequested = System.Web.HttpContext.Current.Request.Files;
  40. if (fileRequested != null)
  41. {
  42. //Create New Folder
  43. CreateDirectory();
  44. //Clear Existing File in Folder
  45. ClearDirectory();
  46. for (int i = 0; i < fileRequested.Count; i++)
  47. {
  48. var file = Request.Files[i];
  49. actualFileName = file.FileName;
  50. fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
  51. int size = file.ContentLength;
  52. try
  53. {
  54. file.SaveAs(Path.Combine(Server.MapPath(directory), fileName));
  55. message = "File uploaded successfully";
  56. UplImageName = fileName;
  57. flag = true;
  58. }
  59. catch (Exception)
  60. {
  61. message = "File upload failed! Please try again";
  62. }
  63. }
  64. }
  65. return new JsonResult
  66. {
  67. Data = new
  68. {
  69. Message = message,
  70. UplImageName = fileName,
  71. Status = flag
  72. }
  73. };
  74. }
  75. [HttpGet]
  76. public async Task<dynamic> GetDetectedFaces()
  77. {
  78. ResultCollection.Clear();
  79. DetectedFaces.Clear();
  80. var DetectedResultsInText = string.Format("Detecting...");
  81. var FullImgPath = Server.MapPath(directory) + '/' + UplImageName as string;
  82. var QueryFaceImageUrl = directory + '/' + UplImageName;
  83. if (UplImageName != "")
  84. {
  85. //Create New Folder
  86. CreateDirectory();
  87. try
  88. {
  89. // Call detection REST API
  90. using (var fStream = System.IO.File.OpenRead(FullImgPath))
  91. {
  92. // User picked one image
  93. var imageInfo = UIHelper.GetImageInfoForRendering(FullImgPath);
  94. // Create Instance of Service Client by passing Servicekey as parameter in constructor
  95. var faceServiceClient = new FaceServiceClient(ServiceKey);
  96. Face[] faces = await faceServiceClient.DetectAsync(fStream, true, true, new FaceAttributeType[] { FaceAttributeType.Gender, FaceAttributeType.Age, FaceAttributeType.Smile, FaceAttributeType.Glasses });
  97. DetectedResultsInText = string.Format("{0} face(s) has been detected!!", faces.Length);
  98. Bitmap CroppedFace = null;
  99. foreach (var face in faces)
  100. {
  101. //Create & Save Cropped Images
  102. var croppedImg = Convert.ToString(Guid.NewGuid()) + ".jpeg" as string;
  103. var croppedImgPath = directory + '/' + croppedImg as string;
  104. var croppedImgFullPath = Server.MapPath(directory) + '/' + croppedImg as string;
  105. CroppedFace = CropBitmap(
  106. (Bitmap)Image.FromFile(FullImgPath),
  107. face.FaceRectangle.Left,
  108. face.FaceRectangle.Top,
  109. face.FaceRectangle.Width,
  110. face.FaceRectangle.Height);
  111. CroppedFace.Save(croppedImgFullPath, ImageFormat.Jpeg);
  112. if (CroppedFace != null)
  113. ((IDisposable)CroppedFace).Dispose();
  114. DetectedFaces.Add(new vmFace()
  115. {
  116. ImagePath = FullImgPath,
  117. FileName = croppedImg,
  118. FilePath = croppedImgPath,
  119. Left = face.FaceRectangle.Left,
  120. Top = face.FaceRectangle.Top,
  121. Width = face.FaceRectangle.Width,
  122. Height = face.FaceRectangle.Height,
  123. FaceId = face.FaceId.ToString(),
  124. Gender = face.FaceAttributes.Gender,
  125. Age = string.Format("{0:#} years old", face.FaceAttributes.Age),
  126. IsSmiling = face.FaceAttributes.Smile > 0.0 ? "Smile" : "Not Smile",
  127. Glasses = face.FaceAttributes.Glasses.ToString(),
  128. });
  129. }
  130. // Convert detection result into UI binding object for rendering
  131. var rectFaces = UIHelper.CalculateFaceRectangleForRendering(faces, MaxImageSize, imageInfo);
  132. foreach (var face in rectFaces)
  133. {
  134. ResultCollection.Add(face);
  135. }
  136. }
  137. }
  138. catch (FaceAPIException)
  139. {
  140. //do exception work
  141. }
  142. }
  143. return new JsonResult
  144. {
  145. Data = new
  146. {
  147. QueryFaceImage = QueryFaceImageUrl,
  148. MaxImageSize = MaxImageSize,
  149. FaceInfo = DetectedFaces,
  150. FaceRectangles = ResultCollection,
  151. DetectedResults = DetectedResultsInText
  152. },
  153. JsonRequestBehavior = JsonRequestBehavior.AllowGet
  154. };
  155. }
  156. public Bitmap CropBitmap(Bitmap bitmap, int cropX, int cropY, int cropWidth, int cropHeight)
  157. {
  158. Rectangle rect = new Rectangle(cropX, cropY, cropWidth, cropHeight);
  159. Bitmap cropped = bitmap.Clone(rect, bitmap.PixelFormat);
  160. return cropped;
  161. }
  162. public void CreateDirectory()
  163. {
  164. bool exists = System.IO.Directory.Exists(Server.MapPath(directory));
  165. if (!exists)
  166. {
  167. try
  168. {
  169. Directory.CreateDirectory(Server.MapPath(directory));
  170. }
  171. catch (Exception ex)
  172. {
  173. ex.ToString();
  174. }
  175. }
  176. }
  177. public void ClearDirectory()
  178. {
  179. DirectoryInfo dir = new DirectoryInfo(Path.Combine(Server.MapPath(directory)));
  180. var files = dir.GetFiles();
  181. if (files.Length > 0)
  182. {
  183. try
  184. {
  185. foreach (FileInfo fi in dir.GetFiles())
  186. {
  187. GC.Collect();
  188. GC.WaitForPendingFinalizers();
  189. fi.Delete();
  190. }
  191. }
  192. catch (Exception ex)
  193. {
  194. ex.ToString();
  195. }
  196. }
  197. }
  198. }

UI Helper

  1. /// <summary>
  2. /// UI helper functions
  3. /// </summary>
  4. internal static class UIHelper
  5. {
  6. #region Methods
  7. /// <summary>
  8. /// Calculate the rendering face rectangle
  9. /// </summary>
  10. /// <param name="faces">Detected face from service</param>
  11. /// <param name="maxSize">Image rendering size</param>
  12. /// <param name="imageInfo">Image width and height</param>
  13. /// <returns>Face structure for rendering</returns>
  14. public static IEnumerable<vmFace> CalculateFaceRectangleForRendering(IEnumerable<Microsoft.ProjectOxford.Face.Contract.Face> faces, int maxSize, Tuple<int, int> imageInfo)
  15. {
  16. var imageWidth = imageInfo.Item1;
  17. var imageHeight = imageInfo.Item2;
  18. float ratio = (float)imageWidth / imageHeight;
  19. int uiWidth = 0;
  20. int uiHeight = 0;
  21. uiWidth = maxSize;
  22. uiHeight = (int)(maxSize / ratio);

  23. float scale = (float)uiWidth / imageWidth;
  24. foreach (var face in faces)
  25. {
  26. yield return new vmFace()
  27. {
  28. FaceId = face.FaceId.ToString(),
  29. Left = (int)(face.FaceRectangle.Left * scale),
  30. Top = (int)(face.FaceRectangle.Top * scale),
  31. Height = (int)(face.FaceRectangle.Height * scale),
  32. Width = (int)(face.FaceRectangle.Width * scale),
  33. };
  34. }
  35. }
  36. /// <summary>
  37. /// Get image basic information for further rendering usage
  38. /// </summary>
  39. /// <param name="imageFilePath">Path to the image file</param>
  40. /// <returns>Image width and height</returns>
  41. public static Tuple<int, int> GetImageInfoForRendering(string imageFilePath)
  42. {
  43. try
  44. {
  45. using (var s = File.OpenRead(imageFilePath))
  46. {
  47. JpegBitmapDecoder decoder = new JpegBitmapDecoder(s, BitmapCreateOptions.None, BitmapCacheOption.None);
  48. var frame = decoder.Frames.First();
  49. // Store image width and height for following rendering
  50. return new Tuple<int, int>(frame.PixelWidth, frame.PixelHeight);
  51. }
  52. }
  53. catch
  54. {
  55. return new Tuple<int, int>(0, 0);
  56. }
  57. }
  58. #endregion Methods
  59. }

MVC View

  1. @{
  2. ViewBag.Title = "Face Detection";
  3. }
  4. <div ng-controller="faceDetectionCtrl">
  5. <h3>{{Title}}</h3>
  6. <div class="loadmore">
  7. <div ng-show="loaderMoreupl" ng-class="result">
  8. <img src="~/Content/ng-loader.gif" /> {{uplMessage}}
  9. </div>
  10. </div>
  11. <div class="clearfix"></div>
  12. <table style="width:100%">
  13. <tr>
  14. <th><h4>Select Query Face</h4></th>
  15. <th><h4>Detection Result</h4></th>
  16. </tr>
  17. <tr>
  18. <td style="width:60%" valign="top">
  19. <form novalidate name="f1">
  20. <input type="file" name="file" accept="image/*" onchange="angular.element(this).scope().selectCandidateFileforUpload(this.files)" required />
  21. </form>
  22. <div class="clearfix"></div>
  23. <div class="loadmore">
  24. <div ng-show="loaderMore" ng-class="result">
  25. <img src="~/Content/ng-loader.gif" /> {{faceMessage}}
  26. </div>
  27. </div>
  28. <div class="clearfix"></div>
  29. <div class="facePreview_thumb_big" id="faceCanvas"></div>
  30. </td>
  31. <td style="width:40%" valign="top">
  32. <p>{{DetectedResultsMessage}}</p>
  33. <hr />
  34. <div class="clearfix"></div>
  35. <div class="facePreview_thumb_small">
  36. <div ng-repeat="item in DetectedFaces" class="col-sm-12">
  37. <div class="col-sm-3">
  38. <img ng-src="{{item.FilePath}}" width="100" />
  39. </div>
  40. <div class="col-sm-8">
  41. <ul>
  42. @*<li>FaceId: {{item.FaceId}}</li>*@
  43. <li>Age: {{item.Age}}</li>
  44. <li>Gender: {{item.Gender}}</li>
  45. <li>{{item.IsSmiling}}</li>
  46. <li>{{item.Glasses}}</li>
  47. </ul>
  48. </div>
  49. <div class="clearfix"></div>
  50. </div>
  51. </div>
  52. <div ng-hide="DetectedFaces.length">No face detected!!</div>
  53. </td>
  54. </tr>
  55. </table>
  56. </div>
  57. @section NgScript{
  58. <script src="~/ScriptsNg/FaceDetectionCtrl.js"></script>
  59. }

Angular Controller

  1. angular.module('myFaceApp', [])
  2. .controller('faceDetectionCtrl', function ($scope, FileUploadService) {
  3. $scope.Title = 'Microsoft FaceAPI - Face Detection';
  4. $scope.DetectedResultsMessage = 'No result found!!';
  5. $scope.SelectedFileForUpload = null;
  6. $scope.UploadedFiles = [];
  7. $scope.SimilarFace = [];
  8. $scope.FaceRectangles = [];
  9. $scope.DetectedFaces = [];
  10. //File Select & Save
  11. $scope.selectCandidateFileforUpload = function (file) {
  12. $scope.SelectedFileForUpload = file;
  13. $scope.loaderMoreupl = true;
  14. $scope.uplMessage = 'Uploading, please wait....!';
  15. $scope.result = "color-red";
  16. //Save File
  17. var uploaderUrl = "/FaceDetection/SaveCandidateFiles";
  18. var fileSave = FileUploadService.UploadFile($scope.SelectedFileForUpload, uploaderUrl);
  19. fileSave.then(function (response) {
  20. if (response.data.Status) {
  21. $scope.GetDetectedFaces();
  22. angular.forEach(angular.element("input[type='file']"), function (inputElem) {
  23. angular.element(inputElem).val(null);
  24. });
  25. $scope.f1.$setPristine();
  26. $scope.uplMessage = response.data.Message;
  27. $scope.loaderMoreupl = false;
  28. }
  29. },
  30. function (error) {
  31. console.warn("Error: " + error);
  32. });
  33. }
  34. //Get Detected Faces
  35. $scope.GetDetectedFaces = function () {
  36. $scope.loaderMore = true;
  37. $scope.faceMessage = 'Preparing, detecting faces, please wait....!';
  38. $scope.result = "color-red";
  39. var fileUrl = "/FaceDetection/GetDetectedFaces";
  40. var fileView = FileUploadService.GetUploadedFile(fileUrl);
  41. fileView.then(function (response) {
  42. $scope.QueryFace = response.data.QueryFaceImage;
  43. $scope.DetectedResultsMessage = response.data.DetectedResults;
  44. $scope.DetectedFaces = response.data.FaceInfo;
  45. $scope.FaceRectangles = response.data.FaceRectangles;
  46. $scope.loaderMore = false;
  47. //Reset element
  48. $('#faceCanvas_img').remove();
  49. $('.divRectangle_box').remove();
  50. //get element byID
  51. var canvas = document.getElementById('faceCanvas');
  52. //add image element
  53. var elemImg = document.createElement("img");
  54. elemImg.setAttribute("src", $scope.QueryFace);
  55. elemImg.setAttribute("width", response.data.MaxImageSize);
  56. elemImg.id = 'faceCanvas_img';
  57. canvas.append(elemImg);
  58. //Loop with face rectangles
  59. angular.forEach($scope.FaceRectangles, function (imgs, i) {
  60. //console.log($scope.DetectedFaces[i])
  61. //Create rectangle for every face
  62. var divRectangle = document.createElement('div');
  63. var width = imgs.Width;
  64. var height = imgs.Height;
  65. var top = imgs.Top;
  66. var left = imgs.Left;
  67. //Style Div
  68. divRectangle.className = 'divRectangle_box';
  69. divRectangle.style.width = width + 'px';
  70. divRectangle.style.height = height + 'px';
  71. divRectangle.style.position = 'absolute';
  72. divRectangle.style.top = top + 'px';
  73. divRectangle.style.left = left + 'px';
  74. divRectangle.style.zIndex = '999';
  75. divRectangle.style.border = '1px solid #fff';
  76. divRectangle.style.margin = '0';
  77. divRectangle.id = 'divRectangle_' + (i + 1);
  78. //Generate rectangles
  79. canvas.append(divRectangle);
  80. });
  81. },
  82. function (error) {
  83. console.warn("Error: " + error);
  84. });
  85. };
  86. })
  87. .factory('FileUploadService', function ($http, $q) {
  88. var fact = {};
  89. fact.UploadFile = function (files, uploaderUrl) {
  90. var formData = new FormData();
  91. angular.forEach(files, function (f, i) {
  92. formData.append("file", files[i]);
  93. });
  94. var request = $http({
  95. method: "post",
  96. url: uploaderUrl,
  97. data: formData,
  98. withCredentials: true,
  99. headers: { 'Content-Type': undefined },
  100. transformRequest: angular.identity
  101. });
  102. return request;
  103. }
  104. fact.GetUploadedFile = function (fileUrl) {
  105. return $http.get(fileUrl);
  106. }
  107. return fact;
  108. })

Upload images to detect faces

Browse Image from local folder to upload and detect faces.



Mark faces in the image

Detected faces will be marked with white rectangle.


List detected faces with face information

List and separate the faces with detailed face information.

Summary

You have just seen how to call Face API to detect faces in an image. I hope this will help to make the application more smart and intelligent.

References