一个图像是由不同颜色值的像素组成的,像素值的分布是图像的重要特征,通过直方图可以描述图像的内容,检测特定对象和纹理,也可以修改图像的外观。
直方图是一个简单的表,它给出了一幅图像或一组图像中拥有给定数值的像素数量。灰度图像的直方图有256个条目(容器)。0号容器是值为0的像素个数。直方图也可以归一化,每一项则表示所占的比例。
#include "stdafx.h"
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
class Histogram
{
private:
int histSize[1];//number of bins
float hranges[2];//min and max pixel value
const float* ranges[1];
int channels[1];//only 1 channel used here
public:
Histogram()
{
//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
}
cv::MatND getHistogram(const cv::Mat &image)
{
cv::MatND hist;
//Compute histogram
cv::calcHist(&image,
1,
channels,
cv::Mat(),
hist,
1,
histSize,
ranges
);
return hist;
}
//Compute 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);
//Image on which to display histogram
cv::Mat histImg(histSize[0],histSize[0],CV_8U,cv::Scalar(255));
//set highest point at 90% of nbins
int hpt = static_cast<int>(0.9*histSize[0]);
//Draw a 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);
//This function draw a line between 2 points
cv::line(histImg,cv::Point(h,histSize[0]),
cv::Point(h,histSize[0] - intensity),
cv::Scalar::all(0));
}
return histImg;
}
};
int main()
{
//Read input image
cv::Mat image = cv::imread("imL.png",0);
//the histogram object
Histogram h;
cv::namedWindow("Histogram");
cv::imshow("Histogram",h.getHistogramImage(image));
cv::waitKey(0);
return 0;
}
效果:
扩展(附上三通道直方图,返回的是3x256的Mat值)
class Histogram
{
private:
int histSize[3];
float hranges[2];
const float* ranges[3];
int channels[3];
public:
Histogram()
{
histSize[0] = 256;histSize[1] = 256;histSize[2] = 256;
hranges[0] = 0.0;
hranges[1] = 255.0;
ranges[0] = hranges;ranges[1] =hranges;
ranges[2] =hranges;
channels[0] = 0;channels[1] = 1;channels[2] = 2;
}
cv::MatND getHistogram(const cv::Mat &image)
{
cv::MatND hist;
cv::calcHist(&image,
1,
channels,
cv::Mat(),
hist,
3,
histSize,
ranges
);
return hist;
}
};