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

时间:2019-12-14 10:08:21

标签: javascript opencv contour

我正在将OpenCV.js与JavaScript结合使用,并尝试获取roxPolyDP返回值。这是我的代码:

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);

使用drawContours()函数可以完美绘制。但是我想获取角点的坐标。在Python上获取它很简单,但在JavaScript上却不是。

如何获取角点的坐标?

2 个答案:

答案 0 :(得分:1)

通过使用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 = {}
        p.x = ci.data32S[j]
        p.y = 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>

答案 1 :(得分:1)