• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * @function calcHist_Demo.cpp
3  * @brief Demo code to use the function calcHist
4  * @author
5  */
6 
7 #include "opencv2/highgui/highgui.hpp"
8 #include "opencv2/imgcodecs.hpp"
9 #include "opencv2/imgproc/imgproc.hpp"
10 #include <iostream>
11 #include <stdio.h>
12 
13 using namespace std;
14 using namespace cv;
15 
16 /**
17  * @function main
18  */
main(int,char ** argv)19 int main( int, char** argv )
20 {
21   Mat src, dst;
22 
23   /// Load image
24   src = imread( argv[1], 1 );
25 
26   if( src.empty() )
27     { return -1; }
28 
29   /// Separate the image in 3 places ( B, G and R )
30   vector<Mat> bgr_planes;
31   split( src, bgr_planes );
32 
33   /// Establish the number of bins
34   int histSize = 256;
35 
36   /// Set the ranges ( for B,G,R) )
37   float range[] = { 0, 256 } ;
38   const float* histRange = { range };
39 
40   bool uniform = true; bool accumulate = false;
41 
42   Mat b_hist, g_hist, r_hist;
43 
44   /// Compute the histograms:
45   calcHist( &bgr_planes[0], 1, 0, Mat(), b_hist, 1, &histSize, &histRange, uniform, accumulate );
46   calcHist( &bgr_planes[1], 1, 0, Mat(), g_hist, 1, &histSize, &histRange, uniform, accumulate );
47   calcHist( &bgr_planes[2], 1, 0, Mat(), r_hist, 1, &histSize, &histRange, uniform, accumulate );
48 
49   // Draw the histograms for B, G and R
50   int hist_w = 512; int hist_h = 400;
51   int bin_w = cvRound( (double) hist_w/histSize );
52 
53   Mat histImage( hist_h, hist_w, CV_8UC3, Scalar( 0,0,0) );
54 
55   /// Normalize the result to [ 0, histImage.rows ]
56   normalize(b_hist, b_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat() );
57   normalize(g_hist, g_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat() );
58   normalize(r_hist, r_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat() );
59 
60   /// Draw for each channel
61   for( int i = 1; i < histSize; i++ )
62   {
63       line( histImage, Point( bin_w*(i-1), hist_h - cvRound(b_hist.at<float>(i-1)) ) ,
64                        Point( bin_w*(i), hist_h - cvRound(b_hist.at<float>(i)) ),
65                        Scalar( 255, 0, 0), 2, 8, 0  );
66       line( histImage, Point( bin_w*(i-1), hist_h - cvRound(g_hist.at<float>(i-1)) ) ,
67                        Point( bin_w*(i), hist_h - cvRound(g_hist.at<float>(i)) ),
68                        Scalar( 0, 255, 0), 2, 8, 0  );
69       line( histImage, Point( bin_w*(i-1), hist_h - cvRound(r_hist.at<float>(i-1)) ) ,
70                        Point( bin_w*(i), hist_h - cvRound(r_hist.at<float>(i)) ),
71                        Scalar( 0, 0, 255), 2, 8, 0  );
72   }
73 
74   /// Display
75   namedWindow("calcHist Demo", WINDOW_AUTOSIZE );
76   imshow("calcHist Demo", histImage );
77 
78   waitKey(0);
79 
80   return 0;
81 
82 }
83