Ask Your Question
0

Find only internal contours in JavaCV/OpenCV

asked 2020-03-17 09:43:27 -0600

I am having a struggle with finding out only internal contours of the provided image. Finding an external contour is easy, however I have no clue how to find internal contours with JavaCV as documentation lacks.

My code so far is:

for (Mat mat : mats) {
        Mat newMat = mat.clone();
        opencv_imgproc.Canny(mat, newMat, 50.0, 100.0);
        opencv_imgproc.blur(newMat, newMat, new Size(2, 2));
        opencv_core.MatVector contours = new opencv_core.MatVector();
        opencv_core.Mat hierarchy = new opencv_core.Mat();
        //Mat hierarchy = new Mat(new double[]{255, 255, 255, 0});
        opencv_imgproc.findContours(newMat, contours, hierarchy, opencv_imgproc.CV_RETR_TREE, opencv_imgproc.CHAIN_APPROX_SIMPLE, new opencv_core.Point(0, 0));

        List<opencv_core.Rect> rectangles = new ArrayList<>();
        for (Mat matContour : contours.get()) {
           //clueless how to find internal contours here 
        }
edit retag flag offensive close merge delete

Comments

1

I have no clue how to find internal contours with JavaCV as documentation lacks.

it's also a different wrapper from opencv, different api, and not supported here

berak gravatar imageberak ( 2020-03-17 09:51:51 -0600 )edit

It's not a problem, if someone knows solution for opencv it would be fine too. It would be easily converted to javacv, as it is, I am clueless how to achieve this scenario, so I would be grateful if anyone shows the way out. @berak

emsmysykbebfgzsqwd gravatar imageemsmysykbebfgzsqwd ( 2020-03-17 12:00:37 -0600 )edit

One way out would be to strip first contour in contours.get(), but I am looking for more clearer approach.

emsmysykbebfgzsqwd gravatar imageemsmysykbebfgzsqwd ( 2020-03-17 12:09:56 -0600 )edit

1 answer

Sort by ยป oldest newest most voted
2

answered 2020-03-23 17:51:04 -0600

You want to take advantage of the information that findContours will put in hierarchy when using CV_RETR_TREE.

If you don't mind adapting information from a Python tutorial, there's an introduction here.

The gist is that each entry in the contours list will have a corresponding entry in the hierarchy list of the form [Next, Previous, First_Child, Parent], where each value is an index into contours.

To find only internal contours, skip entries where the Parent value is -1.

Source: I just did the opposite (keep only Parent=-1) as a way to close large holes in a flood fill without altering the exterior boundaries. (As a proof of concept before switching to RETR_EXTERNAL.)

edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2020-03-17 09:43:27 -0600

Seen: 1,464 times

Last updated: Mar 23 '20