OpenCV:从rect.br()获取x坐标

时间:2017-08-13 12:58:55

标签: java android opencv

我能够在感兴趣的区域周围检测并绘制一个边界矩形,如下所示:

enter image description here

现在我需要找到" x"绿色边界矩形的底部水平线的值。我的主要目标是找到" x"电池底座的价值,以及" x"蓝色纸条的值,这样我就可以计算它们之间的距离。

我只能看到2个值,rect.tl()rect.br(),用于绘制边界矩形Imgproc.rectangle(sourceMat, rect.tl(), rect.br(), green, 3);。我假设" x"从边界矩形的右下角开始的值将是像素点的x坐标。

我如何获得' x'来自rect.br()的价值 当我打印rect.br()Log.e("BR", rect.br().toString());,我得到了这个:

  

E / BR:{793.0,1686.0}

private Bitmap findRoi(Bitmap sourceBitmap) {
        Bitmap roiBitmap = null;
        Scalar green = new Scalar(0, 255, 0, 255);
        Mat sourceMat = new Mat(sourceBitmap.getWidth(), sourceBitmap.getHeight(), CvType.CV_8UC3);
        Utils.bitmapToMat(sourceBitmap, sourceMat);
        Mat roiTmp = sourceMat.clone();

        final Mat hsvMat = new Mat();
        sourceMat.copyTo(hsvMat);

        // convert mat to HSV format for Core.inRange()
        Imgproc.cvtColor(hsvMat, hsvMat, Imgproc.COLOR_RGB2HSV);

        Scalar lowerb = new Scalar(85, 50, 40);         // lower color border for BLUE
        Scalar upperb = new Scalar(135, 255, 255);      // upper color border for BLUE
        Core.inRange(hsvMat, lowerb, upperb, roiTmp);   // select only blue pixels
         // find contours
        List<MatOfPoint> contours = new ArrayList<>();
        List<RotatedRect> boundingRects = new ArrayList<>();
        Imgproc.findContours(roiTmp, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);

        // find appropriate bounding rectangles
        for (MatOfPoint contour : contours) {
            MatOfPoint2f areaPoints = new MatOfPoint2f(contour.toArray());
            RotatedRect boundingRect = Imgproc.minAreaRect(areaPoints);

            double rectangleArea = boundingRect.size.area();

            // test min ROI area in pixels
            if (rectangleArea > 40001) {//400000
                Point rotated_rect_points[] = new Point[4];
                boundingRect.points(rotated_rect_points);

                Rect rect = Imgproc.boundingRect(new MatOfPoint(rotated_rect_points));

                // test horizontal ROI orientation
                if (rect.width > rect.height) {
                    Imgproc.rectangle(sourceMat, rect.tl(), rect.br(), green, 3);
                }
            }
        }

        roiBitmap = Bitmap.createBitmap(sourceMat.cols(), sourceMat.rows(), Bitmap.Config.ARGB_8888);
        Utils.matToBitmap(sourceMat, roiBitmap);
        return roiBitmap;
    }

1 个答案:

答案 0 :(得分:1)

我不了解Java,但我认为它必须与c ++类似,所以我用c ++编写了我的代码。

假设您有如下图所示的矩形 enter image description here

所以我在opencv中写上面的结构

Rect r = Rect(20,20,30,20);  // Rect(x,y,width,height)

我可以通过以下代码访问您想要的内容

int x2=r.br().x ;

下面的图片是整个故事

enter image description here