gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:22:03 24 4
gpt4 key购买 nike

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

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()函数可以完美绘制。但我想获得 Angular 点的坐标。在 Python 上获得它很简单,但在 JavaScript 上则不然。

如何获取 Angular 点的坐标?

最佳答案

使用 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>

关于javascript - 如何在 OpenCV.js 中获取轮廓 Angular 点的坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59334122/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com