fabricjs 实现图像的二值化功能

一、效果图

二、图像二值化的作用

二值化是图像处理中常用的一种方法,其作用是将灰度图像转换为二值图像,即将图像中的像素点根据其灰度值分成两类:黑色和白色。这种处理方法可以帮助我们更清晰地识别图像中的目标,简化图像的复杂度,提高图像的处理速度和准确性。

三、实现思路

1、获取框选的图片,进行截图

c 复制代码
    <div>
      <canvas
        ref="grayCanvas"
        :width="canvasProp.width"
        :height="canvasProp.height"
      ></canvas>
      <canvas
        ref="binaryCanvas"
        :width="canvasProp.width"
        :height="canvasProp.height"
      ></canvas>
    </div>

    <!-- 隐藏的 canvas -->
    <canvas
      ref="hiddenCanvas"
      :width="canvasProp.width"
      :height="canvasProp.height"
      style="display: none;"
    ></canvas>
   // 根据框选的数据,对原图进行截图
    getCanvasImageData() {
      const viewportTransform = this.fabricCanvas.viewportTransform;
      const zoom = this.fabricCanvas.getZoom();
      let selectedCoords = null;

      this.fabricCanvas.getObjects().forEach(rect => {
        const coords = [];
        const points = rect.get("aCoords");

        Object.keys(points).forEach(key => {
          let point = points[key];
          const actualX = (point.x - viewportTransform[4]) / zoom;
          const actualY = (point.y - viewportTransform[5]) / zoom;
          coords.push([Math.round(actualX), Math.round(actualY)]);
        });

        // 假设只有一个矩形对象,我们只需获取一个对象的坐标
        selectedCoords = coords;
      });

      if (selectedCoords) {
        // 获取矩形区域的最小和最大坐标
        const minX = Math.min(...selectedCoords.map(coord => coord[0]));
        const minY = Math.min(...selectedCoords.map(coord => coord[1]));
        const maxX = Math.max(...selectedCoords.map(coord => coord[0]));
        const maxY = Math.max(...selectedCoords.map(coord => coord[1]));

        const width = maxX - minX;
        const height = maxY - minY;

        // 从隐藏的 canvas 中获取选中区域的图像数据
        const ctx = this.$refs.hiddenCanvas.getContext("2d");
        return ctx.getImageData(minX, minY, width, height);
      }

      return null;
    },
    

页面中要有3个canvas,grayCanvas 画灰度图片,binaryCanvas画二值化图片,hiddenCanvas 画原始的图片便于截图

2、对图片进行灰度处理

转化为灰度图片,放在灰度画布中

c 复制代码
  convertToGrayScale(imageData) {
      const data = imageData.data;
      for (let i = 0; i < data.length; i += 4) {
        const avg = 0.3 * data[i] + 0.59 * data[i + 1] + 0.11 * data[i + 2];
        data[i] = avg;
        data[i + 1] = avg;
        data[i + 2] = avg;
      }
      return imageData;
    },
    applyGrayScale() {
      const imageData = this.getCanvasImageData();
      const grayImageData = this.convertToGrayScale(imageData);
      const grayCtx = this.$refs.grayCanvas.getContext("2d");
      grayCtx.putImageData(grayImageData, 0, 0);
      this.applyThreshold();
    },

3、拖动滑块,根据阈值对图片进行二值化处理

c 复制代码
    applyThreshold() {
      const grayCtx = this.$refs.grayCanvas.getContext("2d");
      const grayImageData = grayCtx.getImageData(
        0,
        0,
        this.canvasProp.width,
        this.canvasProp.height
      );
      const data = grayImageData.data;
      for (let i = 0; i < data.length; i += 4) {
        const avg = data[i];
        const value = avg > this.threshold ? 255 : 0;
        data[i] = value;
        data[i + 1] = value;
        data[i + 2] = value;
      }
      const binaryCtx = this.$refs.binaryCanvas.getContext("2d");
      binaryCtx.putImageData(grayImageData, 0, 0);
    },

4、添加滑块移动的监听

c 复制代码
   this.fabricCanvas.on("object:modified", this.applyGrayScale);
   this.fabricCanvas.on("object:added", this.applyGrayScale);
   this.fabricCanvas.on("object:removed", this.applyGrayScale);
相关推荐
小爬的老粉丝2 小时前
JavaScript 纯前端预览 WPS:先识别容器,再路由解析器
前端·javascript·wps
满栀5853 小时前
状态管理:Redux、Vuex、Pinia 核心区别
前端·javascript·typescript
大龄码农有梦想5 小时前
Vue + BPMN.js + Camunda:搭建企业级流程设计器完整实践
javascript·vue.js·流程设计器·bpmn.js·bpmn·流程审批·工作流设计器
Eloudy5 小时前
ReAct 原理简介
前端·javascript·人工智能·react.js·agent·gpu
ZJU_统一阿萨姆6 小时前
【DSH】如何将 DeepSeek Harness 嵌入生产环境?万字解构 DeepSeek Agent Harness 的运行机制与安全边界
前端·javascript·安全
夏天一说说7 小时前
API 安全】API-Pentest:基于 JS 分析 + AI Agent 的自动化 API 渗透测试工具实战指南
javascript·人工智能·安全·api
sunly_8 小时前
TypeScript总结:16、面向对象速查
前端·javascript·typescript
张元清8 小时前
React useInterval Hook:没有过期闭包的 setInterval (2026)
javascript·react.js
MXN_小南学前端8 小时前
React超长文本域中实现“返回顶部”浮动按钮
前端·javascript·react.js
gs801408 小时前
解构 Cordis:面向“时空可组合性”的 TypeScript 元框架深度剖析
前端·javascript·typescript