我试图只检测,绘制和填充/着色电池黑色,同时填充其他所有白色,但我也从背景中获得其他线条 . 我该如何解决这个问题?

注意:我无法更改输入图像的背景 .

下面是使用以下代码绘制黑色部分轮廓后得到的图像输出:

if(getIntent().hasExtra("byteArray")) {

            b = BitmapFactory.decodeByteArray(getIntent().getByteArrayExtra("byteArray"),0,getIntent().getByteArrayExtra("byteArray").length);
            contours = new ArrayList<>();
            srcMat= new Mat();
            gray = new Mat();
            matHSV = new Mat();
            Utils.bitmapToMat(b,srcMat);

            Imgproc.cvtColor(srcMat, gray, Imgproc.COLOR_RGBA2GRAY);
            Imgproc.Canny(gray, gray, 20, 20*3, 3, true);

            Mat hierarchy = new Mat();
            Imgproc.findContours(gray,contours,hierarchy,Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
            for (int contourIdx = 0; contourIdx < contours.size(); contourIdx++) {
                Imgproc.drawContours(srcMat, contours, contourIdx, new Scalar(0, 0, 255), -1);


            }
            mask =  new Mat(new Size(srcMat.cols(), srcMat.rows() ), CvType.CV_8UC1);
            mask.setTo(new Scalar(255));

            black = new Scalar(0,0,0);
            Imgproc.drawContours(mask, contours, -1, black, 10);

            for (MatOfPoint contour: contours) {
                Imgproc.fillPoly(mask, Arrays.asList(contour), black);
            }

            Mat masked = new Mat();

            srcMat.copyTo(masked, mask);
            Utils.matToBitmap(mask, b);


            imgR.setImageBitmap(b);
        }

输出:
1

输入:
2