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 used
043 * to transform an image that represents a map of labeled objects into a list of
044 * {@link ConnectedComponent}s.
045 * <p>
046 * Internally we use a flood-fill approach to finding the
047 * {@link ConnectedComponent}s.
048 *
049 * @author Jonathon Hare (jsh2@ecs.soton.ac.uk)
050 */
051public class GreyscaleConnectedComponentLabeler implements ImageAnalyser<FImage> {
052        List<ConnectedComponent> components;
053
054        /**
055         * Syntactic sugar for calling {@link #analyseImage(FImage)} followed by
056         * {@link #getComponents()};
057         *
058         * @param image
059         *            the image to extract components from
060         * @return the extracted components.
061         */
062        public List<ConnectedComponent> findComponents(FImage image) {
063                analyseImage(image);
064                return components;
065        }
066
067        protected ConnectedComponent floodFill(FImage image, Pixel start, int[][] output, int color) {
068                final ConnectedComponent cc = new ConnectedComponent();
069                // Flood-fill (node, target-color, replacement-color):
070                // 1. Set Q to the empty queue.
071                // Queue<Pixel> queue = new LinkedList<Pixel>();
072                final LinkedHashSet<Pixel> queue = new LinkedHashSet<Pixel>();
073
074                // 2. If the color of node is not equal to target-color, return.
075                final float targetColour = image.pixels[start.y][start.x];
076
077                // 3. Add node to Q.
078                queue.add(start);
079                // 4. For each element n of Q:
080                while (queue.size() > 0) {
081                        // Pixel n = queue.poll();
082                        final Pixel n = queue.iterator().next();
083                        queue.remove(n);
084
085                        // 5. If the color of n is equal to target-color:
086                        if (image.pixels[n.y][n.x] == targetColour && output[n.y][n.x] != color) {
087                                // 6. Set w and e equal to n.
088                                int e = n.x, w = n.x;
089                                // 7. Move w to the west until the color of the node to the west
090                                // of w no longer matches target-color.
091                                while (w > 0 && image.pixels[n.y][w - 1] == targetColour)
092                                        w--;
093
094                                // 8. Move e to the east until the color of the node to the east
095                                // of e no longer matches target-color.
096                                while (e < image.width - 1 && image.pixels[n.y][e + 1] == targetColour)
097                                        e++;
098
099                                // 9. Set the color of nodes between w and e to
100                                // replacement-color.
101                                for (int i = w; i <= e; i++) {
102                                        output[n.y][i] = color;
103                                        cc.addPixel(i, n.y);
104
105                                        // 10. For each node n between w and e:
106                                        final int north = n.y - 1;
107                                        final int south = n.y + 1;
108                                        // 11. If the color of the node to the north of n is
109                                        // target-color, add that node to Q.
110                                        if (north >= 0 && image.pixels[north][i] == targetColour && output[north][i] != color)
111                                                queue.add(new Pixel(i, north));
112                                        // If the color of the node to the south of n is
113                                        // target-color, add that node to Q.
114                                        if (south < image.height && image.pixels[south][i] == targetColour && output[south][i] != color)
115                                                queue.add(new Pixel(i, south));
116                                }
117                                // 12. Continue looping until Q is exhausted.
118                        }
119                }
120                // 13. Return.
121                return cc;
122        }
123
124        @Override
125        public void analyseImage(FImage image) {
126                components = new ArrayList<ConnectedComponent>();
127
128                final int[][] labels = new int[image.height][image.width];
129                int nextColor = 1;
130
131                for (int y = 0; y < image.height; y++) {
132                        for (int x = 0; x < image.width; x++) {
133                                if (labels[y][x] == 0) {
134                                        components.add(floodFill(image, new Pixel(x, y), labels, nextColor));
135                                        nextColor++;
136                                }
137                        }
138                }
139        }
140
141        /**
142         * @return the list of components found in the last call to
143         *         {@link #analyseImage(FImage)}.
144         */
145        public List<ConnectedComponent> getComponents() {
146                return components;
147        }
148}