zoukankan      html  css  js  c++  java
  • OpenCV 直方图计算

     1 #include "opencv2/highgui/highgui.hpp"
     2 #include "opencv2/imgproc/imgproc.hpp"
     3 #include <iostream>
     4 #include <stdio.h>
     5 
     6 using namespace std;
     7 using namespace cv;
     8 
     9 /** @函数 main */
    10 int main( int argc, char** argv )
    11 {
    12   Mat src, dst;
    13 
    14  /// 装载图像
    15  src = imread( argv[1], 1 );
    16 
    17  if( !src.data )
    18    { return -1; }
    19 
    20  /// 分割成3个单通道图像 ( R, G 和 B )
    21  vector<Mat> rgb_planes;
    22  split( src, rgb_planes );
    23 
    24  /// 设定bin数目
    25  int histSize = 255;
    26 
    27  /// 设定取值范围 ( R,G,B) )
    28  float range[] = { 0, 255 } ;
    29  const float* histRange = { range };
    30 
    31  bool uniform = true; bool accumulate = false;
    32 
    33  Mat r_hist, g_hist, b_hist;
    34 
    35  /// 计算直方图:
    36  calcHist( &rgb_planes[0], 1, 0, Mat(), r_hist, 1, &histSize, &histRange, uniform, accumulate );
    37  calcHist( &rgb_planes[1], 1, 0, Mat(), g_hist, 1, &histSize, &histRange, uniform, accumulate );
    38  calcHist( &rgb_planes[2], 1, 0, Mat(), b_hist, 1, &histSize, &histRange, uniform, accumulate );
    39 
    40  // 创建直方图画布
    41  int hist_w = 400; int hist_h = 400;
    42  int bin_w = cvRound( (double) hist_w/histSize );
    43 
    44  Mat histImage( hist_w, hist_h, CV_8UC3, Scalar( 0,0,0) );
    45 
    46  /// 将直方图归一化到范围 [ 0, histImage.rows ]
    47  normalize(r_hist, r_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat() );
    48  normalize(g_hist, g_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat() );
    49  normalize(b_hist, b_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat() );
    50 
    51  /// 在直方图画布上画出直方图
    52  for( int i = 1; i < histSize; i++ )
    53    {
    54      line( histImage, Point( bin_w*(i-1), hist_h - cvRound(r_hist.at<float>(i-1)) ) ,
    55                       Point( bin_w*(i), hist_h - cvRound(r_hist.at<float>(i)) ),
    56                       Scalar( 0, 0, 255), 2, 8, 0  );
    57      line( histImage, Point( bin_w*(i-1), hist_h - cvRound(g_hist.at<float>(i-1)) ) ,
    58                       Point( bin_w*(i), hist_h - cvRound(g_hist.at<float>(i)) ),
    59                       Scalar( 0, 255, 0), 2, 8, 0  );
    60      line( histImage, Point( bin_w*(i-1), hist_h - cvRound(b_hist.at<float>(i-1)) ) ,
    61                       Point( bin_w*(i), hist_h - cvRound(b_hist.at<float>(i)) ),
    62                       Scalar( 255, 0, 0), 2, 8, 0  );
    63     }
    64 
    65  /// 显示直方图
    66  namedWindow("calcHist Demo", CV_WINDOW_AUTOSIZE );
    67  imshow("calcHist Demo", histImage );
    68 
    69  waitKey(0);
    70 
    71  return 0;
    72 
    73 }
  • 相关阅读:
    一道比较有趣的题
    笑话两则
    时钟
    组策略 简单介绍
    网页乱码问题ASP.NET
    同性恋的公鸡
    SQL中CASE函数_可解决编程中空表检索的一些问题
    百万网?
    黑客 故事
    word有趣问题集锦
  • 原文地址:https://www.cnblogs.com/ybqjymy/p/12170946.html
Copyright © 2011-2022 走看看