Published
Edited
Jul 2, 2020
4 forks
3 stars
Insert cell
md`# Contour detection with OpenCV`
Insert cell
Insert cell
html`<img id='origin' alt='No Image' />`
Insert cell
html`<canvas id='output'></canvas>`
Insert cell
sample = () => {
const input = document.getElementById('fileInput');
const image = document.getElementById('origin');
console.log(input);

input.disabled = false;

input.addEventListener(
'change',
e => {
console.log(URL.createObjectURL(e.target.files[0]));
image.src = URL.createObjectURL(e.target.files[0]);
},
false
);

image.onload = function() {
const { cv } = window;
// Source and destination images
const src = new cv.imread('origin');
let dst = cv.Mat.zeros(src.cols, src.rows, cv.CV_8UC3);
// Convert to binary
cv.cvtColor(src, src, cv.COLOR_RGBA2GRAY, 0);
cv.threshold(src, src, 120, 200, cv.THRESH_BINARY);
// Find contours
let contours = new cv.MatVector();
let hierarchy = new cv.Mat();
cv.findContours(src, contours, hierarchy, cv.RETR_CCOMP, cv.CHAIN_APPROX_SIMPLE);
// Draw contours on destination image
for (let i = 0; i < contours.size(); ++i) {
let color = new cv.Scalar(0, 255, 0);
cv.drawContours(dst, contours, i, color, 1, cv.LINE_8, hierarchy, 100);
}
// Show result and clean up
cv.imshow('output', dst);
src.delete(); dst.delete(); contours.delete(); hierarchy.delete();
};
}

Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more