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

DetectDiffCorr::DetectDiffCorr(int tempKernel, int inKernel, double corrThresh, 
                               int corrType, double diffThresh)
  : DetectDiff(diffThresh),
    DetectCorr(tempKernel, inKernel, corrThresh, corrType)
{
}

void DetectDiffCorr::process(DataUnit& data)
{
  assert(!data.mMat[TEMP].empty());
  assert(!data.mMat[TROI].empty());
  assert(!data.mMat[INPU].empty());
  
  // Calculate correlation
  Mat c;
  corr(data.mMat[TEMP], data.mMat[INPU], c);

  // Threshold correlation
  if( DetectCorr::mCorrType == CV_TM_SQDIFF_NORMED )
    c = c > DetectCorr::mThreshold;
  else
    c = c < DetectCorr::mThreshold;
  
  // Calculate difference
  Mat d;
  diff(data.mMat[TEMP], data.mMat[INPU], d);

  
  // Threshold difference image
  d = d > DetectDiff::mThreshold;
  
//   imshow("Corr", c);
//   imshow("Diff", d);
//   waitKey();
  // Combine masks
  multiply(c, d, data.mMat[OUTP]);
  
  // Keep changes in ROI only
  multiply(data.mMat[OUTP], data.mMat[TROI], data.mMat[OUTP]);
}
