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);
    

    转换后图像效果

    hoffylin
    粉丝