#!/bin/bash

. ~/local/bin/die

DRAW="-draw"
STEPX="0.05"
STEPY="0.25"
MODEL="$HOME/local/models/mlp-cascade19x19-20-2-110"

# Find the center of the face in the image. Crop the image along the center of
# the face.

# Requirements: 'torch3vision' http://torch3vision.idiap.ch/downloads.php
which mlpcascadescan > /dev/null || \
	die "Please install mlpcascadescan from torch3vision"

[ -e "$MODEL" ] || die "Model file $MODEL not found, get it from torch3vision"

FACE_CENTER=""

# Find the center of the face. Takes a jpeg and finds the face.
function find_center() {
	jpeg="$1"
	temp="/tmp/crop_center_face"
	ppm="$temp.ppm"
	pos="$temp.pos"
	echo "Converting to ppm"
	jpegtopnm $jpeg > $ppm
	if [ -e "$pos" ]; then
		rm "$pos"
	fi
    HEIGHT=`identify -format "%h" "$jpeg"`;
    WIDTH=`identify -format "%w" "$jpeg"`;
	MIN_FACE_WIDTH=`echo $WIDTH / 6 | bc`
	echo "Beginning face detection, min-width=$MIN_FACE_WIDTH"
	echo "mlpcascadescan "$ppm" -dir /tmp/ -savepos $DRAW -model $MODEL \
		-minWsize $MIN_FACE_WIDTH -stepxfactor $STEPX -stepyfactor $STEPY"
	mlpcascadescan "$ppm" -dir /tmp/ -savepos $DRAW -model $MODEL \
		-minWsize $MIN_FACE_WIDTH -stepxfactor $STEPX -stepyfactor $STEPY
	[ -e "$pos" ] || die "Face detection failed: $jpeg"
	FACE_POS=`head -n 2 "$pos" | tail -n 1`
	FACE_X=`echo $FACE_POS | awk '{print $1}'`
	FACE_W=`echo $FACE_POS | awk '{print $3}'`
	FACE_CENTER=`echo $FACE_X + $FACE_W/2 | bc`
	echo "FACE_X: $FACE_X   FACE_W: $FACE_W   FACE_CENTER: $FACE_CENTER"
}

function crop_image() {
	jpeg="$1"
	ext=${jpeg##*.}
    base=`basename "$jpeg" .$ext`
    crop="$base""_crop.jpg"
    HEIGHT=`identify -format "%h" "$jpeg"`;
    WIDTH=`identify -format "%w" "$jpeg"`;
	echo "Cropping $jpeg at $FACE_CENTER, saving to $crop"
	convert -fill white -draw "rectangle $FACE_CENTER,0 $WIDTH,$HEIGHT" "$jpeg" "$crop"
}


for file in $@; do
	echo "Processing file: $file"
	find_center $file
	crop_image $file
done
