From: Vincent Vanwaelscappel Date: Fri, 22 Nov 2019 20:05:21 +0000 (+0100) Subject: wip #3207 @4 X-Git-Url: http://git.cubedesigners.com/?a=commitdiff_plain;h=d1a133bdc6879cf10ca6d7b426bed7d719fb5801;p=1000pourcent.git wip #3207 @4 --- diff --git a/assets/input.jpg b/assets/input.jpg new file mode 100644 index 0000000..b9c0620 Binary files /dev/null and b/assets/input.jpg differ diff --git a/assets/template.jpg b/assets/template.jpg new file mode 100644 index 0000000..58b05fb Binary files /dev/null and b/assets/template.jpg differ diff --git a/detect.js b/detect.js new file mode 100644 index 0000000..60b9eab --- /dev/null +++ b/detect.js @@ -0,0 +1,80 @@ +document.addEventListener('DOMContentLoaded', function () { + drawImage('assets/input.jpg', 'input', function () { + detect(); + }); +}) + +function drawImage(url, canvas, callback) { + var ctx = document.getElementById(canvas).getContext('2d'); + var img = new Image(); + img.onload = function () { + ctx.drawImage(img, 0, 0); + callback(); + } + img.src = url; +} + +function detect() { + let src = cv.imread('input'); + let dst = cv.Mat.zeros(src.rows, src.cols, cv.CV_8UC3); + let gray = new cv.Mat(); + cv.cvtColor(src, gray, cv.COLOR_BGR2GRAY); + let thr = new cv.Mat(); + cv.threshold(gray, thr, 127, 255, 1); + let contours = new cv.MatVector(); + let hierarchy = new cv.Mat(); + cv.findContours(thr, contours, hierarchy, cv.RETR_CCOMP, cv.CHAIN_APPROX_SIMPLE); + + + var filterByVertices = []; + + for (let i = 0; i < contours.size(); ++i) { + let tmp = new cv.Mat(); + let cnt = contours.get(i); + // You can try more different parameters + cv.approxPolyDP(cnt, tmp, 1, true); + + var cntSize = tmp.size().width * tmp.size().height; + if (cntSize < 5 || cntSize > 6) { + continue; + } + var area = cv.contourArea(tmp, false); + filterByVertices.push({area: area, size: cntSize, contour: tmp}); + } + + if (filterByVertices.length === 0) { + return false; + } + + filterByVertices.sort(function (a, b) { + return b.area - a.area; + }); + var filterByArea = filterByVertices.slice(0, 2); + if (filterByArea[0].area / filterByArea[1].area > 1.1) { + return false; + } + + var c = filterByArea[0]; + if (c.size === 6) { + let tmp = new cv.Mat(); + cv.approxPolyDP(c.contour, tmp, 10, true); + c.contour = tmp; + } + + let poly = new cv.MatVector(); + + poly.push_back(c.contour); + + let color = new cv.Scalar(Math.round(Math.random() * 255), Math.round(Math.random() * 255), + Math.round(Math.random() * 255)); + cv.drawContours(dst, poly, 0, color, 1, 8, hierarchy, 0); + + var res = []; + + for (let j = 0; j < c.contour.rows; j++) { + const vertex = {x: c.contour.data32S[j * 2], y: c.contour.data32S[j * 2 + 1]}; + res.push(vertex); + } + console.log(res); + cv.imshow('output', dst); +} \ No newline at end of file diff --git a/index.html b/index.html new file mode 100644 index 0000000..533ea0c --- /dev/null +++ b/index.html @@ -0,0 +1,14 @@ + + + + + Title + + + + + + + + + \ No newline at end of file