OpenCV, To create Histogram and Draw example source code

Example source code to make histogram and drawing.
Show the 'mareHistogram' function.
Input is Mat. The property is CV_8U and binary image.
Output is also Mat. The output Mat is image of histogram.
If you want to get histogram value array, you should get mhist Mat instead of histo in the function.

Thank you.

Mat mareHistogram(Mat& img, int t)
{
 
 //col or row histogram?
 int sz = (t)?img.rows:img.cols;
 Mat mhist = Mat::zeros(1, sz, CV_8U);

 //count nonzero value and check max V
 int max=-100;
 for(int j=0; j < sz; ++j)
 {
  Mat data = (t)?img.row(j):img.col(j);
  int v = countNonZero(data);
  mhist.at< unsigned char >(j) = v;
  if(v > max)
   max=v;
 }

 Mat histo;
 int width,height;
 if(t)
 {
  width = max;
  height = sz;
  histo = Mat::zeros(Size(width, height), CV_8U);

  for(int i=0; i < height; ++i)
  {
   for(int j=0; j < mhist.at< unsigned char >(i); ++j)
    histo.at< unsigned char >(i,j) = 255;
  }

 }else{
  width = sz;
  height = max;
  histo = Mat::zeros(Size(width,height), CV_8U);

  for(int i=0; i< width; ++i)
  {
   for(int j=0; j< mhist.at< unsigned char >(i); ++j)
    histo.at< unsigned char >(max-j-1,i) = 255;
  }

 }

 

 return histo;

}

void main()
{
        Mat img;
 img = imread(".\\test\\2.jpg", 0);

 
 threshold(img, img, 128, 255, CV_THRESH_BINARY);
 
 //0 horizontal(width), 1 vertical(height)
 Mat hHisto = mareHistogram(img, 0);
 Mat vHisto = mareHistogram(img, 1);

  
 imshow("origin",img);
 imshow("hh",hHisto);
 imshow("vv",vHisto);

 waitKey(0);
}




///


Comments

  1. Anonymous25/3/14 13:26

    So much THanks :) if i want to count black pixel, then what should i change ??

    ReplyDelete
    Replies
    1. You can use bitwise_not() function so that inverse the black and white pixel,i think so

      Delete
  2. Anonymous28/6/16 07:14

    These are horizontal and vertical projection histograms right ??

    ReplyDelete

Post a Comment

Popular posts from this blog

OpenCV Stitching example (Stitcher class, Panorama)

(OpenCV Study) Background subtractor MOG, MOG2, GMG example source code (BackgroundSubtractorMOG, BackgroundSubtractorMOG2, BackgroundSubtractorGMG)

Example source code of extract HOG feature from images, save descriptor values to xml file, using opencv (using HOGDescriptor )

Real-time N camera stitching Class.

8 point algorithm (Matlab source code) / The method to get the Fundamental Matrix and the Essential matrix

Optical Flow sample source code using OpenCV

Video Stabilization example source code, (using cvFindHomography, cvWarpPerspective functions in openCV)

yuv422(YUYV) to RGB and RGB to yuv422(YUYV), (Using OpenCV and TBB)

(C, C++) TinyXML , xml read & write

(OpenCV Study) calcOpticalFlowFarneback example source code ( dense optical flow )