In this tutorial we will learn how to get started with the opencv4nodejs package. This package allows to use the native OpenCV library in Node.js .
In this introductory tutorial we will check how to read an image from the file system and display it on a window.
For the installation instructions, please check the package documentation here.
The first thing we are going to do is importing the opencv4nodejs module, so we can have access to the OpenCV functionality.
const cv = require('opencv4nodejs');
Then we will take care of reading the image from the file system. This is done with a call to the imread function, passing as input a string with the path to the file.
As output, this function returns an object of class Mat, which represents our image. We will store it in a variable.
const image = cv.imread('C:/Users/N/Desktop/Test.jpg');
To finalize, we will display the image with a call to the imshowWait function. This function will display the image in a window.
The imshowWait function receives as first input a string with the name to be assigned to the window and as second input a Mat object to be displayed.
We will call the window “Image” and pass to the function the Mat object we have just obtained from the imread function call.
Note that this window will remain open until we click a key on the keyboard.
The final code can be seen below.
const cv = require('opencv4nodejs'); const image = cv.imread('C:/Users/N/Desktop/Test.jpg'); cv.imshowWait('Image', image);
Testing the code
To test the code, simply run it using a tool of your choice. In my case I’m using Visual Studio Code with the Code Runner extension.
Before running the code, don’t forget to change the path passed as input of the imread function to point to a image in your machine.
You should obtain a result similar to figure 1. As can be seen, a window is opened and the image is displayed. After you click some key in your keyboard, the window should close.
1 thought on “Node.js OpenCV: Getting started”
Olá Nuno, seus tutoriais são ótimos. De alto nível. Como eu não sei nada de Java Script e gostaria de aprender, poderia nos citar um tutorial de como iniciar em JS? Referência bibliográficas, links, etc.
Gustavo Murta (Brasil)