1:/**
2: * Isaias Gonzalez <siderevs@gmail.com>
3: * 1D Histogram with OpenCV
4: */
5:
6:#include <cv.h>
7:#include <cvaux.h>
8:#include <highgui.h>
9:#include <stdio.h>
10:
11:IplImage* image= 0;
12:IplImage* imgHistogram = 0;
13:IplImage* gray= 0;
14:
15:CvHistogram* hist;
16:
17:int main( int argc, char** argv ){
18:
19: if( argc != 2 || !(image = cvLoadImage(argv[1])) )
20: return -1;
21:
22: //size of the histogram -1D histogram
23: int bins = 256;
24: int hsize[] = {bins};
25:
26: //max and min value of the histogram
27: float max_value = 0, min_value = 0;
28:
29: //value and normalized value
30: float value;
31: int normalized;
32:
33: //ranges - grayscale 0 to 256
34: float xranges[] = { 0, 256 };
35: float* ranges[] = { xranges };
36:
37: //create an 8 bit single channel image to hold a
38: //grayscale version of the original picture
39: gray = cvCreateImage( cvGetSize(image), 8, 1 );
40: cvCvtColor( image, gray, CV_BGR2GRAY );
41:
42: //Create 3 windows to show the results
43: cvNamedWindow("original",1);
44: cvNamedWindow("gray",1);
45: cvNamedWindow("histogram",1);
46:
47: //planes to obtain the histogram, in this case just one
48: IplImage* planes[] = { gray };
49:
50: //get the histogram and some info about it
51: hist = cvCreateHist( 1, hsize, CV_HIST_ARRAY, ranges,1);
52: cvCalcHist( planes, hist, 0, NULL);
53: cvGetMinMaxHistValue( hist, &min_value, &max_value);
54: printf("min: %f, max: %f\n", min_value, max_value);
55:
56: //create an 8 bits single channel image to hold the histogram
57: //paint it white
58: imgHistogram = cvCreateImage(cvSize(bins, 50),8,1);
59: cvRectangle(imgHistogram, cvPoint(0,0), cvPoint(256,50), CV_RGB(255,255,255),-1);
60:
61: //draw the histogram :P
62: for(int i=0; i < bins; i++){
63: value = cvQueryHistValue_1D( hist, i);
64: normalized = cvRound(value*50/max_value);
65: cvLine(imgHistogram,cvPoint(i,50), cvPoint(i,50-normalized), CV_RGB(0,0,0));
66: }
67:
68: //show the image results
69: cvShowImage( "original", image );
70: cvShowImage( "gray", gray );
71: cvShowImage( "histogram", imgHistogram );
72:
73: cvWaitKey();
74:
75: return 0;
76:}
Download it: hist1D.cpp