直方图均衡化试图活得具有均匀分布值的直方图。
均衡的结果是图像对比度的增强。均衡能使对比度较低的局部区域获得高对比度,从而分散最频繁的强度。当图像非常暗或者非常亮,并且背景和前景之间存在非常小的差异时,此方法非常有效。通过使用直方图均衡化,可以增加对比度,并提升暴露过度或暴露不足的细节,该技术在医学图像(eg.X射线)中非常有用。
然而,这种方法也有两个缺点:背景噪声的增强以及随之而来的有用信息的减少,同时在增加图像对比度时,直方图会发生变化和扩散。
相关算法的实现如下,详情请看注释~
#include
#include
using namespace std;
using namespace cv;
//显示直方图
void showHist(Mat &img,Mat &dst)
{
//1、创建3个矩阵来处理每个通道输入图像通道。
//我们用向量类型变量来存储每个通道,并用split函数将输入图像划分成3个通道。
vector<Mat>bgr;
split(img, bgr);
//2、定义直方图的区间数
int numbers = 256;
//3、定义变量范围并创建3个矩阵来存储每个直方图
float range[] = {
0,256 };
const float* histRange = {
range };
Mat b_hist, g_hist, r_hist;
//4、使用calcHist函数计算直方图
int numbins = 256;
calcHist(&bgr[0], 1, 0, Mat(), b_hist, 1, &numbins, &histRange);
calcHist(&bgr[1], 1, 0, Mat(), g_hist, 1, &numbins, &histRange);
calcHist(&bgr[2], 1, 0, Mat(), r_hist, 1, &numbins, &histRange);
//5、创建一个512*300像素大小的彩色图像,用于绘制显示
int width = 512;
int height = 300;
Mat histImage(height, width, CV_8UC3, Scalar(20, 20, 20));
//6、将最小值与最大值标准化直方图矩阵
normalize(b_hist, b_hist, 0, height, NORM_MINMAX);
normalize(g_hist, g_hist, 0, height, NORM_MINMAX);
normalize(r_hist, r_hist, 0, height, NORM_MINMAX);
//7、使用彩色通道绘制直方图
int binStep = cvRound((float)width / (float)numbins); //通过将宽度除以区间数来计算binStep变量
for (int i = 1; i < numbins; i++)
{
line(histImage,
Point(binStep * (i - 1), height - cvRound(b_hist.at<float>(i - 1))),
Point(binStep * (i), height - cvRound(b_hist.at<float>(i))),
Scalar(255, 0, 0)
);
line(histImage,
Point(binStep * (i - 1), height - cvRound(g_hist.at<float>(i - 1))),
Point(binStep * (i), height - cvRound(g_hist.at<float>(i))),
Scalar(0, 255, 0)
);
line(histImage,
Point(binStep * (i - 1), height - cvRound(r_hist.at<float>(i - 1))),
Point(binStep * (i), height - cvRound(r_hist.at<float>(i))),
Scalar(0, 0, 255)
);
}
dst = histImage;
return;
}
//直方图均衡化
void hist_equalization(Mat &img,Mat &dst)
{
//1、使用cvtColor函数将BGR图像转至YCrCb
Mat result, ycrcb;
cvtColor(img, ycrcb, COLOR_BGR2YCrCb);
//2、将YCrCb图像拆分为不同的通道矩阵
vector<Mat> channels;
split(ycrcb, channels);
//3、使用equalizeHist函数均衡在Y通道中的直方图
equalizeHist(channels[0], channels[0]);
//4、合并生成的通道,并将其转换为BGR格式
merge(channels, ycrcb);
cvtColor(ycrcb, result, COLOR_YCrCb2BGR);
dst = result;
return;
}
int main()
{
Mat src = imread("test.jpg");
Mat histImage;
namedWindow("src", 0);
if (!src.data)
{
cout << "No src data!" << endl;
}
else
{
imshow("src", src);
}
showHist(src,histImage);
imshow("src_histImage", histImage);
imwrite("src_histImage.jpg", histImage);
Mat equalization;
hist_equalization(src, equalization);
namedWindow("equalization", 0);
imshow("equalization", equalization);
imwrite("equalization.jpg", equalization);
Mat hist_equal;
showHist(equalization, hist_equal);
imshow("hist_equal", hist_equal);
imwrite("hist_equal.jpg", hist_equal);
waitKey(0);
return 0;
}