功能描述
用户拖动不规则多边形后,将多边形透视变换转换为矩形
用到的库
Fabric.js , opencv.js
多边形拖动部分
用到fabric.js 4.0 beta的polygon demo, 将拖动完的点数据储存起来。具体查看官方文档
效果如下
透视变换部分
- 将图片绘制在canvas上转换为opencv.js 的数据矩阵
const outCanvas = document.createElement('canvas');
outCanvas.width = image.width;
outCanvas.height = image.height;
const ctx = outCanvas.getContext('2d');
ctx && ctx.drawImage(image, 0, 0);
const src = cv.imread(outCanvas);
- 用opencv.js的 getPerspectiveTransform 方法获取到目标矩阵,再用 warpPerspective 方法进行透视转换
getResultWithMap = (src: any) => {
const { points } = this;
const array: Array<any> = [];
points.forEach(point => {
array.push(point.x);
array.push(point.y);
});
const dst = new cv.Mat();
const dsize = new cv.Size(this.width, this.height);
const dstWidth = this.width; //转换后图像的宽
const dstHeight = this.height; //转换后图像的高
const srcTri = cv.matFromArray(4, 1, cv.CV_32FC2, array);
const dstTri = cv.matFromArray(4, 1, cv.CV_32FC2, [0, 0, dstWidth, 0, dstWidth, dstHeight, 0, dstHeight]);
const M = cv.getPerspectiveTransform(srcTri, dstTri);
cv.warpPerspective(src, dst, M, dsize);
return dst;
}
- 将矩形重新绘制到canvas上
outCanvas.width = this.width;
outCanvas.height = this.height;
cv.imshow(outCanvas, dst);