FaceCroppingStrategy.java

package ac.essex.ooechs.imaging.commons.apps.training.strategies; 
 
import ac.essex.ooechs.imaging.commons.Pixel; 
import ac.essex.ooechs.imaging.commons.util.Region; 
 
import java.util.Vector; 
 
/** 
 * <p/> 
 * This program is free software; you can redistribute it and/or 
 * modify it under the terms of the GNU General Public License 
 * as published by the Free Software Foundation; either version 2 
 * of the License, or (at your option) any later version, 
 * provided that any use properly credits the author. 
 * This program is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
 * GNU General Public License for more details at http://www.gnu.org 
 * </p> 
 * 
 * @author Olly Oechsle, University of Essex, Date: 17-Oct-2006 
 * @version 1.0 
 */ 
public class FaceCroppingStrategy implements CroppingStrategy { 
 
    public String getName() { 
        return "Face Cropper"; 
    } 
 
    public String getDescription() { 
        return "Select the center points of both eyes and a crop region surrounding the " + 
                "face is generated."; 
    } 
 
    public int countNodes() { 
        return 2; 
    } 
 
    public double getAspectRatio() { 
        return 0.8; 
    } 
 
    public Region getCropRegion(Vector<Pixel> nodes) throws StrategyException { 
 
        if (nodes.size() != countNodes()) { 
            throw new StrategyException("Cannot crop, I need two eye positions to create a face!"); 
        } 
 
        Pixel eye1 = nodes.elementAt(0); 
        Pixel eye2 = nodes.elementAt(1); 
 
        return getCroppingRegion(eye1, eye2); 
 
    } 
 
    public Region getCroppingRegion(Pixel eye1, Pixel eye2) { 
 
        // put eyes in correct order 
        Pixel leftEye, rightEye; 
        Pixel upperEye, lowerEye; 
 
        if (eye1.x < eye2.x) { 
            leftEye = eye1; 
            rightEye = eye2; 
        } else { 
            leftEye = eye2; 
            rightEye = eye1; 
        } 
 
        if (eye1.y < eye2.y) { 
            upperEye = eye1; 
            lowerEye = eye2; 
        } else { 
            upperEye = eye2; 
            lowerEye = eye1; 
        } 
 
        // and find center point 
        double eyeDistX = rightEye.x - leftEye.x; 
        double eyeDistY = lowerEye.y - upperEye.y; 
 
        double centerX = leftEye.x + (eyeDistX / 2); 
        double centerY = upperEye.y + (eyeDistY / 2); 
 
        // build crop region around the centerY; 
 
        // width is going to be twice the eye distance. 
        // height is width / aspect ratio 
 
        double width = eyeDistX * 2.4d; 
        double height = width / getAspectRatio(); 
 
        double left = centerX - (width / 2); 
        double top = centerY - (height * 0.4); 
 
        return new Region((int) left, (int) top, (int) width, (int) height); 
 
    } 
 
 
}