001/**
002 * Copyright (c) 2011, The University of Southampton and the individual contributors.
003 * All rights reserved.
004 *
005 * Redistribution and use in source and binary forms, with or without modification,
006 * are permitted provided that the following conditions are met:
007 *
008 *   *  Redistributions of source code must retain the above copyright notice,
009 *      this list of conditions and the following disclaimer.
010 *
011 *   *  Redistributions in binary form must reproduce the above copyright notice,
012 *      this list of conditions and the following disclaimer in the documentation
013 *      and/or other materials provided with the distribution.
014 *
015 *   *  Neither the name of the University of Southampton nor the names of its
016 *      contributors may be used to endorse or promote products derived from this
017 *      software without specific prior written permission.
018 *
019 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
020 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
021 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
022 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
023 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
024 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
025 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
026 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
027 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
028 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
029 */
030package org.openimaj.image.connectedcomponent;
031
032import java.util.ArrayList;
033import java.util.LinkedHashSet;
034import java.util.List;
035
036import org.openimaj.image.FImage;
037import org.openimaj.image.analyser.ImageAnalyser;
038import org.openimaj.image.pixel.ConnectedComponent;
039import org.openimaj.image.pixel.Pixel;
040
041/**
042 * A Connected Component Labeler for grey-level images. This class can be
043 * used to transform an image that represents a map of labeled objects
044 * into a list of {@link ConnectedComponent}s.  
045 * <p>
046 * Internally we use a flood-fill approach to finding the {@link ConnectedComponent}s.
047 * 
048 * @author Jonathon Hare (jsh2@ecs.soton.ac.uk)
049 */
050public class GreyscaleConnectedComponentLabeler implements ImageAnalyser<FImage> {
051        List<ConnectedComponent> components;
052        
053        /**
054         * Syntactic sugar for calling {@link #analyseImage(FImage)} followed by 
055         * {@link #getComponents()};
056         *  
057         * @param image the image to extract components from
058         * @return the extracted components.
059         */
060        public List<ConnectedComponent> findComponents(FImage image) {
061                analyseImage(image);
062                return components;
063        }
064        
065        protected ConnectedComponent floodFill(FImage image, Pixel start, int[][] output, int color) {
066                ConnectedComponent cc = new ConnectedComponent();
067//              Flood-fill (node, target-color, replacement-color):
068//                       1. Set Q to the empty queue.
069                //Queue<Pixel> queue = new LinkedList<Pixel>();
070                LinkedHashSet<Pixel> queue = new LinkedHashSet<Pixel>();
071                
072//                       2. If the color of node is not equal to target-color, return.
073                float targetColour = image.pixels[start.y][start.x];
074                
075//                       3. Add node to Q.
076                queue.add(start);
077//                       4. For each element n of Q:
078                while (queue.size() > 0) {
079                        //Pixel n = queue.poll();
080                        Pixel n = queue.iterator().next();
081                        queue.remove(n);
082                        
083//                       5.  If the color of n is equal to target-color:
084                        if (image.pixels[n.y][n.x] == targetColour) {
085//                       6.   Set w and e equal to n.
086                                int e = n.x, w=n.x;
087//                       7.   Move w to the west until the color of the node to the west of w no longer matches target-color.
088                                while (w>0 && image.pixels[n.y][w-1] == targetColour) w--;
089                                
090//                       8.   Move e to the east until the color of the node to the east of e no longer matches target-color.
091                                while (e<image.width-1 && image.pixels[n.y][e+1] == targetColour) e++;
092                                
093//                       9.   Set the color of nodes between w and e to replacement-color.
094                                for (int i=w; i<=e; i++) {
095                                        output[n.y][i] = color;
096                                        cc.addPixel(i, n.y);
097                                        
098//                      10.   For each node n between w and e:
099                                        int north = n.y - 1;
100                                        int south = n.y + 1;
101//                      11.    If the color of the node to the north of n is target-color, add that node to Q.
102                                        if (north >= 0 && image.pixels[north][i] == targetColour && output[north][i] != color) queue.add(new Pixel(i, north));
103//                             If the color of the node to the south of n is target-color, add that node to Q.
104                                        if (south < image.height && image.pixels[south][i] == targetColour && output[south][i] != color) queue.add(new Pixel(i, south));
105                                }
106//                      12. Continue looping until Q is exhausted.
107                        }
108                }
109//                      13. Return.
110                return cc;
111        }
112
113        @Override
114        public void analyseImage(FImage image) {
115                components = new ArrayList<ConnectedComponent>();
116                
117                int [][] labels = new int[image.height][image.width];
118                int nextColor=1;
119                
120                for (int y=0; y<image.height; y++) {
121                        for (int x=0; x<image.width; x++) {
122                                if (labels[y][x] == 0) {
123                                        components.add(floodFill(image, new Pixel(x, y), labels, nextColor));
124                                        nextColor++;
125                                }
126                        }
127                }
128        }
129        
130        /**
131         * @return the list of components found in the last call to {@link #analyseImage(FImage)}.
132         */
133        public List<ConnectedComponent> getComponents() {
134                return components;
135        }
136}