0

How do i draw contours on only black object, and filling everything else in the background white? My code currently is able to draw contours on an image:

Bitmap b = BitmapFactory.decodeByteArray(getIntent().getByteArrayExtra("byteArray"),0,getIntent().getByteArrayExtra("byteArray").length);
srcMat= new Mat();
Utils.bitmapToMat(b,srcMat);

Mat gray = new Mat();
Imgproc.cvtColor(srcMat, gray, Imgproc.COLOR_RGBA2GRAY);

Imgproc.Canny(gray, gray, 20, 20*3, 3, true);
List<MatOfPoint> contours = new ArrayList<>();
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);
}

Utils.matToBitmap(gray, b);
imgR.setImageBitmap(b);
1
  • You want to create mask of the image by creating a contour or what other kind of contour you talking about here. Please provide output that you trying to achieve.
    – arqam
    Commented Jul 31, 2017 at 9:51

1 Answer 1

1

You should create and apply mask, like in answer to this question. You can do this, for example, by this way (insert code below after Your Imgproc.findContours() call instead of for (int contourIdx = ...:

// create Mat for mask
Mat mask =  new Mat(new Size(srcMat.cols(), srcMat.rows() ), CvType.CV_8UC1);
mask.setTo(new Scalar(0.0));

// create Scalar for color of mask objects
Scalar white = new Scalar(255, 255, 255);

// draw contours border and fill them
Imgproc.drawContours(mask, contours, -1, white, 10);
for (MatOfPoint contour: contours) {
    Imgproc.fillPoly(mask, Arrays.asList(contour), white);
}

// create mat foe masked image
Mat masked = new Mat();

// apply mask to srcMat and set result to masked
srcMat.copyTo(masked, mask);

Then change gray mat in Utils.matToBitmap() call to masked:

Utils.matToBitmap(masked, b);
imgR.setImageBitmap(b);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.