首页 > 学院 > 开发设计 > 正文

opencv 学习之直方图统计

2019-11-08 20:23:46
字体:
来源:转载
供稿:网友

直方图统计使用的函数是

void calcHist( const Mat* images, int nimages,                          const int* channels, InputArray mask,                          OutputArray hist, int dims, const int* histSize,                          const float** ranges, bool uniform=true, bool accumulate=false );1.images是输入图片,

2.nimages是输入图片数目

3.channels:统计的通道,例如{0}或者{0,1,2}

3.mask:掩码

4.hist:统计输出结果

5.dims:维数

6.histSize:每一维的直方图的尺寸大小

7.ranges:直方图每一维的数据大小范围。例如:{{0,2555}}(统计1个通道),{{0,2555},{0,2555},{0,2555}}(统计3个通道)

8.最后的参数默认为true,false。我的源代码:
#include <cv.h>#include <opencv2/core/core.hpp>  #include <opencv2/imgPRoc/imgproc.hpp>  #include <opencv2/highgui/highgui.hpp> using namespace std;using namespace cv;void mycalhist(Mat image){	MatND hist;	int bins = 256;        	int hist_size[] = {bins};        	float range[] = { 0, 256 };        	const float* ranges[] = { range};      	int channels[] = {0};    	calcHist(&image, 1, channels, Mat(), // do not use mask            hist, 1, hist_size, ranges,            true, // the histogram is uniform            false);		//计算出出现的频率	int sum=image.cols*image.rows;	float p[256];	for(int i=0;i<256;i++){		p[i]=hist.at<float>(i)/(1.0*sum);		//cout<<p[i]<<" ";		}	double max_val;  //直方图的最大值 	minMaxLoc(hist, 0, &max_val, 0, 0); //计算直方图最大值	//画出直方图	int maxheight=256;	Mat image2=Mat::zeros(256,2*256, CV_8UC3);	for(int i=0;i<256;i++){		//		计算高度		double height=(maxheight*hist.at<float>(i))/(1.0*max_val);		//画出对应的高度图		//坐标体系中的零点坐标定义为图片的左上角,X轴为图像矩形的上面那条水平线,从左往右;Y轴为图像矩形左边的那条垂直线,从上往下。在Point(x,y)和Rect(x,y)中,第一个参数x代表的是元素所在图像的列数,第二个参数y代表的是元素所在图像的行数,而在at(x,y)中是相反的。		rectangle(image2,Point(i*2,255),                	Point((i+1)*2 - 1, 255-height),                	CV_RGB(255,255,255));		}	imshow("hist",image2);		//cout<<endl;}int main( int argc, char** argv ){	Mat image=imread("./1.jpg",CV_LOAD_IMAGE_GRAYSCALE);	mycalhist(image);	waitKey(0); 	return 0;}

原图像:

统计结果:


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表