Ask Your Question
0

Android using drawContours to fill region

asked 2014-10-06 16:55:42 -0500

HasanGhaforian gravatar image

It must be simple to find contours and fill them with specific color.I want to find contours in this simple image:

image description

So I used this snippet of code(here iv is an instance of ImageView and bmp is a Bitmap created from above image):

Mat src = new Mat();
Utils.bitmapToMat(bmp, src);
Imgproc.cvtColor(src, src, Imgproc.COLOR_RGBA2GRAY);

Imgproc.Canny(src, src, 50, 200);
List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
Mat hierarchy = new Mat();
// find contours:
Imgproc.findContours(src, contours, hierarchy, Imgproc.RETR_TREE,Imgproc.CHAIN_APPROX_SIMPLE);
for (int contourIdx = 0; contourIdx < contours.size(); contourIdx++) {
    Imgproc.drawContours(src, contours, contourIdx, new Scalar(0, 0, 255), -1);
}
// create a blank temp bitmap:
Bitmap tempBmp1 = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(),
bmp.getConfig());

Utils.matToBitmap(src, tempBmp1);
iv.setImageBitmap(tempBmp1);

But the result is a totally black image like this:

image description

Did I do any thing wrong?

edit retag flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted
2

answered 2014-10-07 03:11:50 -0500

berak gravatar image

updated 2014-10-07 03:23:50 -0500

you converted your src img to grayscale, so you can't draw something 'red' into it.

(actually, Scalar(255,0,0) would have resulted in a white shape, it only looks at the 1st component for b/w drawing, and yours is unfortunately 0, resulting in an all black img)

keep your bgr src image for later drawing:


Mat src = new Mat();
Utils.bitmapToMat(bmp, src);
Mat gray = new Mat();
Imgproc.cvtColor(src, gray, Imgproc.COLOR_RGBA2GRAY);

Imgproc.Canny(gray, gray, 50, 200);
List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
Mat hierarchy = new Mat();
// find contours:
Imgproc.findContours(gray, contours, hierarchy, Imgproc.RETR_TREE,Imgproc.CHAIN_APPROX_SIMPLE);
for (int contourIdx = 0; contourIdx < contours.size(); contourIdx++) {
    Imgproc.drawContours(src, contours, contourIdx, new Scalar(0, 0, 255), -1);
}

image description

edit flag offensive delete link more
2

answered 2014-10-06 18:45:30 -0500

aliavci gravatar image

Did you convert back to rgb? Its only black and white now

edit flag offensive delete link more

Comments

@aliavci How I can convert binary image to rgb?

HasanGhaforian gravatar imageHasanGhaforian ( 2014-10-07 02:52:23 -0500 )edit

cvtColor(src, dst, GRAY2RGBA, 4)

aliavci gravatar imagealiavci ( 2014-10-07 10:35:53 -0500 )edit
Login/Signup to Answer

Question Tools

Stats

Asked: 2014-10-06 16:55:42 -0500

Seen: 10,889 times

Last updated: Oct 07 '14