OpenCV2 cookbook source code analyse - histogram

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;

}

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值