You are on page 1of 3

MAIN.CPP #include <iostream> using namespace std; #include "histogram.h" void main(){ cv::Mat img = cv::imread("pic.

jpg"); cv::Mat img_gray; cvtColor(img,img_gray,CV_RGB2GRAY); // easy way to have grayscale :) cv::Mat img_new = img_gray.clone(); int grayLevel = 256; //HISTOGRAM Histogram1D h; cv::MatND histogram = h.getHistogram(img_gray); //HISTOGRAM BEFORE EQUALIZATION cv::namedWindow("Histogram Before"); cv::imshow("Histogram Before",h.getHistogramImage(img_gray)); // IMAGE BEFORE cv::namedWindow("My Image Before"); cv::imshow("My Image Before",img_gray); //-----------------------------------------------// EQUALIZATION float * pr = new float[grayLevel]; float n = img_gray.rows * img_gray.cols; for(int i = 0 ; i < grayLevel ; i++) { float nk = histogram.at<float>(i); pr[i] = nk / n; } for(int i = 1 ; i < grayLevel ; i++) { pr[i] = pr[i - 1] + pr[i]; } for(int i = 0 ; i < img_new.rows ; i++) { uchar* data = img_new.ptr<uchar>(i); for(int j = 0 ; j < img_new.cols ; j++) { int grayValue = (int)data[j * img_new.channels() + 0 ]; float val = pr[ grayValue ] * ( grayLevel - 1 ); data[j * img_new.channels() + 0 ] = val ; }

} //-----------------------------------------------// HISTOGRAM AFTER cv::namedWindow("Histogram After"); cv::imshow("Histogram After",h.getHistogramImage(img_new)); //---Image After cv::namedWindow("My Image After"); cv::imshow("My Image After",img_new); cv::waitKey(0); } Histogram.h #ifndef _HISTOGRAM #include <opencv2\core\core.hpp> #include <opencv2\highgui\highgui.hpp> #include <opencv2\imgproc\imgproc.hpp> // -> cvtColor class Histogram1D{ private: int histSize[1]; //number of bins float hranges[2]; //min & max pixel value const float* ranges[1]; int channels[1]; // only 1 channels public: Histogram1D(){ // Prepare arguments for 1D histogram histSize[0] = 256; hranges[0] = 0.0; hranges[1] = 255.0; ranges[0] = hranges; channels[0] = 0; } // get Histogram cv::MatND getHistogram(const cv::Mat &image){ cv::MatND hist; //compute histogram cv::calcHist(&image, 1, // 1 image only channels, //channels cv::Mat(), // no mask hist, // the result 1, // 1D histogram histSize, // number of bins ranges // pixel value range ); return hist; } cv::Mat getHistogramImage(const cv::Mat &image)

{ //Compute Hist cv::MatND hist = getHistogram(image); //Get Min and Max Bin Values double max = 0; double min = 0; cv::minMaxLoc(hist,&min,&max,0, 0); //Histogram Image cv::Mat histImg (histSize[0], histSize[0], CV_8U,cv::Scalar(255)); //set highest point int hpt = static_cast<int>(0.9* histSize[0]); // Draw bins for(int h = 0; h < histSize[0]; h++){ float value = hist.at<float>(h); int intensity = static_cast<int>(value * hpt / max); // Draw lines cv::line(histImg, cv::Point(h,histSize[0]), cv::Point(h,histSize[0] - intensity), cv::Scalar::all(0) ); } return histImg; } }; #endif

You might also like