image 描边

本文介绍如何使用OpenCV处理canvas获取的rgba图像,通过轮廓检测、颜色填充和描边生成,实现图片的轮廓增强。步骤包括读取图片、运用OpenCV进行处理、并以新的形式在canvas上显示。代码示例展示了从图片到轮廓描边的完整流程。
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 里面可以直接看到效果

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值