/*
 * 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 "detectdiff.hpp"

#include <opencv2/opencv.hpp>

using namespace cv;

DetectDiff::DetectDiff(double threshold)
  : mThreshold(threshold)
{
}

void DetectDiff::diff(InputArray temp, InputArray in, OutputArray out) const
{
    // Calculate difference
    Mat tmp, mtemp, min;
    tmp = abs(in.getMat() - temp.getMat());
//     mtemp = temp.getMat();
//     min = in.getMat();
//     tmp.create(temp.size(), CV_32F);
// 
//     for(int row = 0; row < temp.rows(); row++) {
//         Vec3f *ptemp = temp.getMat().ptr<Vec3f>(row);
//         Vec3f *pin   = in.getMat().ptr<Vec3f>(row);
//         float *ptmp =  tmp.ptr<float>(row);
// 
//         for( int col = 0; col < temp.cols(); col++ ) {
//             ptmp[col] = norm(pin[col], ptemp[col], NORM_L2SQR);
//         }
//     }

    // Return result
    tmp.copyTo(out);
}

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

  // Threshold difference
  data.mMat[OUTP] = d > mThreshold;
  
  Mat element = getStructuringElement(MORPH_ELLIPSE, Size(3,3));
  morphologyEx(data.mMat[OUTP], data.mMat[OUTP], MORPH_OPEN, element);
  
  // Keep changes in ROI only
  multiply(data.mMat[OUTP], data.mMat[TROI], data.mMat[OUTP]);
}
