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

#include <opencv2/opencv.hpp>

using namespace cv;

DetectShading::DetectShading(double threshold, int kernel)
  : DetectRatio(), mThreshold(threshold), mKernel(kernel)
{
}

void DetectShading::shade(InputArray temp, InputArray in, OutputArray out) const
{
  Mat r, l;
  ratio(temp.getMat(), in.getMat(), r);
  Size kSize = Size(mKernel, mKernel);
  blur(r, l, kSize);
  pow(r-l, 2, r);
  blur(r, r, kSize);
  
  r.copyTo(out);
}

void DetectShading::process(DataUnit& data)
{
  assert(!data.mMat[TEMP].empty());
  assert(!data.mMat[INPU].empty());
  
  // Calculate the ratio
  Mat s;
  shade(data.mMat[TEMP], data.mMat[INPU], s);

  // Threshold ratio
  data.mMat[OUTP] = s > mThreshold;
  
  // Keep changes in ROI only
  multiply(data.mMat[OUTP], data.mMat[TROI], data.mMat[OUTP]);
  s *= 10;
  imshow("Out", s);
  waitKey();
}
