Skip to content

Instantly share code, notes, and snippets.

@rezonn
Created May 6, 2020 03:22
Show Gist options
  • Save rezonn/d3243fc74b17f142bb45a7132aa06626 to your computer and use it in GitHub Desktop.
Save rezonn/d3243fc74b17f142bb45a7132aa06626 to your computer and use it in GitHub Desktop.
OpenCV.js basic example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
function ascript(src){
return new Promise((resolve, reject) => {
let script2 = document.createElement('script');
script2.async = true;
script2.onload = function() {resolve(script2)}
script2.onerror = reject;
script2.src = src;
document.head.appendChild(script2);
})
}
window.onload = async function(){
await ascript("https://huningxin.github.io/opencv.js/build/asm.js/opencv.js");
file.disabled = false;
let img = document.getElementById('img');
file.onchange = function(e) {
img.src = URL.createObjectURL(e.target.files[0]);
};
img.onload = main;
}
function main() {
let src = cv.imread(img);
let dst = cv.Mat.zeros(src.rows, src.cols, cv.CV_8UC3);
cv.cvtColor(src, src, cv.COLOR_RGBA2GRAY, 0);
cv.imshow('canvas2', src);
cv.threshold(src, src, 120, 150, cv.THRESH_BINARY);
cv.imshow('canvas3', src);
let contours = new cv.MatVector();
let hierarchy = new cv.Mat();
cv.findContours(src, contours, hierarchy, cv.RETR_CCOMP, cv.CHAIN_APPROX_SIMPLE);
for (let i = 0; i < contours.size(); ++i) {
let color = new cv.Scalar(Math.round(Math.random() * 255), Math.round(Math.random() * 255), Math.round(Math.random() * 255));
cv.drawContours(dst, contours, i, color, 1, cv.LINE_8, hierarchy, 100);
}
cv.imshow('canvas4', dst);
src.delete();
dst.delete();
contours.delete();
hierarchy.delete();
}
</script>
</head>
<body>
<input disabled="true" type="file" id="file"/><br>
<img id="img" height="400" />
<canvas id="canvas2" ></canvas>
<canvas id="canvas3" ></canvas>
<canvas id="canvas4" ></canvas>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment