#!/bin/sh 
#
# Check and demonstrate the 2D-wavelet packet representation

usage() {
    echo "megawave_wp2dcheck image"
}

if [ $# -ne 1 ]; then
    usage
    exit
fi

if [ "$1" = "-h" ]; then
    usage
    exit
fi

noerror() {
    if [ $? -ne 0 ]; then
	echo "Unexpected error; exit"
	exit 1
    fi
}

echo "Demonstrate decomposition/reconstruction"

SHARE=/usr/share/megawave
DATA=$SHARE/data
WAVE=$DATA/wave
WAVELETFILTER=$WAVE/ortho/da05.ir
WAVELETFILTER2=""

IMAGE=$1

BPARAM="-s 4"
BNAME=${IMAGE}_$$_base
WP=${IMAGE}_$$_wp
R=${IMAGE}_$$_rec
V=${WP}_visu

echo "Creating the quad-tree '$BPARAM' in '$BNAME'"
megawave wp2dmktree $BPARAM $BNAME
noerror

echo "Computing wavelet packets coefficients in '$WP'"
if [ "$WAVELETFILTER2"="" ]; then
    megawave wp2ddecomp $BNAME $IMAGE $WAVELETFILTER $WP
else
    megawave wp2ddecomp -b $WAVELETFILTER2 $BNAME $IMAGE $WAVELETFILTER $WP
fi
noerror

echo "Reconstructing image from wavelet packets in '$R'"
megawave wp2drecomp $WP $R
noerror

echo "Error between the original and the reconstructed image :"
megawave fmse -p $IMAGE $R 

XSIZE=`megawave fsize $IMAGE | cut -f 1 -d " "`
YSIZE=`megawave fsize $IMAGE | cut -f 2 -d " "`

echo "Visualization of the wavelet packets coefficients"
megawave wp2dview  -R $V -p $WP
noerror

ZOOM=""
if [ $XSIZE -lt 512 ] && [ $YSIZE -lt 512 ]; then
    ZOOM="-z 2"
fi
megawave fview $ZOOM $V&
PID="$!"

echo "Type <return> to continue"
read ans
if [ "$PID" != "" ]; then
    kill $PID > /dev/null 2> /dev/null
fi
PID=""

NIMAGE=""

rm -f $BNAME $WP* $R $NIMAGE

echo "Demonstrate image denoising"

# Wavelet to use
WAVELETFILTER=$WAVE/biortho/h/sd07.ir
WAVELETFILTER2=$WAVE/biortho/htilde/sd09.ir

NIMAGE=${IMAGE}_$$_noisy
BPARAM="-w 4"
BNAME=${NIMAGE}_$$_base
R=${NIMAGE}_$$_rec

echo "Computing noisy image '$NIMAGE'"
megawave fnoise -g 10 $IMAGE ${NIMAGE}
noerror

echo "Creating the quad-tree '$BPARAM' in '$BNAME'"
megawave wp2dmktree $BPARAM $BNAME
noerror

echo "Denoise the image by wavelet packets soft thresholding with cycle spinning..."
megawave wp2doperate -t 2 -s 15 -b $WAVELETFILTER2 $BNAME $WAVELETFILTER $NIMAGE $R
noerror

echo "Error between the original and the noisy image :"
megawave fmse -p $IMAGE $NIMAGE
echo "Error between the original and the denoised image :"
megawave fmse -p $IMAGE $R 

X=30
megawave cview -x $X $NIMAGE > /dev/null 2> /dev/null &
PID="$!"
X=$(( $XSIZE + $X + 30 ))
megawave cview -x $X $R > /dev/null 2> /dev/null &
PID="$PID $!"
echo "Left : original noisy image. Right : denoised image"

echo "Type <return> to continue"
read ans
if [ "$PID" != "" ]; then
    kill $PID > /dev/null 2> /dev/null
fi
PID=""

RM -f $BNAME $WP* $R $NIMAGE




