/**
* Lubricant Detecter
* Copyright (C) 2021 Carl Klemm
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA  02110-1301, USA.
*/

#pragma once
#include <opencv2/core/ocl.hpp>
#include <opencv2/imgproc.hpp>
#include <stdint.h>
#include <assert.h>

inline bool normalize(cv::Mat& image, const cv::Mat& referance)
{
	assert(image.size() == referance.size());
	assert(image.type() == referance.type());
	assert(image.type() == CV_8UC3 || image.type() == CV_32FC1);
	
	if(image.type() == CV_8UC3)
	{
		cv::Mat labReferance;
		cv::cvtColor(referance, labReferance, cv::COLOR_BGR2Lab);
		std::vector<cv::Mat> labPlanesRef(3);
		cv::split(labReferance, labPlanesRef);

		cv::Scalar mean = cv::mean(labPlanesRef[0]);
		labPlanesRef[0].convertTo(labPlanesRef[0], CV_16SC1);
		
		labPlanesRef[0] = mean/labPlanesRef[0];
		
		
		cv::Mat labImage;
		cv::cvtColor(image, labImage, cv::COLOR_BGR2Lab);
		
		std::vector<cv::Mat> labPlanes(3);
		cv::split(labImage, labPlanes);
		
		labPlanes[0] = labPlanes[0].mul(labPlanesRef[0]);
		cv::merge(labPlanes, labImage);
		cv::cvtColor(labImage, image,  cv::COLOR_Lab2BGR);
	}
	else
	{
		cv::Scalar mean = cv::mean(referance);
		cv::Mat referanceNorm;
		referance.copyTo(referanceNorm);
		referanceNorm = mean/referanceNorm;
		image = image*referanceNorm;
	}
	return true;
}
