简体   繁体   English

如何在 OpenCV.js 中获得轮廓角点的坐标?

[英]How can I get Coordinates of Points of Contour corners in OpenCV.js?

I'm using OpenCV.js with JavaScript and trying to get points of an approxPolyDP return.我正在将 OpenCV.js 与 JavaScript 一起使用,并试图获得 approxPolyDP 回报的积分。 Here is my code:这是我的代码:

let src = cv.imread(imgElement);
let contours = new cv.MatVector();
let hierarchy = new cv.Mat();
let poly = new cv.MatVector();

cv.findContours(src, contours, hierarchy, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE);

let cnt = contours.get(0);

cv.approxPolyDP(cnt, poly, 0.02 * peri, true);

That draws perfect with drawContours() function.使用drawContours()函数绘制完美。 But I want to get the coordinates of points of the corners.但我想得到角点的坐标。 It's simple to get it on Python, but not JavaScript.在 Python 上获取它很简单,但在 JavaScript 上则不然。

How can I get the points' coordinates of corners?如何获得角点的坐标?

By direct access using data32S property.通过使用data32S属性直接访问。

 function onOpenCvReady() { cv['onRuntimeInitialized']= async ()=>{ await loadSomeImage() const mat = cv.imread(document.querySelector('#imageSrc')) const canvasOutput = document.querySelector('#canvasOutput') canvasOutput.width = mat.size().width canvasOutput.height = mat.size().height cv.cvtColor(mat, mat, cv.COLOR_RGB2GRAY, 0) var contours = new cv.MatVector() const hierarchy = new cv.Mat cv.findContours(mat, contours, hierarchy, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) const points = {} for (let i = 0; i < contours.size(); ++i) { const ci = contours.get(i) points[i] = [] for (let j = 0; j < ci.data32S.length; j += 2){ let p = {} px = ci.data32S[j] py = ci.data32S[j+1] points[i].push(p) } } plotPoints(canvasOutput, points) mat.delete() contours.delete() hierarchy.delete() }; } async function loadSomeImage() { const ctx = document.querySelector('#imageSrc').getContext('2d') ctx.fillStyle = 'black' ctx.fillRect(0,0,279,290) ctx.strokeStyle = 'white' ;[[58,73,96,46,123,114,57,108],[154,92,153,25,263,111],[25,268,32,138,233,131,232,280]].forEach(([x,y,...p]) => { ctx.beginPath();ctx.moveTo(x,y); for(let i = 0; i < p.length; i+= 2){ ctx.lineTo(p[i], p[i+1]) } ctx.lineTo(x,y) ctx.closePath() ctx.stroke() }) } function plotPoints(canvas, points){ const ctx = canvas.getContext('2d') ctx.strokeStyle = 'green' Object.values(points).forEach(ps => { ctx.beginPath() ctx.moveTo(ps[0].x, ps[1].y) ctx.arc(ps[0].x, ps[1].y, 2, 0, 2 * Math.PI) ps.slice(1).forEach(({x,y})=>{ ctx.lineTo(x,y) ctx.arc(x, y, 2, 0, 2 * Math.PI) }) ctx.closePath() ctx.stroke() }) }
 <script async onload="onOpenCvReady()" src="https://docs.opencv.org/master/opencv.js"></script> <canvas id="imageSrc" height="290" width="279" title="base"/></canvas> <canvas id="canvasOutput" style="background:#eeeeee;" title="drawing from points"></canvas>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM