Skip to content

tony-xlh/opencvjs-document-scanner

Repository files navigation

opencvjs-document-scanner

version downloads jsdelivr

A document scanner implemented with opencv.js. It can detect the boundaries of documents and apply perspective transformation to get a deskewed image.

Online demo

opencv-document-scanner.mp4

Example:

example

Installation

Via NPM:

npm install opencv-document-scanner

Via CDN:

<script type="module">
  import { DocumentScanner } from 'https://cdn.jsdelivr.net/npm/opencv-document-scanner/dist/opencv-document-scanner.js';
</script>

You also need to include OpenCV:

<script type="text/javascript">
  var Module = {
    // https://emscripten.org/docs/api_reference/module.html#Module.onRuntimeInitialized
    onRuntimeInitialized() {
      document.getElementById('status').innerHTML = 'OpenCV.js is ready.';
    }
  };
</script>
<script async src="https://docs.opencv.org/4.8.0/opencv.js" type="text/javascript"></script>

Usage

  1. Initialize an instance.

    const documentScanner = new DocumentScanner();
  2. Detect the polygon of documents and return the points.

    const imgElement = document.getElementById("photoRaw")
    const points = documentScanner.detect(imgElement); //detect from an img or canvas element
  3. Get the cropped document image.

    let imgElement = document.getElementById("photoRaw")
    const canvas = documentScanner.crop(imgElement); //get cropped image from an img or canvas element
  4. Live scanning with camera using Dynamsoft Document Viewer.

    <script type="module">
      import { DocumentScanner } from 'https://cdn.jsdelivr.net/npm/opencv-document-scanner/dist/opencv-document-scanner.js';
      const documentScanner = new DocumentScanner();
      const detectHandler = new OpenCVDocumentDetectHandler(documentScanner);
      Dynamsoft.DDV.setProcessingHandler("documentBoundariesDetect", detectHandler);
    </script>

    image

  5. Edit the polygon with Dynamsoft Document Viewer.

    const points = documentScanner.detect(imgElement);
    const quad = [];
    points.forEach(point => {
      quad.push([point.x,point.y]);
    });
    perspectiveViewer.setQuadSelection(quad);

    image

Blog

Web Document Scanner with OpenCV.js