一、效果图
二、图像二值化的作用
二值化是图像处理中常用的一种方法,其作用是将灰度图像转换为二值图像,即将图像中的像素点根据其灰度值分成两类:黑色和白色。这种处理方法可以帮助我们更清晰地识别图像中的目标,简化图像的复杂度,提高图像的处理速度和准确性。
三、实现思路
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);