A document scanner implemented with opencv.js. It can detect the boundaries of documents and apply perspective transformation to get a deskewed image.
opencv-document-scanner.mp4
Example:
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>
-
Initialize an instance.
const documentScanner = new DocumentScanner();
-
Detect the polygon of documents and return the points.
const imgElement = document.getElementById("photoRaw"); const points = documentScanner.detect(imgElement, {useCanny:false}); //detect from an img or canvas element. You can use canny edge detection to detect document with uneven lightings. If the contrast of the background and the document is vivid, then you don't need to enable this.
-
Get the cropped document image.
let imgElement = document.getElementById("photoRaw") const canvas = documentScanner.crop(imgElement); //get cropped image from an img or canvas element
-
Live scanning with camera using Dynamsoft Document Viewer.
<script type="module"> import { DocumentScanner, OpenCVDocumentDetectHandler } 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>
-
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);