001/*******************************************************************************
002 * This software is provided as a supplement to the authors' textbooks on digital
003 *  image processing published by Springer-Verlag in various languages and editions.
004 * Permission to use and distribute this software is granted under the BSD 2-Clause 
005 * "Simplified" License (see http://opensource.org/licenses/BSD-2-Clause). 
006 * Copyright (c) 2006-2016 Wilhelm Burger, Mark J. Burge. All rights reserved. 
007 * Visit http://imagingbook.com for additional details.
008 *******************************************************************************/
009
010package imagingbook.pub.regions;
011
012import ij.process.ByteProcessor;
013
014/**
015 * Binary region labeler based on a recursive flood filling
016 * algorithm. 
017 * 
018 * @author WB
019 * @version 2016-11-08
020 */
021public class RecursiveLabeling extends RegionLabeling {
022
023        /**
024         * Creates a new region labeling.
025         * 
026         * @param ip the binary input image with 0 values for background pixels and values > 0
027         * for foreground pixels.
028         */
029        public RecursiveLabeling(ByteProcessor ip) {
030                super(ip);
031        }
032        
033        @Override
034        void applyLabeling() {
035                resetLabel();
036                for (int v = 0; v < height; v++) {
037                        for (int u = 0; u < width; u++) {
038                                if (getLabel(u, v) >= START_LABEL) {
039                                        // start a new region
040                                        int label = getNextLabel();
041                                        floodFill(u, v, label);
042                                }
043                        }
044                }
045        }
046
047        private void floodFill(int up, int vp, int label) {
048                if ((up>=0) && (up<width) && (vp>=0) && (vp<height) && getLabel(up, vp)>=START_LABEL) {
049                        setLabel(up, vp, label);
050                        floodFill(up + 1, vp, label);
051                        floodFill(up, vp + 1, label);
052                        floodFill(up, vp - 1, label);
053                        floodFill(up - 1, vp, label);
054                }
055        }
056
057}