簡體   English   中英

Android OpenCV:顏色檢測提供奇怪的結果

[英]Android OpenCV: color detection giving weird result

我剛剛學習了如何從OpenCV Java中檢測顏色,並從image獲取關注區域

最終,我想知道如何檢測AA電池(帶或不帶黑色膠帶)

我現在正在嘗試檢測圖片中的電池,但是電池不是全黑的,從而給我一個奇怪的結果:

在此處輸入圖片說明

我用黑色膠帶覆蓋了電池,然后再次嘗試,結果似乎更好,但是它在兩個單獨的部分中檢測電池:

在此處輸入圖片說明

碼:

private Bitmap findRoiBlack(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(0, 0, 0);         // lower color border for BLACK
    Scalar upperb = new Scalar(180, 255, 30);      // upper color border for BLACK

    //Scalar lowerb = new Scalar(0, 0, 200);         // lower color border for WHITE
    //Scalar upperb = new Scalar(180, 255, 255);      // upper color border for WHITE
    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 > 400) {
            Point rotated_rect_points[] = new Point[4];
            boundingRect.points(rotated_rect_points);

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

            // test vertical ROI orientation
            if (rect.height > rect.width) {
                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/4比例的“垂直”矩形(AAA電池的直徑為10.5毫米,長度為44.6毫米),大約在圖像的垂直中心,並在其上鍍鉻高亮度元素頂部和底部等)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM