Utilizing trackingjs as an external library in Ionic2

I have been attempting to incorporate the trackingjs library (https://www.npmjs.com/package/tracking) into my ionic2 project.

Following the guidelines in the documentation (https://ionicframework.com/docs/v2/resources/third-party-libs/), I was able to successfully import and utilize the lodash library.

However, when it comes to tracking js, all I see is an empty object (tracking === {})

import tracking from 'tracking/build/tracking';

I have installed the tracking module via npm and also added the necessary types (https://www.npmjs.com/package/@types/tracking). While I can verify that the code from the module is present in my main.js file when using ionic serve, I am unable to make it function as expected.

Have I overlooked something obvious or is there a specific step required for this library? Any assistance would be greatly appreciated.

Answer №1

Give this a shot.

import * as monitoring from 'monitoring/build/monitoring';

Answer №2

Through various experimentation, I have successfully integrated and utilized tracker.js in my Ionic 2 application with typescript 2.2.1.

The challenge at hand was to identify faces within a photo selected by the user before it gets uploaded.

Below are the steps I took to solve this issue:

1st Step: Install tracking.js using npm

npm install tracking

2nd Step: Import the tracking.js file into your Ionic page.

Note: Locate the tracking.js file within the node_modules/tracking folder. Then, use the file path but exclude the ".js" extension from the end.

//node_modules/tracking/build/tracking.js    
import 'tracking/build/tracking';

3rd Step: Import the face.js Classifier file after importing 'tracking/build/tracking' and declare necessary variables.

//node_modules/tracking/build/tracking.js    
import 'tracking/build/tracking';
//node_modules/tracking/build/data/face.js
import 'tracking/build/data/face';

//Ensure these variables are declared for visibility in your code
declare var window: any;
declare var tracking: any;

4th Step: Utilize the tracker.js API in your code (further optimization is possible)

//Preferably run this after the view has fully loaded
ionViewDidLoad(){

   //Initialize the tracking object with parameters to track faces only
   var tracker = new tracking.ObjectTracker('face');

   //Create an image object
   var img = new Image();

   /** It is crucial to set the height and width 
    as the image may be too small or large for 
    your step size, affecting face detection. 
    I recommend testing this in an HTML file first
    to determine the suitable size for your scenario **/
   img.width = 200;
   img.height = 200;

   //Set cross-origin attribute even when accessing a local file
   img.crossOrigin = '*';

   /** 
     Set the onload callback to ensure the image
     is loaded before further processing
   **/
   img.onload = function() {

      console.log('------------IMAGE LOADED------------');

      /**
       Determine the optimal value based on image size.
       Too small might cause delays or app crashes,
       while too big could lead to missing smaller faces.
      **/ 
      tracker.setStepSize(1.7); //Default size according to docs is 1.7

     //Pass the loaded image object and tracker instance to tracker.track() 
     var task = tracking.track(img, tracker);

     //Detection of faces might take some time
     tracker.on('track', function(event) {


        //An empty event.data implies no faces were found
        console.log( JSON.stringify(event.data) );

        //Iterate through each detected face
        event.data.forEach(function(rect) {
           //Coordinates to render a rectangle on a canvas
           console.log(JSON.stringify(rect));

           console.log('-------------FOUND SOME FACES----------------------');

           //Process the data as required
        });


        //Stop tracking once at least one face is identified
        task.stop();
      });

    }

    //Define the image path to track
    img.src =  'assets/img/facetest.jpg';
}

You can also detect eyes and mouth by importing eye.js and mouth.js Classifier files

//node_modules/tracking/build/data/eye.js
import 'tracking/build/data/eye';
//node_modules/tracking/build/data/mouth.js
import 'tracking/build/data/mouth';

If you wish to track all faces, eyes, and mouths, utilize an array of classifier names as parameters after importing all Classifier files

 var tracker = new tracking.ObjectTracker(['face','eye','mouth']);

Answer №3

import 'tracking/build/tracking.js';
import 'tracking/build/data/face.js';

const global = <any>window;
this.tracker = new global.tracking.ObjectTracker('face');

Working well, implemented in a different Angular 5 project instead of Ionic.

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

The output from Angular Validator.pattern() may differ from that generated by online regex engines

Currently, I am facing an issue with my form group and a regular expression used to validate names. The criteria for the name input field are: It must be required. It should be alphanumeric. It must start with alphabets. It cannot contain any special char ...

Using Angular 4 to delete selected rows based on user input in typescript

I am facing a challenge with a table that contains rows and checkboxes. There is one main checkbox in the header along with multiple checkboxes for each row. I am now searching for a function that can delete rows from the table when a delete button is clic ...

Sending environmental variable values to an Angular application from a Docker file

I am currently facing a challenge with my Angular application where I am attempting to define the environment variable from an external source, specifically from a docker compose file. For reference, I found an article that addresses this issue: docker-c ...

Ways to verify if the current date exists within a TypeScript date array

I am trying to find a way in typescript to check if the current date is included in a given array of dates. However, even after using the code below, it still returns false even when the current date should be present within the array. Can anyone please pr ...

Is there a way to retrieve a data type from a class in TypeScript?

Within my code, there exists a class: class Person { name: string; age: number; gender: string; constructor(params: any){ this.name = params.name; this.age = params.age; this.gender = params.gender; } } My question is how ca ...

What is the best method for retrieving an item from localstorage?

Seeking advice on how to retrieve an item from local storage in next.js without causing a page rerender. Here is the code snippet I am currently using: import { ThemeProvider } from "@material-ui/core"; import { FC, useEffect, useState } from "react"; i ...

Commit to choosing an option from a dropdown menu using TypeScript

I just started learning about typescript and I have been trying to create a promise that will select options from a drop down based on text input. However, my current approach doesn't seem to be working as expected: case 'SelectFromList': ...

Is it possible to import a module that was exported in Node.js using the SystemJS import method?

When working on a Node project, we typically import modules using the require keyword. Is it possible to import the same module in an Angular 2 project using import {} from '', even if the d.ts file is not available? For instance, can I incorpora ...

`The Importance of Validating Enum Arrays in Typescript Using Class-Validator`

Is there a way to validate an array of enums in a DTO without getting misleading error messages? Here is an example of my DTO: import { IsArray, IsEmail, IsEnum, IsIn, IsNotEmpty, IsString } from "class-validator"; import { UserAction, UserModul ...

Angular 7 is taking an unusually long time to load the after login component

Upon logging into my Angular 7 application, the after-login component experiences slow loading for the first time. However, if a user logs out and then logs back in without closing the browser, the speed improves. The routing structure is as follows: In ...

TypeError thrown by Basic TypeScript Class

I'm encountering an issue where TypeScript is throwing a TypeError when trying to use the class Literal from file Classes.tsx in file App.tsx, even though they are in the same file. Strangely, everything works fine on typescriptlang.org/play. // Class ...

Recently updated from Angular 9 to 14 and noticed a peculiar issue in the deployed app - all API calls seem to only reference the root or hosted URL in the request URL

After upgrading the application from angular 9 to angular 14, I encountered a network call issue. The application was successfully deployed via azure devops, but all network calls were directed to the host URL instead of the expected API endpoints. For exa ...

What is the best way to create a custom hook that updates in response to changes in state?

My situation involves a custom hook that handles a specific state variable. After making changes to the state, it doesn't update right away. To solve this issue, I need to subscribe to it using useEffect. The challenge is that I can't directly ...

Will a JavaScript source map file continue to function properly even after the source code file has been minified?

My experience I specialize in utilizing TypeScript and Visual Studio to transform highly organized code into functional JavaScript. My skills involve configuring the project and Visual Studio to perform various tasks: Merging multiple compiled JavaScrip ...

Setting up TypeScript to function with Webpack's resolve.modules

Imagine having a webpack configuration that looks like this: resolve: { extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'], modules: ['my_modules', 'node_modules'], }, You have a ...

Unable to retrieve the updated value from the service variable

I'm attempting to implement a filter that allows me to search for items based on a service variable that is updated with user input. However, I am only able to retrieve the initial value from the service in my component. Service HTML (whatever is typ ...

Backend external login without password feature in .NET Core ABP 6.0 for users

Currently, I am working on a project that involves utilizing ABP 6.0 native backend (.NET Core 6 with IdentityServer) and a non-native angular frontend project with ABP installed for the static proxy tool. I am encountering difficulties in implementing Goo ...

Error message for invalid form control not displayed when value is assigned to form control in Angular

I am currently working with this editor: <div id="editor"></div> which sets its value to a form control. this.FrmGroup.get("name").setValue(this.quill.root.innerHTML)` <div *ngIf="FrmGroup.get('name').inv ...

Change the variable value within the service simultaneously from various components

There is a service called DisplaysService that contains a variable called moneys. Whenever I make a purchase using the buy button on the buy component, I update the value of this variable in the service from the component. However, the updated value does n ...

I am experiencing an issue with the ng template binding when trying to use a button

The tolTemplate is not properly binding with the [tooltip] code snippet. <ng-template #tolTemplate> Just another: </ng-template> <button type="button" class="btn btn-success" [tooltip]="tolTemplate"> Show me tooltip with html </b ...