#include <iostream>
#include "opencv2/opencv.hpp"

using namespace std;
using namespace cv;

Mat calcGrayHist(const Mat& img);
Mat getGrayHistImage(const Mat& hist);
Mat histogram_stretching(const Mat& src);

int main() {
	VideoCapture video;
	video.open("..\\..\\resources\\images\\vtest.avi");
	int fps = video.get(CAP_PROP_FPS);

	Mat src;

	while (true) {
		video >> src;
		if (src.empty())
			return 1;
		imshow("sample", src);
		if (waitKey(1000 / fps) == 27)
			break;
	}
	cvtColor(src, src, COLOR_BGR2GRAY);
	src = src + 20;
	Mat src_hist_img = getGrayHistImage(calcGrayHist(src));
	Mat dst = histogram_stretching(src);
	Mat dst_hist_img = getGrayHistImage(calcGrayHist(dst));

	imshow("src", src);
	imshow("srcHist", src_hist_img);

	imshow("dst", dst);
	imshow("dstHist", dst_hist_img);

	waitKey();
	destroyAllWindows();

	return 0;
}

Mat calcGrayHist(const Mat& img) {
	CV_Assert(img.type() == CV_8UC1);

	Mat hist;
	int channels[] = { 0, };
	int dims = 1;
	const int histSize[] = { 256, };
	float graylevel[] = { 0, 256 };
	const float* ranges[] = { graylevel };

	calcHist(&img, 1, channels, noArray(), hist, dims, histSize, ranges);

	return hist;
}

Mat getGrayHistImage(const Mat& hist) {
	CV_Assert(hist.type() == CV_32FC1);
	CV_Assert(hist.size() == Size(1, 256));

	double histMax;
	minMaxLoc(hist, 0, &histMax);

	Mat imgHist(100, 256, CV_8UC1, Scalar(255));
	for (int i = 0; i < 256; i++) {
		line(imgHist, Point(i, 100), Point(i, 100 - cvRound(hist.at<float>(i, 0) * 100 / histMax)), Scalar(0));
	}

	return imgHist;
}

Mat histogram_stretching(const Mat &src) {
	double gmin, gmax;
	minMaxLoc(src, &gmin, &gmax);

	Mat dst = (src - gmin) * 255 / (gmax - gmin);

	return dst;
}