/*
 * Copyright 2016 Jan Dorazil <deu439@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include "detectldd.hpp"

#include <opencv2/opencv.hpp>

using namespace cv;

DetectLDD::DetectLDD(int wSize, double threshold)
  : mWSize(wSize), mThreshold(threshold)
{
}

void DetectLDD::detect(InputArray _temp, InputArray _inpu, OutputArray _outp)
{
  CV_Assert(_temp.type() == CV_32F && _inpu.type() == CV_32F);
  Mat temp = _temp.getMat();
  Mat inpu = _inpu.getMat();
  
  _outp.create(temp.rows, temp.cols, CV_32F);
  Mat outp = _outp.getMat();
  
  int dx, dy;
  float pt1, pt2;
  float tmp;
  for( int y = 0; y < temp.rows - mWSize; y++ ){
    for( int x = 0; x < temp.cols - mWSize; x++ ){
      float p = 0, u = 0;
      
      for( int i = 0; i < mWSize*mWSize; i++ ){
         dx = i % mWSize;
         dy = i / mWSize;
         
         pt1 = temp.at<float>(y + dy, x + dx);
         pt2 = inpu.at<float>(y + dy, x + dx);
         tmp = pt1 / pt2;
         u += tmp;
         p += tmp * tmp;
      }
      u /= mWSize*mWSize;
      p /= mWSize*mWSize;
      outp.at<float>(y + mWSize / 2, x + mWSize / 2) = p - u*u;
    }
  }
}

void DetectLDD::process(DataUnit& data)
{
  assert(!data.mMat[TEMP].empty());
  assert(!data.mMat[TROI].empty());
  assert(!data.mMat[INPU].empty());
  
  // Calculate differece
  Mat d;
  detect(data.mMat[TEMP], data.mMat[INPU], d);

  // Threshold difference
  data.mMat[OUTP] = d > mThreshold;
  
  // Keep changes in ROI only
  multiply(data.mMat[OUTP], data.mMat[TROI], data.mMat[OUTP]);
  
}
