function stroke(image, width, height) {
const strokeCanvas = document.createElement('canvas')
strokeCanvas.width = width
strokeCanvas.height = height
const strokeCtx = strokeCanvas.getContext('2d')
strokeCtx.drawImage(image, 0, 0, width, height)
document.body.appendChild(strokeCanvas)
const imgData = strokeCtx.getImageData(0, 0, width, height)
// 用于读取图片 通过id 读取img、canvas的img值。
// const imgMat = window.cv.imread(image)
// 通过 canvas 返回的图片的值进行读取
const imgMat = window.cv.matFromImageData(imgData)
const splitMatList = new window.cv.MatVector()
// 对图片数据进行切割,切割成4份、3份或者是1份(根据图片类型来)
window.cv.split(imgMat, splitMatList)
if (splitMatList.size() === 4) {
const processMat = splitMatList.get(3)
// 对数据进行过滤
window.cv.threshold(processMat, processMat, 100, 255, window.cv.THRESH_BINARY)
const contours = new window.cv.MatVector()
const hierarchy = new window.cv.Mat()
// 寻找轮郭
window.cv.findContours(processMat, contours, hierarchy, window.cv.RETR_TREE, window.cv.CHAIN_APPROX_SIMPLE)
// 生成描边路径数据
// let dst = window.cv.Mat.zeros(imgMat.cols, imgMat.rows, window.cv.window.cv_8UC4)
for (let i = 0; i < contours.size(); ++i) {
// let color = new window.cv.Scalar(Math.round(Math.random() * 255), Math.round(Math.random() * 255), Math.round(Math.random() * 255), 255);
const color = new window.cv.Scalar(colorArr[0], colorArr[1], colorArr[2], 255)
window.cv.drawContours(imgMat, contours, i, color, 10, window.cv.LINE_8, hierarchy, 100)
}
}
const newImgData = new ImageData(new Uint8ClampedArray(imgMat.data), imgMat.cols, imgMat.rows)
strokeCtx.putImageData(newImgData, 0, 0)
}
一。如何获取图片,上面是需要传入图片数据,而不是图片链接,可以通过new Image() 进行读取图片。
二。使用 openCV 这个工具进行图片轮郭的读取。通过canvas 读取出来的数据一定是rgba的,不会出现rgb等情况。
三。直接使用 OpenCV 生成含有描边的图片,然后通过canvas 进行显示。
四。地址: https://gitee.com/huangzuomin/h5.git
五。文件目录:/src/components/canvasOperate 里面。启动项目进入 test 里面可以直接看到效果
本文介绍如何使用OpenCV处理canvas获取的rgba图像,通过轮廓检测、颜色填充和描边生成,实现图片的轮廓增强。步骤包括读取图片、运用OpenCV进行处理、并以新的形式在canvas上显示。代码示例展示了从图片到轮廓描边的完整流程。
1万+

被折叠的 条评论
为什么被折叠?



