/**
* @file GenericImageTools.cpp
* @brief simple filter stuff
* @author Erik Rodner
* @date 07/30/2008

*/
#include <iostream>

#include "GenericImageTools.h"

template <class PixelValueDst, class PixelValueSrc>
void GenericImageTools::calcIntegralImage ( NICE::ImageT<PixelValueDst> &integralImage, const NICE::ImageT<PixelValueSrc> &image, int xsize, int ysize )
{
  integralImage ( 0, 0 ) = ( PixelValueDst ) image ( 0, 0 );;

  for ( int y = 0 ; y < (ysize - 1); ++y )
    integralImage ( 0, y + 1) = integralImage ( 0, y) + image ( 0, y);

  for ( int x = 0 ; x < (xsize - 1); ++x )
    integralImage ( x + 1, 0 ) = integralImage ( x, 0 ) + image ( x, 0 );

  for ( int y = 1 ; y < ysize ; y++ )
    for ( int x = 1 ; x < xsize ; x++ )
    {
      integralImage ( x, y ) = ( PixelValueDst ) image ( x, y );
      integralImage ( x, y ) += integralImage ( x, y - 1 );
      integralImage ( x, y ) += integralImage ( x - 1, y );
      integralImage ( x, y ) -= integralImage ( x - 1, y - 1 );
    }
}

template <class PixelValueDst, class PixelValueSrc>
void GenericImageTools::nonMaximumSuppression ( NICE::ImageT<PixelValueDst> &dst, const NICE::ImageT<PixelValueSrc> &src, int xsize, int ysize, bool useEightConnectivity )
{
  for ( int y = 0 ; y < ysize ; y++ )
    for ( int x = 0 ; x < xsize ; x++ )
    {
      if ( x != 0 )
      {
        if ( src ( x - 1, y ) > src ( x, y ) ) {
          dst ( x, y ) = 0;
          continue;
        };
        if ( useEightConnectivity ) {
          if ( ( y != 0 ) && ( src ( x, y - 1 ) > src ( x, y ) ) ) {
            dst ( x, y ) = 0;
            continue;
          };
          if ( ( y != ysize - 1 ) && ( src ( x - 1, y + 1 ) > src ( x, y ) ) ) {
            dst ( x, y ) = 0;
            continue;
          };
        }
      }

      if ( x != xsize - 1 )
      {
        if ( src ( x + 1, y ) > src ( x, y ) ) {
          dst ( x, y ) = 0;
          continue;
        };
        if ( useEightConnectivity ) {
          if ( ( y != 0 ) && ( src ( x + 1, y - 1 ) > src ( x, y ) ) ) {
            dst ( x, y ) = 0;
            continue;
          };
          if ( ( y != ysize - 1 ) && ( src ( x + 1, y + 1 ) > src ( x, y ) ) ) {
            dst ( x, y ) = 0;
            continue;
          };
        }
      }

      // CHANGE THIS to dst <-> src !!

      if ( y != 0 )
        if ( src ( x, y - 1 ) > src ( x, y ) ) {
          dst ( x, y ) = 0;
          continue;
        };

      if ( y != ysize - 1 )
        if ( src ( x, y + 1 ) > src ( x, y ) ) {
          dst ( x, y ) = 0;
          continue;
        };

      dst ( x, y ) = src ( x, y );
    }
}

