cvfindcontours js实现
cv.findContours 的 JavaScript 实现
在 JavaScript 中实现类似 OpenCV 的 findContours 功能,可以使用 HTML5 的 Canvas API 或第三方库(如 OpenCV.js)。以下是两种实现方式:
使用 OpenCV.js
-
加载 OpenCV.js 库 在 HTML 文件中引入 OpenCV.js:
<script async src="https://docs.opencv.org/4.5.5/opencv.js" onload="onOpenCvReady();"></script> -
实现 findContours
function findContours() { let src = cv.imread('inputImage'); let dst = new cv.Mat(); let contours = new cv.MatVector(); let hierarchy = new cv.Mat(); cv.cvtColor(src, src, cv.COLOR_RGBA2GRAY); cv.threshold(src, dst, 120, 200, cv.THRESH_BINARY); cv.findContours(dst, contours, hierarchy, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE); // 绘制轮廓 for (let i = 0; i < contours.size(); ++i) { let color = new cv.Scalar(0, 255, 0); cv.drawContours(src, contours, i, color, 2, cv.LINE_8, hierarchy, 0); } cv.imshow('outputCanvas', src); src.delete(); dst.delete(); contours.delete(); hierarchy.delete(); }
使用纯 JavaScript 和 Canvas
-
获取图像数据
const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); -
实现轮廓查找算法

function findContours(imageData) { const width = imageData.width; const height = imageData.height; const data = imageData.data; const visited = new Array(width * height).fill(false); const contours = []; for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { const index = y * width + x; if (data[index * 4] < 128 && !visited[index]) { const contour = []; const stack = [[x, y]]; visited[index] = true; while (stack.length > 0) { const [cx, cy] = stack.pop(); contour.push([cx, cy]); for (let dy = -1; dy <= 1; dy++) { for (let dx = -1; dx <= 1; dx++) { const nx = cx + dx; const ny = cy + dy; if (nx >= 0 && nx < width && ny >= 0 && ny < height) { const nIndex = ny * width + nx; if (data[nIndex * 4] < 128 && !visited[nIndex]) { visited[nIndex] = true; stack.push([nx, ny]); } } } } } contours.push(contour); } } } return contours; }
注意事项
- OpenCV.js 需要从官方 CDN 加载,文件较大(约 8MB),适合需要完整 OpenCV 功能的场景。
- 纯 JavaScript 实现适用于简单轮廓检测,但性能和精度可能不如 OpenCV.js。
- 两种方法均需在浏览器中运行,不支持 Node.js 环境。






