首页 > 解决方案 > 如何改进矩形的打印?

问题描述

我正在尝试在架子上绘制各种矩形,然后对架子进行排序并将其用作矩阵。问题是我无法绘制每个矩形的轮廓: 在此处输入图像描述

但是,我的结果是这样的: 在此处输入图像描述

这是我的代码:

  public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame{

  Mat img=inputFrame.rgba();
  //bgr to gray
  Imgproc.cvtColor(img,gray,Imgproc.COLOR_BGR2GRAY,0);
   // apply canny
  Imgproc.Canny(gray,gray,100,255,3,true);

  Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, kernelSize);
  //apply dilate
  Imgproc.dilate(gray, gray, kernel);

  Imgproc.GaussianBlur(gray, gray, new Size(3,3), 0);

  List<MatOfPoint> contours = new ArrayList<MatOfPoint>(); 
  Imgproc.findContours(gray, contours, hierarchy, Imgproc.RETR_TREE,Imgproc.CHAIN_APPROX_SIMPLE);
    MatOfPoint2f approxCurve = new MatOfPoint2f();
  // List of rect used for sort
  List<Point> rect_pnt=new ArrayList<Point>();
   //comparator for sorted
    Comparator<Point> comp=new Comparator<Point>() {
    // compare method 
        @Override
        public int compare(Point o1, Point o2) {

            int result= new Integer((int) o1.x).compareTo((int) o2.x);

            if(result==0){

                result = new Integer((int)o1.y).compareTo((int) o2.y);

            }

            return result;

        }

    };

 //For each contour found

    for(int i=0;i<contours.size();i++){

        int j=0;

        //convert contours(i) from MatOfPoint to MatOfPoint2f

        MatOfPoint2f contour2f= new MatOfPoint2f(contours.get(i).toArray());

        double approxDistance=Imgproc.arcLength(contour2f,true)*0.05;

        Imgproc.approxPolyDP(contour2f,approxCurve,approxDistance,true);

        //convert back to MatOfPoint

        MatOfPoint points= new MatOfPoint(approxCurve.toArray());

        //Get bounding rect of contour

        Rect rect = Imgproc.boundingRect(points);

        //draw enclosing rectangle

        if(rect.height>400&&rect.width>400) {
            // if here add rect in list and draw rectangle
            rect_pnt.add(j,rect.tl());
            Imgproc.rectangle(img, rect.tl(), rect.br(), new Scalar(0, 0, 255), 4);
            j++;
        }
    }
    // sort of rect
    Collections.sort(rect_pnt,comp);
    System.out.println("Rectangle sorted:" + rect_pnt);

  return img;
}

所以我想打印架子上的所有矩形,但现在我只打印一个。

你能帮助我吗?

标签: javaandroidopencv

解决方案


推荐阅读