imgproc_calcHist.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #include <opencv2/imgproc.hpp>
  2. #include <opencv2/highgui.hpp>
  3. using namespace cv;
  4. int main( int argc, char** argv )
  5. {
  6. Mat src, hsv;
  7. if( argc != 2 || !(src=imread(argv[1], 1)).data )
  8. return -1;
  9. cvtColor(src, hsv, COLOR_BGR2HSV);
  10. // Quantize the hue to 30 levels
  11. // and the saturation to 32 levels
  12. int hbins = 30, sbins = 32;
  13. int histSize[] = {hbins, sbins};
  14. // hue varies from 0 to 179, see cvtColor
  15. float hranges[] = { 0, 180 };
  16. // saturation varies from 0 (black-gray-white) to
  17. // 255 (pure spectrum color)
  18. float sranges[] = { 0, 256 };
  19. const float* ranges[] = { hranges, sranges };
  20. MatND hist;
  21. // we compute the histogram from the 0-th and 1-st channels
  22. int channels[] = {0, 1};
  23. calcHist( &hsv, 1, channels, Mat(), // do not use mask
  24. hist, 2, histSize, ranges,
  25. true, // the histogram is uniform
  26. false );
  27. double maxVal=0;
  28. minMaxLoc(hist, 0, &maxVal, 0, 0);
  29. int scale = 10;
  30. Mat histImg = Mat::zeros(sbins*scale, hbins*10, CV_8UC3);
  31. for( int h = 0; h < hbins; h++ )
  32. for( int s = 0; s < sbins; s++ )
  33. {
  34. float binVal = hist.at<float>(h, s);
  35. int intensity = cvRound(binVal*255/maxVal);
  36. rectangle( histImg, Point(h*scale, s*scale),
  37. Point( (h+1)*scale - 1, (s+1)*scale - 1),
  38. Scalar::all(intensity),
  39. -1 );
  40. }
  41. namedWindow( "Source", 1 );
  42. imshow( "Source", src );
  43. namedWindow( "H-S Histogram", 1 );
  44. imshow( "H-S Histogram", histImg );
  45. waitKey();
  46. }