void SimplestColorBalance(cv::Mat inArray, cv::Mat &outArray, int percent){

if (percent<= 0)

percent = 5;

inArray.convertTo(inArray, CV_32F);

int rows = inArray.rows;

int cols = inArray.cols;

int chnls = inArray.channels();

double halfPercent = percent /200.0;

std::vector<cv::Mat> channels;

std::vector<cv::Mat> results;

if (chnls == 3){

channels.reserve(3);

cv::split(inArray, channels);

}

else {

channels.reserve(1);

inArray.copyTo(channels[0]);

}

for (int i = 0; i < chnls; i++){

cv::Mat flat;

channels[i].reshape(1,1).copyTo(flat);

cv::sort(flat, flat, cv::SORT_ASCENDING);

double lowVal = flat.at<float>(0, floor(flat.cols * halfPercent));

double topVal = flat.at<float>(0, ceil(flat.cols * (1.0-halfPercent)));

cv::Mat channel = channels[i];

for (int m = 0; m < rows; m++){

for (int n = 0; n < cols; n++){

if (channel.at<float>(m, n) < lowVal)

channel.at<float>(m, n) = lowVal;

if (channel.at<float>(m, n) > topVal)

channel.at<float>(m, n) = topVal;

}

}

cv::normalize(channel, channel, 0, 255, cv::NORM_MINMAX);

//channel.convertTo(channel, CV_32F);

results.push_back(channel);

}

cv::merge(results, outArray);

outArray.convertTo(outArray, CV_8U);

}