每天一个小示例 opencv(1)颜色直方图的统计 calcHist_Demo.cpp

     (我也要坚持每天写写博客,虽然知道会很水,但是会一天天提高,加油)

        直方图统计是一个在视觉中用得比较多的手段,比如直接用颜色直方图进行图片分类,像shift,hog特征都是用到了这种直方图统计技术。

        这种方法的好处是可以将局部或整体的某些特征进行统计,从而可以表示某些特定的性质。

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include
#include

using namespace std;
using namespace cv;

/**
* @function main
*/
int main( int argc, char* argv[] )
{
Mat src, dst;
char *dirimg="E:/uselessvalse/111.jpg";
/// Load image
// src = imread( argv[1], 1 );
src = imread(dirimg);
if( !src.data )
{ return -1; }

/// Separate the image in 3 places ( B, G and R )
vector bgr_planes;
split( src, bgr_planes );//将图片分开,这里是分成了3个通道

/// Establish the number of bins
int histSize = 256;

/// Set the ranges ( for B,G,R) )
float range[] = { 0, 256 } ;//一个数组,包含两个数
const float* histRange = {range};//大括号

bool uniform = true; bool accumulate = false;

Mat b_hist, g_hist, r_hist;//执行完后面的calchist之后是一个histsize行,一列的矩阵。因为设计的维度是1.

/// Compute the histograms:
calcHist( &bgr_planes[0], 1, 0, Mat(), b_hist, 1, &histSize, &histRange, uniform, accumulate );
// 1. 源图片(可多张)--2.张数---- 3.第几通道---
//4.图中对应位置统计的次数----5.hist结果,6.hist维度,7.每个维度的hist的大小、8.hist范围,9,10
calcHist( &bgr_planes[1], 1, 0, Mat(), g_hist, 1, &histSize, &histRange, uniform, accumulate );
calcHist( &bgr_planes[2], 1, 0, Mat(), r_hist, 1, &histSize, &histRange, uniform, accumulate );
// Draw the histograms for B, G and R
int hist_w = 512; int hist_h = 400;
int bin_w = cvRound( (double) hist_w/histSize );

Mat histImage( hist_h, hist_w, CV_8UC3, Scalar( 0,0,0) );//建立一张空图片用来花hist图(0,0,0)表示黑色

/// Normalize the result to [ 0, histImage.rows ]
normalize(b_hist, b_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat() );
//范化(归一化): 1原数据 2归一化之后的数据 3 下值(在1,2,或inf时的归一值) 4上值(只有选norm_minmax时用) 5 范化的类型(inf、1、2、区间)
//这里是归一到一个区间

normalize(g_hist, g_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat() );
normalize(r_hist, r_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat() );

/// Draw for each channel 例题中是用一条曲线画出来,所以连接相邻两点就可以
for( int i = 1; i < histSize; i++ )
{
line( histImage, Point( bin_w*(i-1), hist_h - cvRound(b_hist.at(i-1)) ) ,
Point( bin_w*(i), hist_h - cvRound(b_hist.at(i)) ),
Scalar( 255, 0, 0), 2, 8, 0 );
line( histImage, Point( bin_w*(i-1), hist_h - cvRound(g_hist.at(i-1)) ) ,
Point( bin_w*(i), hist_h - cvRound(g_hist.at(i)) ),
Scalar( 0, 255, 0), 2, 8, 0 );
line( histImage, Point( bin_w*(i-1), hist_h - cvRound(r_hist.at(i-1)) ) ,
Point( bin_w*(i), hist_h - cvRound(r_hist.at(i)) ),
Scalar( 0, 0, 255), 2, 8, 0 );
}

/// Display
namedWindow("calcHist Demo", CV_WINDOW_AUTOSIZE );
imshow("calcHist Demo", histImage );

waitKey(0);

return 0;

}

转载于:https://www.cnblogs.com/yazifei/p/3861422.html

你可能感兴趣的:(人工智能)