roi.vue 20 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
<!--
 * @Author: your name
 * @Date: 2021-12-18 17:18:34
 * @LastEditTime: 2021-12-24 17:26:15
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /sdc-face/src/views/Algo/roi.vue
-->
<template>
  <div class="modal-body b-box">
    <div class="modal-left">
      <div class="pic" id="picbox">
        <img :src="bgUrl"  height="500" width="860" alt="" @load="imgload">
        <canvas id="main"  class="cavmain" height="500" width="860" ></canvas>
      </div>
    </div>
  </div>
</template>
<script>
import { fabric } from "fabric";
var drawingObject = null; //当前绘制对象
var mouseFrom = {},
  mouseTo = {},
  drawType = "",
  canvasObjectIndex = 0,
  canvasObject = null,
  textbox = null;
var drawWidth = 2; //笔触宽度
var color = "#E34F51"; //画笔颜色

var moveCount = 1; //绘制移动计数器
var doDrawing = false; // 绘制状态
var cvselect = false;
var curObjcet = null;
var cvunselect = true;

export default {
  data(){
    return {
      canvas:null,
      polygonMode: false,
      showligang:true,
      pointArray: [],
       activeShape: false,
      lineArray: [],
      klassarr:[],
      bgUrl:"",
       drawWidth: 2,
       roitype:"",
    }
  },
  props:["dtype","rois"],
  watch:{
    rois(){
   
    }
  },
  methods:{
    imgload(){
        this.initRoI();
    },
    setDrawType(val, type){
      //获取所有绘制的对象
      if(val == 'polygon') {
         this.drawPolygon();
      } else {
         this.polygonMode = false;
      }
      this.roitype = type;
     drawType = val
    /**
     * @description: 初始化ROI设置
     * @param {*}
     * @return {*}
     */
    },
    initRoI(){
      let {linexysets:[{coordinates:linec}], directionxysets,recxysets:[{coordinates:recxc}]} = this.rois;
      debugger
      this.intline(linec);
      drawType = 'line'
      this.drawing("init");

      this.initRect(recxc);
      drawType = 'rect'
      this.drawing("init");

      this.initArrow(directionxysets[0])
       drawType = 'arrow'
      this.drawing("init");
      
    },
    /**
     * @description: 坐标转换
     * @param {xy}  坐标集合
     * @return {*} 转换后结果
     */    
    setxy(xy){
      let W = document.getElementsByTagName("img")[0].naturalWidth,
          H = document.getElementsByTagName("img")[0].naturalHeight;
      let {height,width} = document.getElementById('main');
      let scalWidth = width/W;
      let scalHeight = height/H;
      let obj = {};
      // debugger
      obj.x = xy.x * scalWidth
      obj.y = xy.y* scalHeight
      // obj.x = xy.x 
      // obj.y = xy.y
      return obj
    },
    initRect(points) {
     let mousxy =  this.setxy( points[0])
      mouseFrom.x = mousxy.x;
      mouseFrom.y = mousxy.y;
     let mouseToxy =  this.setxy( points[2])
      mouseTo.x = mouseToxy.x;
      mouseTo.y = mouseToxy.y;
    },
    intline(points){
      let mf = this.setxy(points[0])
      mouseFrom.x = mf.x;
      mouseFrom.y = mf.y;
      let mt = this.setxy(points[1])
      mouseTo.x = mt.x;
      mouseTo.y = mt.y ;
    },
    intPolygon(points) {
      let {x,y} =  this.setxy(points[0])
      mouseFrom.x = x;
      mouseFrom.y = y;
      let pointarr = [];
      points.map(ele => {
        let {x,y} =  this.setxy(ele)
        let obj = {
          x:x,
          y:y        
        }
      pointarr.push(obj);
      })
      this.polygonpoint = pointarr
    },
    initArrow(points){
      let xyf = {
        x:points.beginx,
        y:points.beginy,
      }
      let xyt = {
        x:points.endx,
        y:points.endy,
      }
      let mfxy = this.setxy(xyf)
      mouseFrom.x = mfxy.x;
      mouseFrom.y = mfxy.y;
      let mtxy = this.setxy(xyt)
      mouseTo.x = mtxy.x;
      mouseTo.y = mtxy.y;
    },
     
    drawPloygen(){},
    drawing(type) {
   
      var vthis = this;
      var color = this.color
      if (drawingObject && type == "draw") {
        this.canvas.remove(drawingObject);
      }
      switch (drawType) {
        case "arrow": //箭头
           var x1 = mouseFrom.x,
            x2 = mouseTo.x,
            y1 = mouseFrom.y,
            y2 = mouseTo.y;
          var w = x2 - x1,
            h = y2 - y1,
            sh = Math.cos(Math.PI / 4) * 16;
          var sin = h / Math.sqrt(Math.pow(w, 2) + Math.pow(h, 2));
          var cos = w / Math.sqrt(Math.pow(w, 2) + Math.pow(h, 2));
          var w1 = (16 * sin) / 4,
            h1 = (16 * cos) / 4,
            centerx = sh * cos,
            centery = sh * sin;
          /**
           * centerx,centery 表示起始点,终点连线与箭头尖端等边三角形交点相对x,y
           * w1 ,h1用于确定四个点
           */
          var path = " M " + x1 + " " + y1;
          path += " L " + (x2 - centerx + w1) + " " + (y2 - centery - h1);
          path +=
            " L " + (x2 - centerx + w1 * 2) + " " + (y2 - centery - h1 * 2);
          path += " L " + x2 + " " + y2;
          path +=
            " L " + (x2 - centerx - w1 * 2) + " " + (y2 - centery + h1 * 2);
          path += " L " + (x2 - centerx - w1) + " " + (y2 - centery + h1);
          path += " Z";
          this.canvasObject = new fabric.Path(path, {
            stroke:'red',
            fill: 'blue',
            strokeWidth: this.drawWidth,
            roitype:'directionxysets'
          });
          break;
        case "line": //直线
          this.canvasObject = new fabric.Line(
            [mouseFrom.x, mouseFrom.y, mouseTo.x, mouseTo.y],
            {
               strokeWidth: 2,
              class: "line",
              originX: "center",
              originY: "center",
              selectable: true,
              hasBorders: true,
              hasControls: true,
              evented: true,
              objectCaching: false,
              stroke: "red",
              drawtype:'line',
              roitype:'linexysets'
            }
          );
          break;
         case "rect": //长方形
          // eslint-disable-next-line no-redeclare
          var left = mouseFrom.x,
            top = mouseFrom.y;
          this.canvasObject = new fabric.Rect({
            left: left,
            top: top,
            width: mouseTo.x - left, //矩形的宽度
            height: mouseTo.y - top, //矩形的高度
            fill: "rgba(0,0,0,.3)", //填充的颜色
            stroke: "orange", // 边框原色
            roitype:'recxysets',
            strokeWidth: 1, // 边框大小
          });
          break;
        case "polygon": //路径绘制
          var left = mouseFrom.x,
            top = mouseFrom.y,
            path = vthis.path;

          this.canvasObject = new fabric.Polygon(vthis.polygonpoint, {
           
            hasControls: true,
            stroke: color,
            fill: "rgba(255, 255, 255, 0)",
            roitype:'recxysets'
          });
          break;
        default:
          break;
      }
      // canvasObject.index = getCanvasObjectIndex();
      if (this.canvasObject) {
        this.canvasObject.on("selected", function() {
          cvselect = true;
          cvunselect = true;
          curObjcet = vthis.canvasObject || curObjcet;
        });
        this.canvasObject.on("deselected", function() {
          var group = vthis.canvas.getObjects();
          cvunselect = false;
        });
        this.canvasObject.drawtype = drawType;
        vthis.canvas.add(this.canvasObject); //.setActiveObject(canvasObject)
        drawingObject = this.canvasObject;
      }
    },
      addPoint(e) {
      var random = Math.floor(Math.random() * 10000);
      var id = new Date().getTime() + random;
      var circle = new fabric.Circle({
        radius: 5,
        fill: "#ffffff",
        stroke: "#333333",
        strokeWidth: 0.5,
        left: (e.pointer.x || e.e.layerX) / this.canvas.getZoom(),
        top: (e.pointer.y || e.e.layerY) / this.canvas.getZoom(),
        selectable: false,
        hasBorders: false,
        hasControls: false,
        originX: "center",
        originY: "center",
        id: id,
        objectCaching: false
      });
      if (this.pointArray.length == 0) {
        circle.set({
          fill: "red"
        });
      }
      var points = [
        (e.pointer.x || e.e.layerX) / this.canvas.getZoom(),
        (e.pointer.y || e.e.layerY) / this.canvas.getZoom(),
        (e.pointer.x || e.e.layerX) / this.canvas.getZoom(),
        (e.pointer.y || e.e.layerY) / this.canvas.getZoom()
      ];

      this.line = new fabric.Line(points, {
        strokeWidth: 2,
        fill: "#999999",
        stroke: "#999999",
        class: "line",
        originX: "center",
        originY: "center",
        selectable: false,
        hasBorders: false,
        hasControls: false,
        evented: false,
        objectCaching: false
      });
      if (this.activeShape) {
        var pos = this.canvas.getPointer(e.e);
        var points = this.activeShape.get("points");
        points.push({
          x: pos.x,
          y: pos.y
        });
        var polygon = new fabric.Polygon(points, {
          stroke: "rgb(255, 126,10)",
          strokeWidth: 1,
          fill: "#cccccc",
          opacity: 1,
          hasBorders: false,
          hasControls: true,
          evented: false,
          selectable: true,
          objectCaching: false
        });
        polygon.drawtype = drawType;
        this.canvas.remove(this.activeShape);
        this.canvas.add(polygon);
        this.activeShape = polygon;
        this.canvas.requestRenderAll();
      } else {
        var polyPoint = [
          {
            x: (e.pointer.x || e.e.layerX) / this.canvas.getZoom(),
            y: (e.pointer.y || e.e.layerY) / this.canvas.getZoom()
          }
        ];
        var polygon = new fabric.Polygon(polyPoint, {
          stroke: "#333333",
          strokeWidth: 1,
          fill: "#cccccc",
          opacity: 0.3,

          selectable: false,
          hasBorders: false,
          hasControls: false,
          evented: false,
          objectCaching: false
        });
        this.activeShape = polygon;
        this.canvas.add(polygon);
      }
      this.activeLine = this.line;
      this.pointArray.push(circle);
      this.lineArray.push(this.line);
      this.canvas.add(this.line);
      this.canvas.add(circle);
    },
    Initfab() {
      var vthis = this;
      var deleteIcon =
        "data:image/svg+xml,%3C%3Fxml version='1.0' encoding='utf-8'%3F%3E%3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E%3Csvg version='1.1' id='Ebene_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='595.275px' height='595.275px' viewBox='200 215 230 470' xml:space='preserve'%3E%3Ccircle style='fill:%23F44336;' cx='299.76' cy='439.067' r='218.516'/%3E%3Cg%3E%3Crect x='267.162' y='307.978' transform='matrix(0.7071 -0.7071 0.7071 0.7071 -222.6202 340.6915)' style='fill:white;' width='65.545' height='262.18'/%3E%3Crect x='266.988' y='308.153' transform='matrix(0.7071 0.7071 -0.7071 0.7071 398.3889 -83.3116)' style='fill:white;' width='65.544' height='262.179'/%3E%3C/g%3E%3C/svg%3E";
      var img = document.createElement("img");
      //设置图形显示拖拽点样式
      if (drawType !== "polygon") {
        fabric.Object.prototype.controls.deleteControl = new fabric.Control({
          x: 0.5,
          y: -0.5,
          offsetY: -10,
          offsetX: -30,
          cursorStyle: "pointer",
          mouseUpHandler: deleteObject,
          render: renderIcon,
          cornerSize: 16
        });
      }
      function deleteObject(eventData, transform) {
        var target = transform.target;
        var canvas = target.canvas;
        cvselect = false;
        canvas.remove(target);
        canvas.requestRenderAll();
      }

      function renderIcon(ctx, left, top, styleOverride, fabricObject) {
        var size = this.cornerSize;
        ctx.save();
        ctx.translate(left, top);
        ctx.rotate(fabric.util.degreesToRadians(fabricObject.angle));
        ctx.drawImage(img, - size / 2, -size / 2, size, size);
        ctx.restore();
      }
      img.src = deleteIcon;
      window.zoom = window.zoom ? window.zoom : 1;
      this.canvas = new fabric.Canvas("main", {});
      this.canvas.selectionColor = "rgba(0,0,0,0)";
      this.canvas.on("mouse:down", function(options) {
        //设置每个区域只允许设置一次
        let klassArr = vthis.canvas.getObjects();
        let drawstatus = true;
        for(let i = 0;i < klassArr.length; i++) {
          if(klassArr[i].roitype == vthis.roitype){
            drawstatus =false;
            break;
          }
        }
      if(!drawstatus) {return false}
      var xy = transformMouse(options.e.offsetX, options.e.offsetY);
        mouseFrom.x = xy.x;
        mouseFrom.y = xy.y;
        let e = options;
        this.skipTargetFind = false;
        try {
          // 此段为判断是否闭合多边形,点击红点时闭合多边形
          if (vthis.pointArray.length > 1) {
            // e.target.id == this.pointArray[0].id 表示点击了初始红点
            if (e.target && e.target.id == vthis.pointArray[0].id) {
              vthis.generatePolygon();
            }
          }
          //未点击红点则继续作画
          if (vthis.polygonMode) {
            vthis.addPoint(e);
          }
        } catch (error) {
          console.log(error);
        }
        if (!cvselect) {
          doDrawing = true;
        } else {
          if (!cvunselect) {
            cvselect = false;
          }
        }
      });
      var vthis = this;
      this.canvas.on("mouse:up", function(options) {
        var xy = transformMouse(options.e.offsetX, options.e.offsetY);
        mouseTo.x = xy.x;
        mouseTo.y = xy.y;
        // if(cvselect) {
        //    vthis.saveRoi(curObjcet, curObjcet.roitype)
        // }
        // if(vthis.canvasObject != null) {
        //   vthis.saveRoi(vthis.canvasObject, vthis.canvasObject.roitype)
        // }
        vthis.canvasObject = null;
        let unique = [...new Set(vthis.klassarr)]
        vthis.klassarr = unique
        drawingObject = null;
        moveCount = 1;
        doDrawing = false;
      });
      this.canvas.on("mouse:move", function(options) {
        if (drawType == "polygon") {
          if (vthis.activeLine && vthis.activeLine.class == "line") {
            var pointer = vthis.canvas.getPointer(options.e);
            vthis.activeLine.set({ x2: pointer.x, y2: pointer.y });

            var points = vthis.activeShape.get("points");
            points[vthis.pointArray.length] = {
              x: pointer.x,
              y: pointer.y,
              zIndex: 1
            };
            vthis.activeShape.set({
              points: points
            });
            vthis.canvas.renderAll();
          }
          vthis.canvas.renderAll();
          return false;
        }
        if (moveCount % 2 && !doDrawing) {
          //减少绘制频率
          return;
        }
        moveCount++;
        var xy = transformMouse(options.e.offsetX, options.e.offsetY);
        mouseTo.x = xy.x;
        mouseTo.y = xy.y;
        vthis.drawing("draw");
      });
      function transformMouse(mouseX, mouseY) {
        return { x: mouseX / window.zoom, y: mouseY / window.zoom };
      }
    },
     //生成多边形
    generatePolygon() {
      var points = new Array();
      this.pointArray.map((point, index) => {
        points.push({
          x: point.left,
          y: point.top
        });
        this.canvas.remove(point);
      });
      this.lineArray.map((line, index) => {
        this.canvas.remove(line);
      });
      this.canvas.remove(this.activeShape).remove(this.activeLine);
      var polygon = new fabric.Polygon(points, {
        stroke: "rgb(255,126,10)",
        strokeWidth: this.drawWidth,
        fill: "rgba(255, 255, 255, 0)",
        
        selectable: true,
        hasBorders: true,
        hasControls: true,
        evented: true,
        objectCaching: false,
        transparentCorners: false,
        drawtype: 'polygon',
        roitype:'recxysets'
      });
      polygon.drawtype = drawType;
      this.canvas.add(polygon);
      // polygon.key = this.citem.config['算法ID']
      this.canvasObject = polygon
      this.activeLine = null;
      this.activeShape = null;
      this.polygonMode = false;
      this.doDrawing = false;
      this.drawType = null;
      var group = this.canvas.getObjects();
    },
    // 绘制多边形开始,绘制多边形和其他图形不一样,需要单独处理
    drawPolygon() {
      drawType = "polygon";
      this.polygonMode = true;
      //这里画的多边形,由顶点与线组成
      this.pointArray = new Array(); // 顶点集合
      this.lineArray = new Array(); //线集合
      // this.canvas.isDrawingMode = false;
    },
    capImg(){
      this.$api.captureImage().then(res => {
        this.bgUrl = 'data:image/png;base64,' + res;
      })
    },
    saveRoi(){
      let areaisActive = false, inoutActive = false, doorLineActive = false;
      let W = document.getElementsByTagName("img")[0].naturalWidth,
          H = document.getElementsByTagName("img")[0].naturalHeight;
      let {height,width} = document.getElementById('main');
      let scalWidth = W/width;
      let scalHeight = H/height;
      let linspoint = [];
      let directionxysets = [];
      let recxysets = [];
      let cavArr = this.canvas.getObjects();
      console.log("🚀 ~ file: roi.vue ~ line 556 ~ saveRoi ~ cavArr", cavArr)
      
      cavArr.map(ele => {
        debugger
      if(ele.roitype == 'linexysets') {
        let { bl,tr} = ele.lineCoords;
        bl.x = bl.x*scalWidth
        bl.y = bl.y*scalHeight
        tr.x = tr.x*scalWidth
        tr.y = tr.y*scalHeight
        let obj = {
          coordinates:[]
        }
        obj.coordinates.push(bl)
        obj.coordinates.push(tr)
        linspoint.push(obj)
        doorLineActive = true
        this.rois['linexysets'] = linspoint;
      } else if (ele.roitype == 'recxysets' && ele.drawtype == 'rect') {
         let { tl,tr,bl,br} = ele.aCoords
        bl.x = bl.x*scalWidth
        bl.y = bl.y*scalHeight
        br.x = br.x*scalWidth
        br.y = br.y*scalHeight
        tl.x = tl.x*scalWidth
        tl.y = tl.y*scalHeight
        tr.x = tr.x*scalWidth
        tr.y = tr.y*scalHeight
         let obj = {
          coordinates:[]
        }
        obj.coordinates.push(tl)
        obj.coordinates.push(tr)
        obj.coordinates.push(bl)
        obj.coordinates.push(br)
        recxysets.push(obj)
        this.rois['recxysets'] = recxysets;
        areaisActive = true
      } else if(ele.roitype == 'recxysets' && ele.drawtype == 'polygon') {
        let {points} = ele
        let spoint = JSON.parse(JSON.stringify(points))
        spoint.map(k=> {
          k.x = k.x*scalWidth
          k.y = k.y*scalHeight
        })
         let obj = {
          coordinates:[]
        }
        obj.coordinates = spoint
         recxysets.push(obj)
        this.rois['recxysets'] =  recxysets
        areaisActive = true
      }  else if(ele.roitype == 'directionxysets') {
        let {path} =  ele;
        let x =  path[0][1]*scalWidth
        let y =  path[0][2]*scalHeight
        let x1 =  path[3][1]*scalWidth
        let y1 =  path[3][2]*scalHeight
        let obj = {
          coordinates:[{
            x: x,
            y: y
          },{
            x: x1,
            y: y1
          }]
        }
      directionxysets.push(obj);
      this.rois['directionxysets'] = directionxysets;
      inoutActive = true
      }
    })
        let info = "";
        if(!areaisActive){
          info = "请绘制识别区域"
        } else if(!inoutActive){
          info = "请绘制进门方向"
        } else if(!doorLineActive) {
          info = "请绘制进门线"
        } else {
          this.$emit('roiset','roi',this.rois)
        }
       this.$message({
          message: info,
          type: 'warning'
        });
    },
  },
  mounted(){
    this.Initfab();
    this.capImg();
  }
}
</script>

<style scoped>
.b-box canvas{
    background: rgba(0,0,0,0);
}
.pic{
  position: relative;
}
.pic img{
  position: absolute;
  height: 100%;
  width: 100%;
  top: 0;
  left: 0;
}

</style>