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 */
030/**
031 *
032 */
033package org.openimaj.image.processing.face.tracking;
034
035import java.util.ArrayList;
036import java.util.Iterator;
037import java.util.List;
038
039import org.openimaj.image.FImage;
040import org.openimaj.image.processing.face.detection.DetectedFace;
041import org.openimaj.image.processing.face.detection.HaarCascadeDetector;
042import org.openimaj.math.geometry.shape.Rectangle;
043import org.openimaj.video.processing.tracking.BasicObjectTracker;
044import org.openimaj.video.tracking.klt.KLTTracker;
045
046/**
047 * A face tracker that uses the {@link HaarCascadeDetector} to detect faces in
048 * the image and then tracks them using the {@link KLTTracker}.
049 *
050 * @author David Dupplaw (dpd@ecs.soton.ac.uk)
051 *
052 * @created 13 Oct 2011
053 */
054public class KLTHaarFaceTracker implements FaceTracker<FImage> {
055        /** The face detector used to detect the faces */
056        private final HaarCascadeDetector faceDetector = new HaarCascadeDetector();
057
058        /** A list of trackers that are tracking faces within the image */
059        private final List<BasicObjectTracker> trackers = new ArrayList<BasicObjectTracker>();
060
061        /** The previous frame */
062        private FImage previousFrame = null;
063
064        /** When all faces are lost, the frame is retried */
065        private boolean retryFrame = false;
066
067        /** The number of frames to force a retry */
068        private int forceRetry = -1;
069
070        /** Used for forcing retry */
071        private int frameCounter = 0;
072
073        private final float detectionScalar = 1.2f;
074
075        /**
076         * Default constructor that takes the minimum size (in pixels) of detections
077         * that should be considered faces.
078         *
079         * @param minSize
080         *            The minimum size of face boxes
081         */
082        public KLTHaarFaceTracker(final int minSize) {
083                this.faceDetector.setMinSize(minSize);
084        }
085
086        /**
087         * Used to detect faces when there is no current state.
088         *
089         * @return The list of detected faces
090         */
091        private List<DetectedFace> detectFaces(final FImage img) {
092                return this.faceDetector.detectFaces(img);
093        }
094
095        /**
096         * {@inheritDoc}
097         *
098         * @see org.openimaj.image.processing.face.tracking.FaceTracker#trackFace(org.openimaj.image.Image)
099         */
100        @Override
101        public List<DetectedFace> trackFace(final FImage img)
102        {
103                List<DetectedFace> detectedFaces = new ArrayList<DetectedFace>();
104
105                // Determine whether we need to force a retry now
106                if (this.forceRetry != -1 && this.frameCounter % this.forceRetry == 0)
107                        this.trackers.clear();
108
109                // If we're just starting tracking, find some features and start
110                // tracking them.
111                if (this.previousFrame == null || this.trackers.size() == 0) {
112
113                        // Detect the faces in the image.
114                        final List<DetectedFace> faces = this.detectFaces(img);
115
116                        // Create trackers for each face found
117                        for (final DetectedFace face : faces) {
118                                // Create a new tracker for this face
119                                final BasicObjectTracker faceTracker = new BasicObjectTracker();
120                                final Rectangle r = face.getBounds();
121                                r.scaleCentroid(this.detectionScalar);
122                                faceTracker.initialiseTracking(r, img);
123                                this.trackers.add(faceTracker);
124
125                                // Store the last frame
126                                this.previousFrame = img;
127                        }
128
129                        detectedFaces = faces;
130                } else
131                        // If we have a previous frame, attempt to track the frame
132                        if (this.previousFrame != null) {
133                                // Update all the trackers
134                                final Iterator<BasicObjectTracker> i = this.trackers.iterator();
135                                while (i.hasNext()) {
136                                        final BasicObjectTracker tracker = i.next();
137                                        if (tracker.trackObject(img).size() == 0)
138                                                i.remove();
139                                        else {
140                                                // Store the bounding box of the tracked features as the
141                                                // face
142                                                detectedFaces
143                                                .add(new DetectedFace(
144                                                                tracker.getFeatureList().getBounds(),
145                                                                img.extractROI(tracker.getFeatureList().getBounds()),
146                                                                tracker.getFeatureList().countRemainingFeatures()));
147
148                                                // Store the last frame
149                                                this.previousFrame = img;
150                                        }
151                                }
152
153                                if (this.trackers.size() == 0 && this.retryFrame == false) {
154                                        this.retryFrame = true;
155                                        detectedFaces = this.trackFace(img);
156                                }
157                        }
158
159                this.frameCounter++;
160                this.retryFrame = false;
161                return detectedFaces;
162        }
163
164        /**
165         * @return the forceRetry
166         */
167        public int getForceRetry()
168        {
169                return this.forceRetry;
170        }
171
172        /**
173         * @param forceRetry
174         *            the forceRetry to set
175         */
176        public void setForceRetry(final int forceRetry)
177        {
178                this.forceRetry = forceRetry;
179        }
180}