OpenCV2 cookbook source code analyse - histogram

来源:互联网 发布:淘宝如何部分商品退款 编辑:程序博客网 时间:2024/06/05 23:45

Histogram.h

 

#if !defined HISTOGRAM
#define HISTOGRAM

#include <opencv2\core\core.hpp>
#include <opencv2\imgproc\imgproc.hpp>

class Histogram1D {

 

  private:

    int histSize[1];
 float hranges[2];
    const float* ranges[1];
    int channels[1];

  public:

 Histogram1D() {

  // Prepare arguments for 1D histogram
  histSize[0]= 256;
  hranges[0]= 0.0;
  hranges[1]= 255.0;
  ranges[0]= hranges;
  channels[0]= 0; // by default, we look at channel 0
 }

 // Sets the channel on which histogram will be calculated.
 // By default it is channel 0.
 void setChannel(int c) {

  channels[0]= c;
 }

 // Gets the channel used.
 int getChannel() {

  return channels[0];
 }

 // Sets the range for the pixel values.
 // By default it is [0,255]
 void setRange(float minValue, float maxValue) {

  hranges[0]= minValue;
  hranges[1]= maxValue;
 }

 // Gets the min pixel value.
 float getMinValue() {

  return hranges[0];
 }

 // Gets the max pixel value.
 float getMaxValue() {

  return hranges[1];
 }

 // Sets the number of bins in histogram.
 // By default it is 256.
 void setNBins(int nbins) {

  histSize[0]= nbins;
 }

 // Gets the number of bins in histogram.
 int getNBins() {

  return histSize[0];
 }

 // Computes the 1D histogram.
 cv::MatND getHistogram(const cv::Mat &image) {

  cv::MatND hist;

  // Compute histogram
  cv::calcHist(&image,
   1,   // histogram of 1 image only
   channels, // the channel used
   cv::Mat(), // no mask is used
   hist,  // the resulting histogram
   1,   // it is a 1D histogram
   histSize, // number of bins
   ranges  // pixel value range
  );

  return hist;
 }

 // Computes the 1D histogram and returns an image of it.
 cv::Mat getHistogramImage(const cv::Mat &image){

  // Compute histogram first
  cv::MatND hist= getHistogram(image);

  // Get min and max bin values
  double maxVal=0;
  double minVal=0;
  cv::minMaxLoc(hist, &minVal, &maxVal, 0, 0);

  // Image on which to display histogram
  // white backgroud image
  cv::Mat histImg(histSize[0], histSize[0], CV_8U, cv::Scalar(255));

  // set highest point at 90% of nbins, e.g, 90% high of histImg
  int hpt = static_cast<int>(0.9 * histSize[0]);
  
  // coordination direct: origin(left up corner), x down, y right
  // Draw vertical line for each bin
  for( int h = 0; h < histSize[0]; h++ ) {

   float binVal = hist.at<float>(h);
   int intensity = static_cast<int>(binVal * hpt / maxVal);
   // black line
   cv::line(histImg,cv::Point(h,histSize[0]),cv::Point(h,histSize[0]-intensity),cv::Scalar::all(0));
  }

  return histImg;
 }

 // Equalizes the source image.
 cv::Mat equalize(const cv::Mat &image) {

  cv::Mat result;
  cv::equalizeHist(image,result);

  return result;
 }

 // Stretches the source image.
 cv::Mat stretch(const cv::Mat &image, int minValue=0) {

  // Compute histogram first
  cv::MatND hist= getHistogram(image);

  // find left extremity of the histogram
  int imin= 0;
  for( ; imin < histSize[0]; imin++ ) {
   std::cout<<hist.at<float>(imin)<<std::endl;
   if (hist.at<float>(imin) > minValue)
    break;
  }
  
  // find right extremity of the histogram
  int imax= histSize[0]-1;
  for( ; imax >= 0; imax-- ) {

   if (hist.at<float>(imax) > minValue)
    break;
  }

  // Create lookup table
  int dims[1]={256};
  cv::MatND lookup(1,dims,CV_8U);

  for (int i=0; i<256; i++) {
  
   if (i < imin) lookup.at<uchar>(i)= 0;
   else if (i > imax) lookup.at<uchar>(i)= 255;
   else lookup.at<uchar>(i)= static_cast<uchar>(255.0*(i-imin)/(imax-imin)+0.5);
  }

  // Apply lookup table
  cv::Mat result;
  result= applyLookUp(image,lookup);

  return result;
 }

 // Applies a lookup table transforming an input image into a 1-channel image
 cv::Mat applyLookUp(const cv::Mat& image, const cv::MatND& lookup) {

  // Set output image (always 1-channel)
  cv::Mat result(image.rows,image.cols,CV_8U);
  cv::Mat_<uchar>::iterator itr= result.begin<uchar>();

  // Iterates over the input image
  cv::Mat_<uchar>::const_iterator it= image.begin<uchar>();
  cv::Mat_<uchar>::const_iterator itend= image.end<uchar>();

  // Applies lookup to each pixel
  for ( ; it!= itend; ++it, ++itr) {

   *itr= lookup.at<uchar>(*it);
  }

  return result;
 }


};


#endif

 

 

Histograms.cpp

 

/*------------------------------------------------------------------------------------------*\
   This file contains material supporting chapter 4 of the cookbook: 
   Computer Vision Programming using the OpenCV Library.
   by Robert Laganiere, Packt Publishing, 2011.

   This program is free software; permission is hereby granted to use, copy, modify,
   and distribute this source code, or portions thereof, for any purpose, without fee,
   subject to the restriction that the copyright notice may not be removed
   or altered from any source or altered source distribution.
   The software is released on an as-is basis and without any warranties of any kind.
   In particular, the software is not guaranteed to be fault-tolerant or free from failure.
   The author disclaims all warranties with regard to this software, any use,
   and any consequent failure, is purely the responsibility of the user.
 
   Copyright (C) 2010-2011 Robert Laganiere, www.laganiere.name
\*------------------------------------------------------------------------------------------*/

#include <iostream>
using namespace std;

#include <opencv2\core\core.hpp>
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\imgproc\imgproc.hpp>
#include <opencv2\video\tracking.hpp>

#include "histogram.h"

int main()
{


         // Read input image
          cv::Mat image= cv::imread("C:/images/group.jpg", 0);
         if (!image.data)
          return 0;

    // Display the image
 cv::namedWindow("Image");
 cv::imshow("Image",image);

 // The histogram object
 Histogram1D h;

    // Compute the histogram
 cv::MatND histo= h.getHistogram(image);

 // Loop over each bin
 for (int i = 0; i < 256; i++)
  cout << "V[" << i << "]= " << histo.at<float>(i) << endl; 

 // Display a histogram as an image
 cv::namedWindow("Histogram");
 cv::imshow("Histogram", h.getHistogramImage(image));

 // creating a binary image by thresholding at the valley
 cv::Mat thresholded;
 cv::threshold(image, thresholded, 60, 255, cv::THRESH_BINARY);
 
 // Display the thresholded image
 cv::namedWindow("Binary Image");
 cv::imshow("Binary Image",thresholded);
 cv::imwrite("binary.bmp",thresholded);

 // Equalize the image
 cv::Mat eq= h.equalize(image);

 // Show the result
 cv::namedWindow("Equalized Image");
 cv::imshow("Equalized Image",eq);

 // Show the new histogram
 cv::namedWindow("Equalized Histogram");
 cv::imshow("Equalized Histogram",h.getHistogramImage(eq));

 // Stretch the image ignoring bins with less than 5 pixels
 cv::Mat str= h.stretch(image, 5);

 // Show the result
 cv::namedWindow("Stretched Image");
 cv::imshow("Stretched Image",str);

 // Show the new histogram
 cv::namedWindow("Stretched Histogram");
 cv::imshow("Stretched Histogram",h.getHistogramImage(str));
 
 // Create an image inversion table
 int dims[1] = {256};
 cv::MatND lookup(1, dims, CV_8U);

 // uchar lookup[256];
 
 for (int i=0; i<256; i++) {
  lookup.at<uchar>(i)= 255 - i;
  // lookup[i]= 255 - i;
 }

 // Apply lookup and display negative image
 cv::namedWindow("Negative image");
 cv::imshow("Negative image", h.applyLookUp(image, lookup));
 

 cv::waitKey();
 return 0;

}