Check if a curve is closed

2019-07-26 22:05发布

问题:

How can I check efficiently if a curve is closed? For example look this figure:

The curve will always be white on a black background. I tried with flood fill algorithm but not works well with this situation (I don't understand how modify it).

Here the code:

public static boolean isWhite(BufferedImage image, int posX, int posY) {
    Color color = new Color(image.getRGB(posX, posY));
    int r=color.getRed();
    int g=color.getGreen();
    int b=color.getBlue();
    if(r==0&&g==0&&b==0)
        return false;
    return true;
}

public static void checkClosed(BufferedImage bimg) {

    boolean[][] painted = new boolean[bimg.getHeight()][bimg.getWidth()];

    for (int i = 0; i < bimg.getHeight(); i++) {
        for (int j = 0; j < bimg.getWidth(); j++) {

            if (isWhite(bimg, j, i) && !painted[i][j]) {

                Queue<Point> queue = new LinkedList<Point>();
                queue.add(new Point(j, i));

                int pixelCount = 0;
                while (!queue.isEmpty()) {
                    Point p = queue.remove();

                    if ((p.x >= 0) && (p.x < bimg.getWidth() && (p.y >= 0) && (p.y < bimg.getHeight()))) {
                        if (!painted[p.y][p.x] && isWhite(bimg, p.x, p.y)) {
                            painted[p.y][p.x] = true;
                            pixelCount++;


                            queue.add(new Point(p.x + 1, p.y));
                            queue.add(new Point(p.x - 1, p.y));
                            queue.add(new Point(p.x, p.y + 1));
                            queue.add(new Point(p.x, p.y - 1));
                        }
                    }
                }
                System.out.println("Blob detected : " + pixelCount + " pixels");
            }

        }
    }
}

回答1:

The way to see if the boundary in your image is closed is by doing a flood fill of the boundary starting at all the image edge pixels. That is, you put all the background pixels that are at the image edge on the queue, then flood fill from there.

Next, check to see if any background pixels are left. If the flood fill filled inside the object, the boundary wasn’t closed.