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

Working with Typescript to map and sort the key values of a new datasource object

Managing a large datasource filled with objects can be challenging. My goal is to rearrange the order of objects in the array based on new values for each key. Whenever a new value for a key is found, I want the corresponding object to move to the top of t ...

Angular Project: Exploring Classes and Interfaces with and without the Export Keyword

Currently, I am delving into the world of Angular. I have taken up a video course and also referred to a PDF book, but I find myself perplexed when it comes to understanding the usage of the "export" keyword... The PDF course focuses on Angular 5 and util ...

The Angular2 Router encounters an issue with the URL when it contains the "&

Ever since updating to the latest version of angular v4.3.2, I've encountered an issue where all my URLs break at the & value. For instance, I have a route /:value from which I need to retrieve the value: http://localhost:4200/one&two Inst ...

Dynamic Angular components and their content projection

Can content projection be utilized in Angular 2 components that are dynamically loaded and created at runtime, rather than being known at compilation time? ...

Taking advantage of Input decorator to access several properties in Angular 2

I am currently working on a component that is designed to receive two inputs through its selector. However, I would like to make it flexible enough to accept any number of inputs from various components. Initially, I tried using a single @Input() decorator ...

Issue with Material UI v5: "spacing" property not found on custom theme object

My current setup involves using version 5 of material ui, where I have customized a theme and applied it to all my components. However, when trying to add padding to a paper element in one of my components based on the theme, I encountered the following e ...

Discover the specifics of an element within angular version 6

My goal is to have the details of a course module displayed when it is clicked. However, I am encountering an error with my current code: Cannot read property 'id' of undefined. coursemoduleapi.service.ts getCourseModule(id:number) { return thi ...

Styling components with SASS in NextJS

I've encountered an issue while working on a basic NextJS app, specifically with component-level styling using SASS/SCSS. Initially, everything appears fine when the user lands on the page for the first time. However, as they navigate to different pag ...

What is the correct way to utilize Global Variables in programming?

Having trouble incrementing the current page in my pagination script to call the next page via AJAX... In my TypeScript file, I declare a global variable like this; declare var getCurrentPage: number; Later in the same file, I set the value for getCurren ...

React TypeScript throws an error when a Socket.IO object is passed to a child component and appears as undefined

Currently, I'm developing a simple chat application as part of my university course. The code below represents a work-in-progress page for this project. While I am able to get the socket from the server and use it in the main component without any is ...

Guide to setting a default value for a select option in Angular 2+

I am having trouble setting a default option in my select box using the html selected property. I want the selected option to be assigned to StartingYear, but currently it's not working as expected. <select [(ngModel)]="StartingYear"> < ...

Guide on creating a 4-point perspective transform with HTML5 canvas and three.js

First off, here's a visual representation of my objective: https://i.stack.imgur.com/5Uo1h.png (Credit for the photo: ) The concise question How can I use HTML5 video & canvas to execute a 4-point perspective transform in order to display only ...

Example TypeScript code: Use the following function in Angular 5 to calculate the total by summing up the subtotals. This function multiplies the price by the quantity

I have a table shown in the image. I am looking to create a function that calculates price* quantity = subtotal for each row, and then sum up all the subtotals to get the total amount with Total=Sum(Subtotal). https://i.stack.imgur.com/4JjfL.png This is ...

Avoid stopping Bootstrap Vue's events

Need help with a b-form-select control in Bootstrap Vue. Trying to execute a function when the value changes, but want the option to cancel the event and keep the original value. Complicating matters, the select is in a child component while the function ...

Encountering an issue with a specific property not being defined in a spec

I am currently developing an Angular8 project and have set up jest and jasmine for testing purposes. .ts // all necessary imports are included @Component({ selector: 'app-xyz', templateUrl: './xyz.component.html', styleUrls: [& ...

Linking a variable in typescript to a translation service

I am attempting to bind a TypeScript variable to the translate service in a similar way as binding in HTML markup, which is functioning correctly. Here's what I have attempted so far: ngOnInit() { this.customTranslateService.get("mainLayout.user ...

What is the best approach for promoting reusability in Angular: creating a new CSS class or a new component?

I have a div with a set of CSS properties that are essential to my application. These properties will be reused across multiple pages and components. <div style="display: flex; flex-direction: column; height: 100%"> //inner html will vary based on c ...

Troubleshooting the issue of Angular2's http withCredentials not functioning as expected

Utilizing Angular2's HTTP module, I am sending HTTP requests. Once a user logs in, the backend server creates a cookie session which is then used by the frontend to send subsequent requests. The Angular code snippet is outlined below: get(url: string ...

Ways to store a component in cache once its route is triggered

There are 3 components in my project: 1 parent and 2 child components with router outlet. The child component becomes active whenever its route is called, sharing data using a service. Both of these child components have complex views. When switching bet ...

Effectively enhance constructor by incorporating decorators

Is it possible to properly extend a class constructor with decorators while maintaining the original class name and static attributes and methods? Upon reading the handbook, there is a note that cautions about this scenario: https://www.typescriptlang.or ...