Learn Node.js basics. Although this tutorial assumes the user knows JavaScript, experience with Node.js is not required.
Minimal example
Create a file example1.js with the following content:
// Define a global variable 'Module' with a method 'onRuntimeInitialized':Module = {
onRuntimeInitialized() {
// this is our application:console.log(cv.getBuildInformation())
}
}
// Load 'opencv.js' assigning the value to the global variable 'cv'cv = require('./opencv.js')
Execute it
Save the file as example1.js.
Make sure the file opencv.js is in the same folder.
The following command should print OpenCV build information:
nodeexample1.js
What just happened?
In the first statement:, by defining a global variable named 'Module', emscripten will call Module.onRuntimeInitialized() when the library is ready to use. Our program is in that method and uses the global variable cv just like in the browser.
The statement "cv = require('./opencv.js')" requires the file opencv.js and assign the return value to the global variable cv. require() which is a Node.js API, is used to load modules and files. In this case we load the file opencv.js form the current folder, and, as said previously emscripten will call Module.onRuntimeInitialized() when its ready.
OpenCV.js doesn't support image formats so we can't load png or jpeg images directly. In the browser it uses the HTML DOM (like HTMLCanvasElement and HTMLImageElement to decode and decode images). In node.js we will need to use a library for this.
In this example we use jimp, which supports common image formats and is pretty easy to use.
Example setup
Execute the following commands to create a new node.js package and install jimp dependency:
mkdirproject1cdproject1npminit -ynpminstalljimp
The example
constJimp = require('jimp');
asyncfunctiononRuntimeInitialized(){
// load local image file with jimp. It supports jpg, png, bmp, tiff and gif:varjimpSrc = awaitJimp.read('./lena.jpg');
// `jimpImage.bitmap` property has the decoded ImageData that we can use to create a cv:Matvarsrc = cv.matFromImageData(jimpSrc.bitmap);
// following lines is copy&paste of opencv.js dilate tutorial:letdst = newcv.Mat();
letM = cv.Mat.ones(5, 5, cv.CV_8U);
letanchor = newcv.Point(-1, -1);
cv.dilate(src, dst, M, anchor, 1, cv.BORDER_CONSTANT, cv.morphologyDefaultBorderValue());
// Now that we are finish, we want to write `dst` to file `output.png`. For this we create a `Jimp`// image which accepts the image data as a [`Buffer`](https://nodejs.org/docs/latest-v10.x/api/buffer.html).// `write('output.png')` will write it to disk and Jimp infers the output format from given file name:newJimp({
width: dst.cols,
height: dst.rows,
data: Buffer.from(dst.data)
})
.write('output.png');
src.delete();
dst.delete();
}
// Finally, load the open.js as before. The function `onRuntimeInitialized` contains our program.Module = {
onRuntimeInitialized
};
cv = require('./opencv.js');
Execute it
Save the file as exampleNodeJimp.js.
Make sure a sample image lena.jpg exists in the current directory.
The following command should generate the file output.png:
nodeexampleNodeJimp.js
Emulating HTML DOM and canvas
As you might already seen, the rest of the examples use functions like cv.imread(), cv.imshow() to read and write images. Unfortunately as mentioned they won't work on Node.js since there is no HTML DOM.
In this section, you will learn how to use jsdom and node-canvas to emulate the HTML DOM on Node.js so those functions work.
Example setup
As before, we create a Node.js project and install the dependencies we need:
const { Canvas, createCanvas, Image, ImageData, loadImage } = require('canvas');
const { JSDOM } = require('jsdom');
const { writeFileSync, existsSync, mkdirSync } = require("fs");
// This is our program. This time we use JavaScript async / await and promises to handle asynchronicity.
(async () => {
// before loading opencv.js we emulate a minimal HTML DOM. See the function declaration below.installDOM();
awaitloadOpenCV();
// using node-canvas, we an image file to an object compatible with HTML DOM Image and therefore with cv.imread()constimage = awaitloadImage('./lena.jpg');
constsrc = cv.imread(image);
constdst = newcv.Mat();
constM = cv.Mat.ones(5, 5, cv.CV_8U);
constanchor = newcv.Point(-1, -1);
cv.dilate(src, dst, M, anchor, 1, cv.BORDER_CONSTANT, cv.morphologyDefaultBorderValue());
// we create an object compatible HTMLCanvasElementconstcanvas = createCanvas(300, 300);
cv.imshow(canvas, dst);
writeFileSync('output.jpg', canvas.toBuffer('image/jpeg'));
src.delete();
dst.delete();
})();
// Load opencv.js just like before but using Promise instead of callbacks:functionloadOpenCV() {
returnnewPromise(resolve => {
global.Module = {
onRuntimeInitialized: resolve
};
global.cv = require('./opencv.js');
});
}
// Using jsdom and node-canvas we define some global variables to emulate HTML DOM.// Although a complete emulation can be archived, here we only define those globals used// by cv.imread() and cv.imshow().functioninstallDOM() {
constdom = newJSDOM();
global.document = dom.window.document;
// The rest enables DOM image and canvas and is provided by node-canvasglobal.Image = Image;
global.HTMLCanvasElement = Canvas;
global.ImageData = ImageData;
global.HTMLImageElement = Image;
}
Execute it
Save the file as exampleNodeCanvas.js.
Make sure a sample image lena.jpg exists in the current directory.
The following command should generate the file output.jpg:
nodeexampleNodeCanvas.js
Dealing with files
In this tutorial you will learn how to configure emscripten so it uses the local filesystem for file operations instead of using memory. Also it tries to describe how files are supported by emscripten applications
Before the example, is worth consider first how files are handled in emscripten applications such as OpenCV.js. Remember that OpenCV library is written in C++ and the file opencv.js is just that C++ code being translated to JavaScript or WebAssembly by emscripten C++ compiler.
These C++ sources use standard APIs to access the filesystem and the implementation often ends up in system calls that read a file in the hard drive. Since JavaScript applications in the browser don't have access to the local filesystem, emscripten emulates a standard filesystem so compiled C++ code works out of the box.
In the browser, this filesystem is emulated in memory while in Node.js there's also the possibility of using the local filesystem directly. This is often preferable since there's no need of copy file's content in memory. This section explains how to do just that, this is, configuring emscripten so files are accessed directly from our local filesystem and relative paths match files relative to the current local directory as expected.
const { Canvas, createCanvas, Image, ImageData, loadImage } = require('canvas');
const { JSDOM } = require('jsdom');
const { writeFileSync, existsSync, mkdirSync } = require('fs');
(async () => {
awaitloadOpenCV();
constimage = awaitloadImage('lena.jpg');
constsrc = cv.imread(image);
letgray = newcv.Mat();
cv.cvtColor(src, gray, cv.COLOR_RGBA2GRAY, 0);
letfaces = newcv.RectVector();
leteyes = newcv.RectVector();
letfaceCascade = newcv.CascadeClassifier();
leteyeCascade = newcv.CascadeClassifier();
// Load pre-trained classifier files. Notice how we reference local files using relative paths just// like we normally would dofaceCascade.load('./haarcascade_frontalface_default.xml');
eyeCascade.load('./haarcascade_eye.xml');
letmSize = newcv.Size(0, 0);
faceCascade.detectMultiScale(gray, faces, 1.1, 3, 0, mSize, mSize);
for (leti = 0; i < faces.size(); ++i) {
letroiGray = gray.roi(faces.get(i));
letroiSrc = src.roi(faces.get(i));
letpoint1 = newcv.Point(faces.get(i).x, faces.get(i).y);
letpoint2 = newcv.Point(faces.get(i).x + faces.get(i).width, faces.get(i).y + faces.get(i).height);
cv.rectangle(src, point1, point2, [255, 0, 0, 255]);
eyeCascade.detectMultiScale(roiGray, eyes);
for (letj = 0; j < eyes.size(); ++j) {
letpoint1 = newcv.Point(eyes.get(j).x, eyes.get(j).y);
letpoint2 = newcv.Point(eyes.get(j).x + eyes.get(j).width, eyes.get(j).y + eyes.get(j).height);
cv.rectangle(roiSrc, point1, point2, [0, 0, 255, 255]);
}
roiGray.delete();
roiSrc.delete();
}
constcanvas = createCanvas(image.width, image.height);
cv.imshow(canvas, src);
writeFileSync('output3.jpg', canvas.toBuffer('image/jpeg'));
src.delete(); gray.delete(); faceCascade.delete(); eyeCascade.delete(); faces.delete(); eyes.delete()
})();
/**
* Loads opencv.js.
*
* Installs HTML Canvas emulation to support `cv.imread()` and `cv.imshow`
*
* Mounts given local folder `localRootDir` in emscripten filesystem folder `rootDir`. By default it will mount the local current directory in emscripten `/work` directory. This means that `/work/foo.txt` will be resolved to the local file `./foo.txt`
* @param {string} rootDir The directory in emscripten filesystem in which the local filesystem will be mount.
* @param {string} localRootDir The local directory to mount in emscripten filesystem.
* @returns {Promise} resolved when the library is ready to use.
*/functionloadOpenCV(rootDir = '/work', localRootDir = process.cwd()) {
if(global.Module && global.Module.onRuntimeInitialized && global.cv && global.cv.imread) {
returnPromise.resolve()
}
returnnewPromise(resolve => {
installDOM()
global.Module = {
onRuntimeInitialized() {
// We change emscripten current work directory to 'rootDir' so relative paths are resolved// relative to the current local folder, as expectedcv.FS.chdir(rootDir)
resolve()
},
preRun() {
// preRun() is another callback like onRuntimeInitialized() but is called just before the// library code runs. Here we mount a local folder in emscripten filesystem and we want to// do this before the library is executed so the filesystem is accessible from the startconstFS = global.Module.FS// create rootDir if it doesn't existsif(!FS.analyzePath(rootDir).exists) {
FS.mkdir(rootDir);
}
// create localRootFolder if it doesn't existsif(!existsSync(localRootDir)) {
mkdirSync(localRootDir, { recursive: true});
}
// FS.mount() is similar to Linux/POSIX mount operation. It basically mounts an external// filesystem with given format, in given current filesystem directory.FS.mount(FS.filesystems.NODEFS, { root: localRootDir}, rootDir);
}
};
global.cv = require('./opencv.js')
});
}
functioninstallDOM(){
constdom = newJSDOM();
global.document = dom.window.document;
global.Image = Image;
global.HTMLCanvasElement = Canvas;
global.ImageData = ImageData;
global.HTMLImageElement = Image;
}
Execute it
Save the file as exampleNodeCanvasData.js.
Make sure the files aarcascade_frontalface_default.xml and haarcascade_eye.xml␛ are present in project's directory. They can be obtained from OpenCV sources.
Make sure a sample image file lena.jpg exists in project's directory. It should display people's faces for this example to make sense. The following image is known to work:
image
The following command should generate the file output3.jpg: