使用opencv.js获取轮廓点

时间:2018-06-25 13:38:17

标签: javascript opencv

我正在here中所述在javascript中使用opencv.js。我正在使用findContour()方法获取计数器。我想在两个轮廓之间获得极左点和右点。有什么办法吗? 这是我的js代码:

    let contours = new cv.MatVector();
    let hierarchy = new cv.Mat();
    cv.findContours(image, contours, hierarchy, 1, 2);
      var cntareas=[];
    for (let i = 0; i < contours.size(); i++) {
       // storing the areas of countors
      cntareas.push(cv.contourArea(contours.get(i)));
     }
   //finding position of largest two areas.
  var twoLargetsValues = findTwoLargestPositions(cntareas);
   //contour with largest area
  var lcnt = contours.get(twoLargetsValues[0]); 
   //contour with second largest area
  var lcnt2 = contours.get(twoLargetsValues[1]);

现在我如何使用lctn和lctn2查找极端的左坐标和右坐标(意味着得到极端的左,右,上,下点)

1 个答案:

答案 0 :(得分:1)

我使用下面的代码做到了:

    var lcntPoint=[], lcnt2Point=[];
    for (let i = 0; i < lcnt.rows; i++) {

     lcntPoint.push({x:lcnt.data32S[i*2],y:lcnt.data32S[i*2+1]});   
    }
    for (let i = 0; i < lcnt2.rows; i++) {
    lcnt2Point.push({x:lcnt2.data32S[i*2],y:lcnt2.data32S[i*2+1]}); 
   }
   var a = findMinPointX(lcntPoint);
   var b = findMinPointX(lcnt2Point);
   var extLeft = (a.x < b.x) ? a.x : b.x;
   a = findMaxPointX(lcntPoint);
   b = findMaxPointX(lcnt2Point);
   var extRight = (a.x > b.x) ? a.x : b.x;

   a = findMinPointY(lcntPoint);
   b = findMinPointY(lcnt2Point);
   var extTop = (a.y < b.y) ? a.y : b.y;

   a = findMaxPointY(lcntPoint);
   b = findMaxPointY(lcnt2Point);
   var extBottom = (a.y > b.y) ? a.y : b.y;

   function findMinPointX(arr){
   var x=[];
   for(let i=0;i<arr.length;i++){
   x[i]=arr[i].x;
   }
   var MinPos=x.indexOf(Math.min(...x));
   return arr[MinPos];
   }
   function findMaxPointX(arr){
   var x=[];
   for(let i=0;i<arr.length;i++){

    x[i]=arr[i].x;
   }

   var MaxPos=x.indexOf(Math.max(...x));
   return arr[MaxPos];
   }
   function findMinPointY(arr){
   var x=[];
   for(let i=0;i<arr.length;i++){
    x[i]=arr[i].y;
   }
   var MinPos=x.indexOf(Math.min(...x));
   return arr[MinPos];
   }
   function findMaxPointY(arr){
   var y=[];
   for(let i=0;i<arr.length;i++){
    y[i]=arr[i].y;
   }
   var MaxPos=y.indexOf(Math.max(...y));
   return arr[MaxPos];
   }