#include "stdafx.h"
#include "highgui.hpp"
#include "cv.hpp"
#include "iostream"
using namespace cv;
using namespace std;
int main() {
//读取图像,并显示图像
Mat img = imread("H:\\3.jpg",CV_LOAD_IMAGE_GRAYSCALE);
if (img.empty())
cout << "Load image error" << endl;
imshow("raw image",img);
//初始化直方图参数
int size = 256; //直方图中bin的数量
float range[] = {0,255};const float* ranges[] = { range }; //每个bin的取值范围
//创建直方图
MatND hist;
const int channels = 0 ;
//计算灰度图的直方图
calcHist(&img,1,&channels,Mat(), hist,1, &size,ranges,true,false);
//归一化直方图
normalize(hist,hist, 1.0,0);
//创建一张一维直方图的图(width:256,height:128)
Mat hist_mat = Mat::zeros(Size(256,128), CV_8UC1);
//获取直方图中的最大直方块
double max_value = 0;
minMaxLoc(hist, 0, &max_value, 0, 0);
//将每个直方块的值绘制到图中
for (int i = 0; i < size; i++)
{
float bin_value = hist.at<float>(i); //像素i的概率
int intensity = cvRound(bin_value * 256 / max_value);//要绘制的高度
rectangle(hist_mat,
Point(i, 128),
Point((i + 1) , ( 128 - intensity)),
Scalar(255),
FILLED);
}
imshow("hist", hist_mat);
waitKey(0);
return(0);
}
#include "highgui.hpp"
#include "cv.hpp"
#include "iostream"
using namespace cv;
using namespace std;
int main() {
//读取图像,并显示图像
Mat img = imread("H:\\3.jpg",CV_LOAD_IMAGE_GRAYSCALE);
if (img.empty())
cout << "Load image error" << endl;
imshow("raw image",img);
//初始化直方图参数
int size = 256; //直方图中bin的数量
float range[] = {0,255};const float* ranges[] = { range }; //每个bin的取值范围
//创建直方图
MatND hist;
const int channels = 0 ;
//计算灰度图的直方图
calcHist(&img,1,&channels,Mat(), hist,1, &size,ranges,true,false);
//归一化直方图
normalize(hist,hist, 1.0,0);
//创建一张一维直方图的图(width:256,height:128)
Mat hist_mat = Mat::zeros(Size(256,128), CV_8UC1);
//获取直方图中的最大直方块
double max_value = 0;
minMaxLoc(hist, 0, &max_value, 0, 0);
//将每个直方块的值绘制到图中
for (int i = 0; i < size; i++)
{
float bin_value = hist.at<float>(i); //像素i的概率
int intensity = cvRound(bin_value * 256 / max_value);//要绘制的高度
rectangle(hist_mat,
Point(i, 128),
Point((i + 1) , ( 128 - intensity)),
Scalar(255),
FILLED);
}
imshow("hist", hist_mat);
waitKey(0);
return(0);
}