opencv4nodejs
opencv4nodejs allows you to use the native OpenCV library in nodejs. Besides a synchronous API the package provides an asynchronous API, which allows you to build non-blocking and multithreaded computer vision tasks. opencv4nodejs supports OpenCV 3 and OpenCV 4.
The ultimate goal of this project is to provide a comprehensive collection of nodejs bindings to the API of OpenCV and the OpenCV-contrib modules. To get an overview of the currently implemented bindings, have a look at the type declarations of this package. Furthermore, contribution is highly appreciated. If you want to add missing bindings check out the contribution guide.
- Examples
- How to install
- Usage with Docker
- Usage with Electron
- Usage with NW.js
- Quick Start
- Async API
- With TypeScript
- External Memory Tracking (v4.0.0)
Examples
See examples for implementation.
Face Detection
Face Recognition with the OpenCV face module
Check out Node.js + OpenCV for Face Recognition.
Face Landmarks with the OpenCV face module
face-recognition.js
Face Recognition withCheck out Node.js + face-recognition.js : Simple and Robust Face Recognition using Deep Learning.
Hand Gesture Recognition
Check out Simple Hand Gesture Recognition using OpenCV and JavaScript.
Object Recognition with Deep Neural Networks
Check out Node.js meets OpenCV’s Deep Neural Networks — Fun with Tensorflow and Caffe.
Tensorflow Inception
Single Shot Multibox Detector with COCO
Machine Learning
Check out Machine Learning with OpenCV and JavaScript: Recognizing Handwritten Letters using HOG and SVM.
Object Tracking
Feature Matching
Image Histogram
Boiler plate for combination of opencv4nodejs, express and websockets.
opencv4nodejs-express-websockets - Boilerplate express app for getting started on opencv with nodejs and to live stream the video through websockets.
Automating lights by people detection through classifier
Check out Automating lights with Computer Vision & NodeJS.
How to install
npm install --save opencv4nodejs
Native node modules are built via node-gyp, which already comes with npm by default. However, node-gyp requires you to have python installed. If you are running into node-gyp specific issues have a look at known issues with node-gyp first.
Important note: node-gyp won't handle whitespaces properly, thus make sure, that the path to your project directory does not contain any whitespaces. Installing opencv4nodejs under "C:\Program Files\some_dir" or similar will not work and will fail with: "fatal error C1083: Cannot open include file: 'opencv2/core.hpp'"!**
On Windows you will furthermore need Windows Build Tools to compile OpenCV and opencv4nodejs. If you don't have Visual Studio or Windows Build Tools installed, you can easily install the VS2015 build tools:
npm install --global windows-build-tools
Installing OpenCV Manually
Setting up OpenCV on your own will require you to set an environment variable to prevent the auto build script to run:
# linux and osx:export OPENCV4NODEJS_DISABLE_AUTOBUILD=1# on windows:set OPENCV4NODEJS_DISABLE_AUTOBUILD=1
Windows
You can install any of the OpenCV 3 or OpenCV 4 releases manually or via the Chocolatey package manager:
# to install OpenCV 4.1.0choco install OpenCV -y -version 4.1.0
Note, this will come without contrib modules. To install OpenCV under windows with contrib modules you have to build the library from source or you can use the auto build script.
Before installing opencv4nodejs with an own installation of OpenCV you need to expose the following environment variables:
- OPENCV_INCLUDE_DIR pointing to the directory with the subfolder opencv2 containing the header files
- OPENCV_LIB_DIR pointing to the lib directory containing the OpenCV .lib files
Also you will need to add the OpenCV binaries to your system path:
- add an environment variable OPENCV_BIN_DIR pointing to the binary directory containing the OpenCV .dll files
- append
;%OPENCV_BIN_DIR%;
to your system path variable
Note: Restart your current console session after making changes to your environment.
MacOSX
Under OSX we can simply install OpenCV via brew:
brew updatebrew install opencv@4brew link --force opencv@4
Linux
Under Linux we have to build OpenCV from source manually or using the auto build script.
Installing OpenCV via Auto Build Script
The auto build script comes in form of the opencv-build npm package, which will run by default when installing opencv4nodejs. The script requires you to have git and a recent version of cmake installed.
Auto Build Flags
You can customize the autobuild flags using OPENCV4NODEJS_AUTOBUILD_FLAGS=. Flags must be space-separated.
This is an advanced customization and you should have knowledge regarding the OpenCV compilation flags. Flags added by default are listed here.
Installing a Specific Version of OpenCV
You can specify the Version of OpenCV you want to install via the script by setting an environment variable:
export OPENCV4NODEJS_AUTOBUILD_OPENCV_VERSION=4.1.0
Installing only a Subset of OpenCV modules
If you only want to build a subset of the OpenCV modules you can pass the -DBUILD_LIST cmake flag via the OPENCV4NODEJS_AUTOBUILD_FLAGS environment variable. For example export OPENCV4NODEJS_AUTOBUILD_FLAGS=-DBUILD_LIST=dnn
will build only modules required for dnn
and reduces the size and compilation time of the OpenCV package.
Configuring Environments via package.json
It's possible to specify build environment variables by inserting them into the package.json
as follows:
The following environment variables can be passed:
- autoBuildBuildCuda
- autoBuildFlags
- autoBuildOpencvVersion
- autoBuildWithoutContrib
- disableAutoBuild
- opencvIncludeDir
- opencvLibDir
- opencvBinDir
Usage with Docker
opencv-express - example for opencv4nodejs with express.js and docker
Or simply pull from justadudewhohacks/opencv-nodejs for opencv-3.2 + contrib-3.2 with opencv4nodejs globally installed:
FROM justadudewhohacks/opencv-nodejs
Note: The aforementioned Docker image already has opencv4nodejs
installed globally. In order to prevent build errors during an npm install
, your package.json
should not include opencv4nodejs
, and instead should include/require the global package either by requiring it by absolute path or setting the NODE_PATH
environment variable to /usr/lib/node_modules
in your Dockerfile and requiring the package as you normally would.
Different OpenCV 3.x base images can be found here: https://hub.docker.com/r/justadudewhohacks/.
Usage with Electron
opencv-electron - example for opencv4nodejs with electron
Add the following script to your package.json:
"electron-rebuild": "electron-rebuild -w opencv4nodejs"
Run the script:
$ npm run electron-rebuild
Require it in the application:
const cv = ;
Usage with NW.js
Any native modules, including opencv4nodejs, must be recompiled to be used with NW.js. Instructions on how to do this are available in the Use Native Modules section of the the NW.js documentation.
Once recompiled, the module can be installed and required as usual:
const cv = ;
Quick Start
const cv = ;
Initializing Mat (image matrix), Vec, Point
const rows = 100; // heightconst cols = 100; // width// empty Matconst emptyMat = rows cols cvCV_8UC3;// fill the Mat with default valueconst whiteMat = rows cols cvCV_8UC1 255;const blueMat = rows cols cvCV_8UC3 255 0 0;// from array (3x3 Matrix, 3 channels)const matData =255 0 0 255 0 0 255 0 00 0 0 0 0 0 0 0 0255 0 0 255 0 0 255 0 0;const matFromArray = matData cvCV_8UC3;// from node bufferconst charData = 255 0 ...;const matFromArray = Buffer rows cols cvCV_8UC3;// Pointconst pt2 = 100 100;const pt3 = 100 100 05;// Vectorconst vec2 = 100 100;const vec3 = 100 100 05;const vec4 = 100 100 05 05;
Mat and Vec operations
const mat0 = ...;const mat1 = ...;// arithmetic operations for Mats and Vecsconst matMultipliedByScalar = mat0; // scalar multiplicationconst matDividedByScalar = mat0; // scalar divisionconst mat0PlusMat1 = mat0; // additionconst mat0MinusMat1 = mat0; // subtractionconst mat0MulMat1 = mat0; // elementwise multiplicationconst mat0DivMat1 = mat0; // elementwise division// logical operations Mat onlyconst mat0AndMat1 = mat0;const mat0OrMat1 = mat0;const mat0bwAndMat1 = mat0;const mat0bwOrMat1 = mat0;const mat0bwXorMat1 = mat0;const mat0bwNot = mat0;
Accessing Mat data
const matBGR = ... cvCV_8UC3;const matGray = ... cvCV_8UC1;// get pixel value as vector or number valueconst vec3 = matBGR;const grayVal = matGray;// get raw pixel value as arrayconst b g r = matBGR;// set single pixel valuesmatBGR;matBGR;matGray;// get a 25x25 sub region of the Mat at offset (50, 50)const width = 25;const height = 25;const region = matBGR;// get a node buffer with raw Mat dataconst matAsBuffer = matBGR;// get entire Mat data as JS arrayconst matAsArray = matBGR;
IO
// load image from fileconst mat = cv;cv// save imagecv;cv// show imagecv;cv;// load base64 encoded imageconst base64text='data:image/png;base64,R0lGO..';//Base64 encoded stringconst base64data =base64text;//Strip image type prefixconst buffer = Buffer;const image = cv; //Image is now represented as Mat// convert Mat to base64 encoded jpg imageconst outBase64 = cv; // Perform base64 encodingconst htmlImg='<img src=data:image/jpeg;base64,'+outBase64 + '>'; //Create insert into HTML compatible <img> tag// open capture from webcamconst devicePort = 0;const wCap = devicePort;// open video captureconst vCap = './path/video.mp4';// read frames from captureconst frame = vCap;vCap;// loop through the captureconst delay = 10;let done = false;while !donelet frame = vCap;// loop back to start on end of stream reachedif frameemptyvCap;frame = vCap;// ...const key = cv;done = key !== 255;
Useful Mat methods
const matBGR = ... cvCV_8UC3;// convert typesconst matSignedInt = matBGR;const matDoublePrecision = matBGR;// convert color spaceconst matGray = matBGR;const matHSV = matBGR;const matLab = matBGR;// resizeconst matHalfSize = matBGR;const mat100x100 = matBGR;const matMaxDimIs100 = matBGR;// extract channels and create Mat from channelsconst matB matG matR = matBGR;const matRGB = matR matB matG;
Drawing a Mat into HTML Canvas
const img = ...// convert your image to rgba color spaceconst matRGBA = imgchannels === 1? img: img;// create new ImageData from raw mat dataconst imgData =matRGBAimgcolsimgrows;// set canvas dimensionsconst canvas = document;canvasheight = imgrows;canvaswidth = imgcols;// set image dataconst ctx = canvas;ctx;
Method Interface
OpenCV method interface from official docs or src:
void
translates to:
const src = ...;// invoke with required argumentsconst dst0 = src;// with optional paramatersconst dst2 = src;// or pass specific optional parametersconst optionalArgs =borderType: cvBORDER_CONSTANT;const dst2 = src;
Async API
The async API can be consumed by passing a callback as the last argument of the function call. By default, if an async method is called without passing a callback, the function call will yield a Promise.
Async Face Detection
const classifier = cvHAAR_FRONTALFACE_ALT2;// by nesting callbackscv;// via Promisecv;// using async awaittryconst img = await cv;const grayImg = await img;const objects numDetections = await classifier;...catch errconsole;
With TypeScript
Check out the TypeScript examples.
External Memory Tracking (v4.0.0)
Since version 4.0.0 was released, external memory tracking has been enabled by default. Simply put, the memory allocated for Matrices (cv.Mat) will be manually reported to the node process. This solves the issue of inconsistent Garbage Collection, which could have resulted in spiking memory usage of the node process eventually leading to overflowing the RAM of your system, prior to version 4.0.0.
Note, that in doubt this feature can be disabled by setting an environment variable OPENCV4NODEJS_DISABLE_EXTERNAL_MEM_TRACKING
before requiring the module:
export OPENCV4NODEJS_DISABLE_EXTERNAL_MEM_TRACKING=1 // linuxset OPENCV4NODEJS_DISABLE_EXTERNAL_MEM_TRACKING=1 // windows
Or directly in your code:
processenvOPENCV4NODEJS_DISABLE_EXTERNAL_MEM_TRACKING = 1const cv =