Utilizing Cordova Camera Plugin and MS-Cognitive Services in JavaScript for Face Detection through Face-API call

Over the last 48 hours, I have been trying to troubleshoot a problem with my Cordova android app for Face recognition using Microsoft Cognitive Services. To capture images, I utilized the Cordova Camera plugin and implemented JS for face detection and identification. In this post, I will walk through the code step by step. Below are my Content Security Policies:

<meta http-equiv="Content-Security-Policy" content="media-src * blob:; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src  'self' 'unsafe-inline' *">
 <meta name="format-detection" content="telephone=no">
 <meta name="msapplication-tap-highlight" content="no">
 <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">

Following the security policies, here is the standard HTML Code to display the button for capturing pictures:

<button id="take-picture-button">Take Picture</button>

Now, let's move on to the .js file which contains the logic for the Cordova Camera plugin events:

    bindEvents: function () {
    document.addEventListener('deviceready', this.onDeviceReady, false);
    document.addEventListener('pause', this.onPause, false);
    document.addEventListener('resume', this.onResume, false);
},
 onDeviceReady: function () {
    document.getElementById("take-picture-button").addEventListener("click", function () {
        appState.takingPicture = true; 
        navigator.camera.getPicture(cameraSuccessCallback, cameraFailureCallback,
            {
                sourceType: Camera.PictureSourceType.CAMERA,
                destinationType: Camera.DestinationType.FILE_URI,
                targetWidth: 500,
                targetHeight: 500
            });     });
},

Additionally, there are functions for onPause() and onResume(). The following code snippet showcases the AJAX call made to the MS-Cognitive services Face API for face detection. Note that image conversion into binary data is necessary before sending it in the POST request.

  var img = new Image();
img.src = imageUri;  

var canvas = document.createElement("canvas");
canvas.width = $(window).width();
canvas.height = $(window).height();

var ctx = canvas.getContext("2d");
img.onload = function () {
    ctx.drawImage(img, 0, 0);
}
var dataURL = canvas.toDataURL("image/jpeg");

var data = dataURL.split(',')[1];
var mimeType = dataURL.split(';')[0].slice(5)
var bytes = window.atob(data);
var buf = new ArrayBuffer(bytes.length);
var byteArr = new Uint8Array(buf);

for (var i = 0; i < bytes.length; i++) {
    byteArr[i] = bytes.charCodeAt(i);
}

var params = {
    "returnFaceId": "true",
    "returnFaceLandmarks": "false",
    "returnFaceAttributes": "age",
};

var faceIds = new Array();
$.ajax({
    url: "https://australiaeast.api.cognitive.microsoft.com/face/v1.0/detect?" + $.param(params),
    beforeSend: function (xhrObj) {
        xhrObj.setRequestHeader("Content-Type", "application/octet-stream");
        xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", "API_KEY");
    },
    type: "POST",
    data: byteArr,
    processData: false,
})
    .done(function (data) {
          for (var i = 0; i < data.length; i++) {
                faceIds.push(data.faceId);
                alert("FaceID at index"+ i+" is " + JSON.stringify(data.faceId[i]));
            }
    })
    .fail(function (jqXHR, textStatus, errorThrown) {
        alert("Failed in Face Detect, Details:  Status:: " + jqXHR.status + "  ResponseText:: " + jqXHR.statusText + "");
    });

The output of the above code is showing "Failed in Face Detect, Details: Status::400 ResponseText:: Bad Request". I am currently stuck and unsure where changes are needed or if something is missing. Your assistance would be greatly appreciated. Thank You

Answer №1

If an error occurs, the response will include a message indicating what went wrong. Potential causes of errors include InvalidImage and InvalidImageSize. For a comprehensive list of error codes and messages, please consult the documentation here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Iterate through various lists according to their respective sizes

I am working on a project that involves 6 lists of objects with varying sizes. My task is to iterate through all the lists in a specific order, starting from the smallest list to the largest one. var list_1 = [...] // length 24 var list_2 = [...] // ...

Tips for eliminating redundant code in Angular controllers

I have a dilemma with two controllers that are responsible for similar tasks. How can I efficiently eliminate code duplication? Initially, my attempt was to create a template method as an angular service. However, I noticed that it's not possible to ...

"Headers cannot be set once they have been sent to the client... Error handling for unhandled promise rejection

Having trouble with cookies in the header - specifically, encountering an error at line number 30. The error message reads: "Cannot set headers after they are sent to the client." Additionally, there is an UnhandledPromiseRejectionWarning related to a prom ...

Here's a unique version: "Discover the process of implementing click functionality, similar to ng-click, on a circle SVG

Within my JS file, I have some HTML text that is being returned to an HTML page. This HTML text contains a circle SVG element, which displays properly when retrieved from the API. When clicking on the circle, I want to call a JavaScript function in the sam ...

Whenever the page is refreshed, the vertical menu bar with an accordion feature hides the sub

I have designed a vertical accordion menu bar following the example at http://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_accordion_symbol However, I am encountering an issue where clicking on a button to display a submenu causes the page to refr ...

Solving the problem of Axis label alignment in Three.js grid and techniques for visualizing x, y, z data on

I have been tasked with plotting well deviation surveys on a 3D grid. After referencing several articles online, I successfully created a 3D grid of the required size. However, I am currently struggling with positioning the labels for the x, y, and z axis ...

Best practices for displaying a Multidimensional JSON Object using JavaScript

Within my current project, I have a JSON object structured as follows: { "face": [ { "attribute": { "age": { "range": 5, "value": 35 }, "gender": { "confidence ...

Arranging a collection of objects into a two-dimensional array

I've got an array of objects that I want to format in a way suitable for react-csv, specifically as a 2D array resembling a nested loop structure shown below: https://i.sstatic.net/41cuj.png The desired end result should look like this: [ ["Name", ...

Submitting a form using AJAX only works with the click event and not the submit event. However, when using the click event, the form fields are not validated

I am facing an issue with my classic form submission using Ajax. Currently, it only works with $("button").click(function(), which results in the fields not being validated properly. <script type="text/javascript"> $(document).ready(function(){ ...

How to stop the mobile keyboard from hiding in JavaScript

On a webpage, I have an HTML setup with an editor and buttons positioned above the keyboard: ------------ |1| Hello | |2| World | | | | | | | ------------ |Tab|( ) [ | ------------ |qwertyuiop| | asdfghkl | | zxcvbnm | | [ ] | ------- ...

What could be causing the issue of PHP not receiving this multidimensional array through Ajax?

Having an issue with receiving a multidimensional array in PHP after posting it from JS using Ajax: $.ajax({ type: 'post', url: 'external_submit.php', dataType: "json", data: { edit_rfid_changes_submit ...

Troubleshooting a timing loop problem with jQuery Ajax and setInterval when using flipCounter's onAnimationStopped feature

In the code below, I am retrieving some data to use for a counter. The problem is that after the initial page load and one interval, things start to go haywire. The calls are made without any delay and the counter cannot react before the next call is made. ...

Unable to retrieve response token from form in a Next.js/React application utilizing Cloudflare Turnstile

As a beginner in Next.js/React, I'm currently working on creating a basic contact form with Cloudflare Turnstile integration. Prior to implementing Turnstile, the form functioned perfectly, submitting data to the API and sending emails without any iss ...

What is the process for obtaining a component's ref using JavaScript event propagation?

Here is a code snippet I am working with: const dailyRef = createRef(); const monthlyRef = createRef(); const annuallyRef = createRef(); const handleBillingCycleClick = ({target}) => { const value = target.dataSet.value // How can I access the clic ...

Multiple angularjs validations applied to a single textbox

Hello, I am currently working on an angularjs application where I have a textbox with a custom directive attached to it. This directive only accepts numbers within a certain range, for example between 100 to 200. The validation for this is working perfectl ...

Tips for effectively loading data of a specific user or event into a bootstrap modal in Laravel using AJAX

I'm having some trouble loading Event data into my bootstrap modal in Laravel. This is all new to me as I'm just getting started with AJAX. Can someone please take a look at what I've done so far? Modal Template <div class="modal fa ...

Is it possible to implement an automatic clicking function on a bootstrap navigation bar similar to a carousel?

I am working on a website with a bootstrap navigation bar similar to the one shown in this image : bootstrap nav <ul class="nav nav-tabs" id="tab_home" role="tablist"> <li class="nav-item" role="pres ...

Is there anyone out there who has successfully imported a model from the three.js editor?

As a designer and 3D artist who occasionally delves into coding, I have a question regarding loading a model from the three.js editor into an actual web page. Despite my limited programming knowledge, I've tried various methods to achieve this, includ ...

Ajax sends the URL location to Python

I'm attempting to piece together some code. There are two distinct functions that I am trying to merge into a single entity. Code snippet: <!DOCTYPE html> <head> <meta http-equiv="content-type" content="text/html;charset=UTF-8"> &l ...

Why is Ajax/FormData rounding my decimal values?

When sending data from a form to my PHP script, I am utilizing the new FormData() method to retrieve the values. However, there are additional values that I append later on which are not part of the form: var fd = new FormData(document.getElementById(&apo ...