OpenCV, Android: remove background lines draw only object

Viewed 316

I'm trying to only detect, draw & fill/color the battery black while filling everything else white, but I'm getting other lines from the background as well. How do i go about fixing this?

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

Below is the output of an image i got after drawing the contours of everything that's 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

0 Answers
Related