Process images with OpenCV directly inside a web page!



    As a multi-platform library, OpenCV can be used with an extensive number of languages including, of course, Javascript.

    Doing image processing tasks directly in the browser can be very useful, after all… a big part of the internet is based on multimedia content (hence, video and images). There’s also HTML 5 which allowed us to access each pixel image via canvas API, making everything even easier.

 

OpenCV.js

    OpenCV.js is a JavaScript binding for a large subset of  OpenCV functions. It could be loaded in a webpage by the <script>  tag. It could take a bit to load ( the file has around 8 Mb)  So be advised that it may not be ready immediately. We always can load it asynchronously by adding async to the tag. The resulting call is as follows:

 

<script async src="https://docs.opencv.org/4.5.4/opencv.js" type="text/javascript"></script>

 

  • Note that the script link is from the official OpenCV website. You can always download it and make it available from your server.

 

The code

Everything will be done using usual tags, such as divs , img  and canvas . So, to show the image:


 

   As mentioned, it is important to load the script asynchronously. Then, it’s necessary to warn the user of the current script state (loading/loaded)

 

 

    The script that does the heavy lifting:

 

    Noticed something? The image processing code we used is the same as we use in other languages. This code simply runs a Canny edge detector on an image:

 

 

   The full code is as follows:

 

 

 

   This code as rendered by your page generates output as shown below, fully interactive and ready to use, have fun!

 

OpenCV.js Magic box 🙂

OpenCV.js status: Loading…