Skip to content

Instantly share code, notes, and snippets.

@NoxFly
Last active September 14, 2023 07:58
Show Gist options
  • Save NoxFly/ff9cc03b2abb5113091ba9b688c506aa to your computer and use it in GitHub Desktop.
Save NoxFly/ff9cc03b2abb5113091ba9b688c506aa to your computer and use it in GitHub Desktop.
OpenCV installation + OpenCV4NodeJS

To install OpenCV

Tried with OpenCV 4.6 and 4.8. Should work for most versions.

# in a new folder Downloads/opencv

# core dependencies / tools
sudo apt update && sudo apt install -y cmake g++ wget unzip
# GTK packages - because building with QT does not work (at least with OpenCV 4.6)
sudo apt-get install libgtk2.0-dev pkg-config

# download sources
wget -O opencv.zip https://github.com/opencv/opencv/archive/4.x.zip
wget -O opencv_contrib.zip https://github.com/opencv/opencv_contrib/archive/4.x.zip

unzip opencv.zip
unzip opencv_contrib.zip

mkdir -p build && cd build

# prepare build scanning all configurations
# we're disabiling QT and enabling GTK because when I tried
# on multiple machines with QT, it always failed
# -----------------!!! IF YOU DON'T WANT EXTRA MODULES !!!----------------
# --- REMOVE -DOPENCV_EXTRA_MODULES_PATH=../opencv_contrib-4.x/modules ---
# Last argument must be the opencv sources path
cmake -DWITH_QT=OFF -DWITH_GTK=ON -DOPENCV_EXTRA_MODULES_PATH=../opencv_contrib-4.x/modules ../opencv-4.x
# This command will take around 1h, depending your CPU
cmake --build .
sudo make install
sudo ldconfig

Opencv installed here :

  • /usr/local/bin
  • /usr/local/include
  • /usr/local/lib

To fix include dependencies issues :

sudo mv /usr/local/include/opencv4/opencv2 /usr/local/include
sudo rmdir /usr/local/include/opencv4

Installation of OpenCV4NodeJS

Prerequire : NodeJS >= 14 installed

Create a new NodeJS project :

npm init -y
echo 'const cv = require("@u4/opencv4nodejs"); const cap = new cv.VideoCapture(0); ' > index.js

Then run these commands in the terminal :

# exports variables upstream
export OPENCV_INCLUDE_DIR=/usr/local/include/opencv4
export OPENCV_LIB_DIR=/usr/local/lib
export OPENCV_BIN_DIR=/usr/local/bin
export OPENCV4NODEJS_DISABLE_AUTOBUILD=1

sudo apt-get install cmake

Add this to the end of your package.json (into the object) :

"opencv4nodejs": {
    "disableAutoBuild": 1,
    "opencvIncludeDir": "/usr/local/include/opencv4",
    "opencvLibDir": "/usr/local/lib",
    "opencvBinDir": "/usr/local/bin"
}

Add this 'install' command in the scripts of package.json :

"scripts": {
    "install": "npx build-opencv --incDir /usr/local/include/opencv4 --libDir /usr/local/lib --binDir /usr/local/bin --nobuild rebuild"
}

Last, run these commands :

npm i @u4/opencv4nodejs # if the latest version does not work, use version ^6.2.4
npm i -g typescript ts-node
node . # should not throw an error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment