直方图与直方图均衡化
均衡化会提高对比度。
均衡化函数:
直方图的计算
#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
using namespace cv;
using namespace std;
int main(int argc, char** argv) {
Mat src, dst;
src = imread("E://VS-pro//images//zhu.jpg");
if (!src.data) {
printf("could not load image...\n");
return -1;
}
imshow("input", src);
//多通道图
//分通道显示
vector<Mat> bgr_planes;//放BGR三个通道图像
split(src, bgr_planes);
//计算直方图
int histSize = 256; //总数
float range[] = { 0, 256 }; //范围
const float *histRanges = { range };
Mat b_hist, g_hist, r_hist;
calcHist(&bgr_planes[0], 1, 0, Mat(), b_hist, 1, &histSize, &histRanges, true, false);
calcHist(&bgr_planes[1], 1, 0, Mat(), g_hist, 1, &histSize, &histRanges, true, false);
calcHist(&bgr_planes[2], 1, 0, Mat(), r_hist, 1, &histSize, &histRanges, true, false);
//归一化
int hist_h = 400;
int hist_w = 512; //总宽度
int bin_w = hist_w / histSize; //每一份区间的宽度
Mat histImage(hist_w, hist_h, CV_8UC3, Scalar(0, 0, 0));
normalize(b_hist, b_hist, 0, hist_h, NORM_MINMAX, -1, Mat());
normalize(g_hist, g_hist, 0, hist_h, NORM_MINMAX, -1, Mat());
normalize(r_hist, r_hist, 0, hist_h, NORM_MINMAX, -1, Mat());
//绘制直方图render histogram chart
for (int i = 1; i < histSize; i++) {
//起点 x = 上一份区间的x坐标 y等于上一份区间的y坐标
//终点 x = 本份区间的x坐标 y等于本份区间的y坐标
//B cvRound():返回跟参数最接近的整数值,即四舍五入;
line(histImage, Point((i - 1)*bin_w, hist_h - cvRound(b_hist.at<float>(i - 1))),
Point((i)*bin_w, hist_h - cvRound(b_hist.at<float>(i))), Scalar(255, 0, 0), 2, LINE_AA);
//G
line(histImage, Point((i - 1)*bin_w, hist_h - cvRound(g_hist.at<float>(i - 1))),
Point((i)*bin_w, hist_h - cvRound(g_hist.at<float>(i))), Scalar(0, 255, 0), 2, LINE_AA);
//R
line(histImage, Point((i - 1)*bin_w, hist_h - cvRound(r_hist.at<float>(i - 1))),
Point((i)*bin_w, hist_h - cvRound(r_hist.at<float>(i))), Scalar(0, 0, 255), 2, LINE_AA);
}
imshow("直方图", histImage);
waitKey(0);
return 0;
}