#include "stdafx.h"
//本节讲述 图像处理之 直方图均衡化;
#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
using namespace std;
using namespace cv;
Mat src, dst, map_x, map_y, gray_src;
//const char*output_title = "canny双阈值处理";
char input_title[] = "原图";
int main(int argc, char**argv)
{
src = imread("C:/Users/Rubison.DELL/Desktop\\杂物/壁纸/小白2.jpg"); //存放自己图像的路径
if (!src.data)
{
printf("could not load image...\r\n");
return -1;
}
namedWindow(input_title, CV_WINDOW_AUTOSIZE);
imshow(input_title, src);
vector<Mat>bgr_planes; //定义一个数组
split(src,bgr_planes);
//imshow("分离的单通道",bgr_planes);
//设置范围
int histSize = 256;
float rang[] = {0,256};
const float *histRanges = { rang }; //定义一个指针
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 = 521;
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()); // 归一化到 [ 0, histImage.rows ]
normalize(g_hist, g_hist, 0, hist_h, NORM_MINMAX, -1, Mat()); //因为得出的频数可能超过直方图最大值
normalize(r_hist, r_hist, 0, hist_h, NORM_MINMAX, -1, Mat());
for (int i = 1; i < histSize; i++) //绘制直方图
{
line(histImage, Point(bin_w*(i - 1), hist_h - cvRound(b_hist.at<float>(i - 1))), //cvRound,函数的一种,对一个float型的数进行四舍五入。
Point(bin_w*(i), hist_h - cvRound(b_hist.at<float>(i))), //默认坐标系原点在左下角,其实坐标在左上角
Scalar(255, 0, 0), 2, 8, 0);
line(histImage, Point(bin_w*(i - 1), hist_h - cvRound(g_hist.at<float>(i - 1))),
Point(bin_w*(i), hist_h - cvRound(g_hist.at<float>(i))),
Scalar(0, 255, 0), 2, 8, 0);
line(histImage, Point(bin_w*(i - 1), hist_h - cvRound(r_hist.at<float>(i - 1))),
Point(bin_w*(i), hist_h - cvRound(r_hist.at<float>(i))),
Scalar(0, 0, 255), 2, 8, 0);
}
imshow("分离通道", histImage);
//imshow("二值化结果图", dst);
waitKey(0);
destroyAllWindows();
return 0;
}
运行结果:
备注:
1.程序中画线函数Line中,需要用图像高度减去得到的的频数,即
个人理解是图片的坐标系原点和我们认为的坐标系原点唯一,图片坐标系原点在图片左上角,因此要与高度相减。不减的图片如下:
2.关于显示calcHist中的输出显示可理解为(关于calHist计算直方图的结果hist,hist的结果为统计的灰度级0, 1,…,255的数量;表示一维或三维的矩阵;)