How do you include OpenCV into a javascript project? - javascript

I recently installed OpenCV through npm using the following guide:
https://www.npmjs.com/package/opencv
My question is pretty simple. How do I actually use the OpenCV library in my project?
On that site, there is a face detection example that looks like this:
cv.readImage("./examples/files/mona.png", function(err, im){
im.detectObject(cv.FACE_CASCADE, {}, function(err, faces){
for (var i=0;i<faces.length; i++){
var x = faces[i]
im.ellipse(x.x + x.width/2, x.y + x.height/2, x.width/2, x.height/2);
}
im.save('./out.jpg');
});
})
The cv. variable is where I'm stuck at. Typically whenever I install a new package using npm, I would add it to my app.js file like so:
angular
.module('App', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',
'ui.sortable',
'firebase',
'angular-toArrayFilter'
])
Similarly in any of my controllers, I would add the name of the module as a parameter to the controller:
angular.module('App')
.controller('LoginCtrl', function ($scope, UserAuth, $window, $firebaseArray, fireBaseRef)
I can't seem to find the dependency name for OpenCV to even allow me to use it in the first place. None of the guides that I've looked at to date ever mention how to include it into your project.
Thanks for your time!

You can't use OpenCV in browser-side javascript projects. OpenCV is a native library and node-opencv allows you to use it on the server, but you cannot use it directly in the browser.
From the installation instructions for node-opencv:
You'll need OpenCV 2.3.1 or newer installed before installing
node-opencv. Note that OpenCV 3.x is not yet fully supported.

Follow the installation instructions for whatever your operating system is (i.e. Mac OSX, Windows, Linux/Debian). Instructions for the most popular systems can be found here: https://www.npmjs.com/package/opencv.
Then, before using the 'cv' variable you must require the 'opencv' module.
var cv = require('opencv');
If you receive an error, it will usually be a dependency issue. Verify that you have correctly installed all the dependencies for node-opencv. On my first install I needed
npm install buffers
and
npm install node-pre-gyp
Depending on where you installed your opencv bundle, you may need to explicitly include the file path to the opencv.js file like so
var cv = require('/path_to_node-opencv-master/lib/opencv');
I recommend reading the intro to OpenCV articles and the documentation on the OpenCV website at http://opencv.org/ to learn more.

Related

"ERROR in xx.js from UglifyJs Invalid assignment" when importing a module into another module

I cannot post exact code due to NDAs, so I will do my best.
Javascript is not my string suit, but I took it up for my team.
Background:
I built a module which basically will perform a very simple task and can be imported as a dependency in other projects and then added into the project by adding the tag.
I wanted to keep this as lightweight as possible and let the app which was adding it in do the heavy lifting and have the imports to run and compile Angular code.
Code for SimpleApp:
Everything seems to work fine except for places marked with /* Potential Issue */
Within the simple module, I have a few file:
simpleApp.js -- the main js file which does the work necessary
simpleApp.html -- the html of simpleApp.js
innerProvider.js -- a module.service which does some work when called from the simpleApp.js -- this import seems to be the issue causer.
All within the companySimpleApp package:
simpleApp.js:
import angular from "angular"
/* I believe this to be the issue */
import innerProviderModule from "./pathToFile/innerProvider /* Potential Issue */
/* Potential Issue */
angular.module('simpleApp', [innerProviderModule]).component('simpleComponent, {
controller: ['$scope, 'innerProvider', ..., function($scope, innerProvider, ...) {
/* does work */
}],
template: require("./simpleApp.html"),
bindings: {
bind1: '#',
bind2: '#'
}
simpleApp.html:
<div>
do stuff
call stuff
</div>
innerProvider.js:
import angular from "angular"
const innerProviderModule = angular.module('innerProvider', [])
.service('innerProvider', function (%http, ...) {
this.doWork = function (param1) {
retStmt = doSomething(param1)
return retStmt
}
});
export default innerProviderModule.name;
Everything here builds correctly and will do as is told. I am able to build this package as well as the one which uses it and have a working webpage with the simpleApp's services. However, this is when I host everything myself.
Code for Larger Service using SimpleApp:
In another project I have this listed as a dependency "simpleApp = 1.0" this may be different than expected due to my company's internal workings, but this works.
It appears in the node_module directory
I then have a module for the webpage which loads in simpleApp and has all of the other packages like angular, babel, uglify, webpack, etc:
/* Potential Issue */
import "companySimpleApp/simpleApp.js"
export default angular
.module("app", [otherDependencies, simpleApp])
.config(function ($stateProvider, $stuff){
someMappingsForUrls
});
...
<script src="../node_modules/companySimpleApp/simpleApp.js"></script>
...
and another html and js file which use the simpleApp
<div>
<simpleApp bind1='{{value}}'></simpleApp>
</div>
Error:
Now, everything will run fine on my localhost and I can fully use the larger service using SimpleApp site with the simpleApp. However, when I build this (npm run webpack) on the service using simpleApp, I get the following error even though everything seems to run fine on my localhost:
ERROR in bundle.js from UglifyJs
Invalid assignment [bundle.js:146461,67]
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! # webpack: `webpack -p`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the # webpack script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
........
The code seems to build when I remove the import innerProviderModule from "./pathToFile/innerProvider from simpleApp.js but I then get an error saying that innerProvider is an unresolved reference or something along the line.
What I am asking is for some help on why I may be seeing this error when I import the innerProviderModule I built. Do I need to add webpack and all that to my simpleApp project even though it all seems to run fine physically on my localhost?
Any help or ideas is very much so appreciated. Thanks!
Bumping this as I posted it late at night.
Edit: It seems to not like "=>" in the innerProvider which I have
I built the package which uses the simpleApp with 'webpack -p' which was not done on simpleApp. So, what it looked like that happened was that the simpleApp was not minified or something and didnt like a few lines in the provider code (ie: "=>", "let", etc...)
So instead of having the simpleApp have more dependencies, I simply wrote code which would pass webpack -p.
You should also be able to just remove the "-p" flag
Hope this helps someone.

Attempting to load a JavaScript sdk into an Angular2 application. Can't find all dependencies

I'm attempting to make use of this library: https://github.com/MagicTheGathering/mtg-sdk-javascript in an Angular2 application.
Unfortunately, I've been going in circles trying to load it into my application.
Firstly, on the TypeScript side if I import it using:
import { } from 'mtgsdk';
there are no types to load into the {}.
If I attempt to load it using something similar to:
import * as mtg from 'mtgsdk'
I'm unable to because it says that it's unable to find a module named mtgsdk.
I've installed the module using
npm install --save mtgsdk
Also, npm installs work fine for other modules.
The application compiles fine if I load it in using require via something similar to this:
var mtg = require('mtgsdk');
Taking that approach, I'm able to compile and launch but in the browser I get a number of errors about modules that it can't find. I figure they are prerequisites for the sdk that didn't get loaded so I start bringing them in via package.json.
For every one that I bring in, I then have to go to systemjs.config.js and add an entry pointing to the module's entry point and often have to specify a default extension using blocks like this:
pointer
'mtgsdk': 'npm:mtgsdk/lib/index.js',
'request-promise': 'npm:request-promise/lib/rp.js',
'ramda': 'npm:ramda/dist/ramda.js',
'emitter20': 'npm:emitter20/index.js',
'bluebird': 'npm:bluebird/js/browser/bluebird.js',
'request': 'npm:request/index.js'
default extension
'request-promise':
{
defaultExtension: 'js'
}
I'm not sure if that's the right approach though because the more dependencies I add, the more that I end up requiring. At one point I had literally gotten up to 50 extra dependencies added because every time I launched, the browser console would find more that were needed.
Is there any easier way to load all of these in?
Also, some of them (such as tough-cookie and request-promise-core) were very problematic to load and I couldn't get the browser console to stop complaining about them. Finally, some of them seemed very basic such as url, http, https. Those seem like they should already be present.
Using systemjs was utilized in the previous versions of Angular 2, However Angular 2 has evolved to Angular 4, with super new features like Angular CLI.
I recommend your use Angular CLI, with #angular/cli.
Importing Node modules
Since mtgsdk is a node-module, you can easily import it using
import * as mtg from 'mtgsdk'
However for your program to compile, you must install a type definition for it. or declare one for it in /typings.json or your app might not build.
Importing Client Scripts
For client scripts like firebase.js you won't need to add client scripts as entries in systemjs.config.js again.
Using #angular/cli, you would easily add them in the scripts[] array in your angular-cli.json for automatic compilation.
Then access them like this
declare const firebase: any;
Here is a quickstart tutorial to set up Angular with #angular/cli.

How to include 3rd party library that uses older import approach to Angular4.x?

What is the proper workflow to include the library to angular 4.0 and use it inside a component?
My steps:
yarn add mathjs
Then there should be a way to injects js libraries in one of the build lifecycles so the angular4 component can use it. JHipster utilizes Webpack and Yarn.
Then I tried to add to Component (docs):
import { mathjs } from "./mathjs";
and
var math = require('mathjs');
Those were not working. What am I missing?
UPDATE:
It seems like mathjs uses older approach suggesting var math = require('mathjs'). Maybe it is similar to JQuery question in some way...
UPDATE2
This is a great question and I'm glad you ask because I wish I had what I'm about to write the first time I encountered this little problem. This is a typescript/javascript and webpack issue before it is an angular issue. I definitely am planning a writeup on my blog soon as possible.
Your Scenario:
You run
npm install mathjs
Now you try to use math.js from a component:
Find math.js dist js file (node_modules/mathjs/dist/math.js) and reference like this
import {mathjs} from "../../node_modules/mathjs/dist/math";
But you get error message saying "set --allowJS". You do that like this:
Set --allowJS in config (tsconfig.json)
{ "compilerOptions": {
"allowJs": true, ...
Now you get:
ERROR in ../node_modules/mathjs/dist/math.js (12209,13): Unreachable
code detected.
Looking in the math.js source, you see that it is an old school module but there is no root wrapper function (one function to bring them all and in the darkness bind them..) (more on that later).
Solution: install a typings file for the target lib (#types/mathjs)
First, check to see if you can get #typings files for your module here
https://microsoft.github.io/TypeSearch/
Grab mathjs typings file from npm (https://www.npmjs.com/package/#types/mathjs) and Run npm install to add the typings .d.ts files to the target lib's node_modules directory
npm install --save #types/mathjs
Add your type ref correctly
import * as mjs from "mathjs"
Use it like this:
console.log("e was: " + mjs.e);
I have the complete solution for the math.js lib on my github here
https://github.com/res63661/importOldJSDemoWithTypings/
More:
For examples look no further than your own angular project. CLI creates node_modules folder each time you run npm install after creating a new project with ng new . Dig down into here and note the d.ts files for many of the .js files.
When messing with typings or defining your own (.d.ts files) be sure to restart your server between builds as the typings don't seem to update currently on the fly
Further reading:
http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html
https://angular.io/guide/typescript-configuration#typescript-typings
https://microsoft.github.io/TypeSearch/
Lastly:
If you are in a pinch and this is not working for you, I did have success creating a custom wrapper for a different (much smaller) module by wrapping it in a master export type
export var moduleNamer = (function(){
//module implementation
}());
then dumping the .js file local to my component and then referencing it as follows:
//reference like this from your component:
import {moduleNamer} from "./source"; //from source.js
--rich
I did this way and it worked for angular9.
First install npm package mathjs.
npm install mathjs
Then import in your component or directive.
import { round } from 'mathjs'
You may test with this.
console.log(round(math.pi, 3) )
Try to include the script into index.html:
<script src="./assets/math.js" type="text/javascript"></script>
Then add this into your component file:
declare const math;
You can then use math in your component:
ngOnInit(): void {
console.log(math.sqrt(-4););
}

Ionic native using ionic/angular 1

I'm currently working on a project in ionic/angular 1. I'm using ionic native to wrap the cordova plugins.
I installed ionic native with bower, and added dependency to 'ionic.native' in my app's angular module. Now I can inject stuff like $cordovaFile into my controllers and use them. This works great.
My problem is using the MediaPlugin. I inject $cordovaMediaPlugin in my controller. Now the documentation ( https://ionicframework.com/docs/v2/native/mediaplugin/ ) says do this:
new MediaPlugin('path/to/file.mp3', onStatusUpdate);
Obviously i cant do this in angular1.
I tried stuff like this:
var media = this.$cordovaMediaPlugin('PATH');
var media = new this.$cordovaMediaPlugin('patch');
nothing seems to work, getting undefined all the time.
How would I make this calls in angular/ionic 1? I really think the 'new' keyword is the issue here...
Try to install ngCordova Media plugin.
Install ngCordova, and inject in your app module 'ngCordova'.
See de following steps
Install plugin
If you want create a service to provide a media resources see (Not required)

How do I set up AngularJS intellisense on VS Code

I've been working on setting up Visual Studio Code specifically to work with a Angular 1.5 codebase that we have at work. Here's what I've done up to this point:
Installed TSD
Ran tsd query -r -o -a install angular -s
Add a reference at the top of my file to tsd.d.ts like so:
/// <reference path="../typings/tsd.d.ts" />
(function() {
'use strict';
angular.module('moduleName').controller('CtrlName',
['$scope', '$window',function ($scope, $window){
}
})();
At this point, it looks like I have partial success; when I hover over the angular keyword I see type-specific information (i.e. namespace angular, var angular: ng.IAngularStatic) but none of the type information is coming through in the angular specific dependencies, i.e. when I hover over $window, it tells me it is of any type.
My questions:
What more do I have to do to get intellisense to work properly?
Is there a way around having to add the reference at the top of every single JS file I have in the codebase to be able to get intellisense working?
After some digging around, I found that this used to be supported in VS Code once upon a time but support was lost in the latest versions. Source: https://github.com/Microsoft/vscode/issues/8163

Categories

Resources