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 :) //HISTOGRAM Histogram1D h; /*cv::MatND histogram = h.getHistogram(img_gray); // VALUE ONLY for(int i = 0 ; i < 256 ; i++) { cout << "Value" << i << " = " << histogram.at<float>(i) << endl; } */ // Histogram --> IMAGE /**/ cv::namedWindow("Histogram"); cv::imshow("Histogram", h.getHistogramImage(img_gray) ); //---HISTOGRAM cv::imshow("My Image",img_gray); 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