How to use OpenCV with Node.js?
OpenCV is a free-to-use cross-platform programming library that is mainly utilized for computer vision. It is written in C/C++. Computer vision is widely used in applications like face detection, autonomous vehicles, etc. To use this with Node.js we will use opencv4nodejs library. Opencv4nodejs allows us to use the native OpenCV library with our Node.js application. This is a great way of implementing computer vision on your existing website and a great way to make projects.
Advantages of using OpenCV with Node.js
- As OpenCV is written in C/C++ it is very efficient and hence does not slow down the site.
- Implementing on web applications that already have a Node.js backend is super easy hence any project can have features like facial recognition and computer vision.
- Easily use prebuilt classifiers which makes it easy to implement
- It is an open-source library that means it is continuously worked on and updated to improve performance.
Installing Required Modules:
First, we’ll create a web express server that hosts the whole application, then we will use socket.io to update the image and then use OpenCV to read the image.
Example This HTML file will be used to display the image.
index.html
<!DOCTYPE html>
< html >
< body >
< img id = "image" >
<! --Connecting html page to socket.io -->
< script src =
</ script >
< script >
// Connecting socket.io to localhost
// listening to the image event in index.js
socket.on('image', (data)=>{
console.log('data', data);
// Now we are getting the image and
// displaying it via img tag
const imageEle = document.getElementById('image');
// Also we are decoding the base64 encoding
// set in javascript file.
imageEle.src = data:image/jpeg;base64,${image};
});
</ script >
</ body >
</ html >
|
This is the Node.js entry point file which will use express, socket.io, and OpenCV to display the image.
Filename:
index.js
const cv = require( 'opencv4nodejs' );
const path = require( 'path' )
const express = require( 'express' );
const app = express();
const server = require( 'http' ).Server(app);
const io = require( 'socket.io' )(server);
const wCap = new cv.VideoCapture(0);
wCap.set(cv.CAP_PROP_FRAME_WIDTH, 300);
wCap.set(cv.CAP_PROP_FRAME_HEIGHT, 300);
app.get( '/' , (req, res)=>{
res.sendFile(path.join(__dirname, 'index.html' ));
});
setInterval(()=>{
const frame = wCap.read();
const image = cv.imencode( '.jpg' , frame).toString( 'base64' );
io.emit( 'image' , image);
}, 1000)
server.listen(3000);
|
Run index.js file using below command:
node index.js
Output: Open any browser on our machine and type localhost:3000.
Last Updated :
12 May, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...