OpenCV, Android: remove background lines draw object only

I am only trying to detect, draw and fill / paint the black battery, filling everything else with white, but I get other lines in the background too. How can I fix this?

Note. I cannot change the background of the input image.

Below is the result of the image I got after drawing the outlines of all black using the following code:

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);
        }

      

Output: 1

Input: 2

+3


source to share





All Articles