@techstark/opencv-js

repository·main·Indexed 20 days ago

https://github.com/techstark/opencv-js

An NPM package providing the OpenCV JavaScript version for Node.js and browser environments. It enables computer vision tasks in JavaScript/TypeScript applications, offering runtime methods and properties for OpenCV CV objects. Version 5.0.0-release.1 includes support for features such as template matching, colormaps, keypoint drawing, and Locality Sensitive Hashing via the LshTable class.

Tokens
4.5K
Snippets
18
Records
22
Agent score
73%

What's inside @techstark/opencv-js

  1. Overview of @techstark/opencv-js

    main
    The @techstark/opencv-js package provides the runtime methods and properties for OpenCV CV objects in a JavaScript/TypeScript environment. It serves as a bridge to ensure that the expected OpenCV functionality is available and correctly typed for developers working with computer vision in the browser or Node.js.
  2. Check availability of official OpenCV.js binary

    main

    Before updating, determine if an official binary is available for the target version. Use curl to check the docs.opencv.org endpoint.

    • If the response is 200 OK, you can download the binary directly (use step 1a).
    • If the response is 404, you must build the binary from source via GitHub Actions CI (use step 1b).
    curl -I "https://docs.opencv.org/X.Y.Z/opencv.js"
  3. Build OpenCV.js from source via GitHub Actions

    main

    If no official binary exists, trigger the Build OpenCV.js workflow in GitHub Actions with these parameters:

    • opencv_version: The target version tag (e.g., 5.0.0).
    • emscripten_version: 4.0.20 (only bump if required by OpenCV release notes).
    • cmake_options: -DCMAKE_CXX_STANDARD=17 (Required for Emscripten 4.0.20+ and OpenCV 5.x).
    • build_flags: Leave empty.

    After the workflow completes, download the opencv.js artifact from the resulting GitHub Release and replace the existing dist/opencv.js.

  4. Configure TypeScript for @techstark/opencv-js

    main

    When using TypeScript, you can import the module using standard import syntax. To ensure compatibility with the module's export structure, set "esModuleInterop": true in your tsconfig.json file.

    // tsconfig.json
    {
      "compilerOptions": {
        "esModuleInterop": true
      }
    }
    import cv from "@techstark/opencv-js";
    // or
    import * as cv from "@techstark/opencv-js";
  5. Initialize OpenCV.js in your application

    main

    Because OpenCV.js loads asynchronously, you must ensure the runtime is initialized before calling OpenCV methods. The module might be returned as a Promise, or you may need to wait for the onRuntimeInitialized callback. Use the following pattern to safely acquire the cv object.

    import cvModule from "@techstark/opencv-js";
    
    async function getOpenCv() {
      let cv;
      if (cvModule instanceof Promise) {
        cv = await cvModule;
      } else {
        if (cvModule.Mat) {
          cv = cvModule;
        } else {
          await new Promise((resolve) => {
            cvModule.onRuntimeInitialized = () => resolve();
          });
          cv = cvModule;
        }
      }
      return { cv };
    }
    
    async function main() {
      const { cv } = await getOpenCv();
      console.log("OpenCV.js is ready!");
      console.log(cv.getBuildInformation());
    }
    
    main();
  6. Apply UMD compatibility patches to opencv.js

    main

    The downloaded opencv.js binary requires two specific patches to ensure compatibility with modern browser ESM and Webpack strict mode. Apply these using sed:

    1. Patch 1 (Browser ESM Fix): Changes this to globalThis to prevent TypeError.
    2. Patch 2 (Webpack Strict Mode Fix): Changes Module = {} to var Module = {} to prevent ReferenceError.

    After patching, verify the changes with grep.

    # Patch 1: this → globalThis
    sed -i '' 's/}(this, function () {/}(globalThis, function () {/' dist/opencv.js
    
    # Patch 2: Module = {} → var Module = {}
    sed -i '' 's/    Module = {};/    var Module = {};/' dist/opencv.js
    
    # Verification
    grep -c "globalThis, function" dist/opencv.js   # expect 1
    grep -c "var Module = {}"      dist/opencv.js   # expect 1
  7. Configure Webpack for browser usage

    main

    When using this package in a browser environment via Webpack, you must provide polyfills for Node.js-specific modules that are not available in the browser. Update your webpack.config.js to disable these fallbacks.

    module.exports = {
      resolve: {
        modules: [...],
        fallback: {
          fs: false,
          path: false,
          crypto: false
        }
      }
    };
  8. Check available OpenCV methods and properties

    main
    The TypeScript type declarations provided with the package may not always be perfectly synchronized with the latest version of OpenCV.js. To verify which methods and properties are actually available at runtime, refer to the doc/cvKeys.json file in the repository.
  9. Update version strings across the project

    main

    When bumping the OpenCV version, update the following files to maintain consistency:

    FileField/Section to Update
    package.json`
  10. Draw matches between two images with drawMatches()

    main

    Use drawMatches to draw lines connecting corresponding keypoints from two different images in a single output image.

    Parameters:

    • img1: The first source image.
    • keypoints1: Keypoints from the first source image.
    • img2: The second source image.
    • keypoints2: Keypoints from the second source image.
    • matches1to2: The matches where keypoints1[i] corresponds to keypoints2[matches[i]].
    • outImg: The output image (InputOutputArray).
    • matchColor (optional): Color of the match lines and connected keypoints. If set to Scalar::all(-1), colors are generated randomly.
    • singlePointColor (optional): Color of keypoints that do not have a match. If set to Scalar::all(-1), colors are generated randomly.
    • matchesMask (optional): A mask determining which matches are drawn. If empty, all matches are drawn.
    • flags (optional): Drawing feature settings defined by DrawMatchesFlags.
    import { drawMatches } from '@techstark/opencv-js';
    
    // Example usage:
    // drawMatches(img1, kp1, img2, kp2, matches, outImg, matchColor, singlePointColor, mask, flags);