间断式更新一些无用的知识…
直方图处理一直是传统图像处理中最重要的技术手段之一,直方图处理包括经典的直方图均衡化、直方图规定化、直方图比较、局部直方图的均衡等等。本章主要介绍直方图均衡,后续不断更新剩下的图像处理技术。
直方图均衡化的作用:通过使均衡化后的图像的灰度级覆盖更宽的灰度范围,从而实现对源图像对比度的增强。
直方图均衡化特点:整个实现过程直接从给定的图像中提取信息,而不需要规定任何参数,自适应程度高。
结合OpenCV,直方图均衡C/C++实现代码如下:
int main()
{
string path = "F:\\Speedlimit\\RGBCutImages1\\21.jpg";
Mat SrcImage = imread(path);
if (!SrcImage.data) {
std::cout << "Could not open or find the image" << std::endl;
return -1;
}
cvtColor(SrcImage, SrcImage, COLOR_BGR2GRAY);
Mat dstImage = cv::Mat::zeros(SrcImage.size(), SrcImage.type());
int height = SrcImage.rows;
int width = SrcImage.cols;
//直方图参数定义
cv::Mat gray_hist, ShowImage; //grag_hist类型自动为float32
const int histSize = 256;
float range[] = {
0, 256 };
const float* histRange[] = {
range };
bool uniform = true, accumulate = false;
calcHist(&SrcImage, 1, 0, Mat(), gray_hist, 1, &histSize, histRange, uniform, accumulate);
Show_Hist(gray_hist, ShowImage);
//获得归一化图像直方图
cv::Mat norm_gray_hist = cv::Mat::zeros(gray_hist.size(), gray_hist.type());
for (int i = 0; i < histSize; ++i)
{
norm_gray_hist.at<float>(i) = gray_hist.at<float>(i) / SrcImage.total();
}
//遍历源图像中的每一个点,进行r_k-->s_k的映射
for (int i = 0; i < height; ++i)
{
for (int j = 0; j < width; ++j)
{
double sum_Fx = 0;
//计算图像中小于当前点灰度值的概率
for (int k = 0; k <= SrcImage.at<uchar>(i, j); ++k)
sum_Fx += norm_gray_hist.at<float>(k);
dstImage.at<uchar>(i, j) = cvRound(255 * sum_Fx);
}
}
cv::Mat dst_gray_hist, dst_ShowImage; //float32
calcHist(&dstImage, 1, 0, Mat(), dst_gray_hist, 1, &histSize, histRange, uniform, accumulate);
Show_Hist(dst_gray_hist, dst_ShowImage);
imshow("src", SrcImage);
imshow("dst", dstImage);
cv::waitKey(0);
return 0;
}
Show_Hist()函数用于显示灰度图像的直方图
void Show_Hist(const cv::Mat& HistImage, cv::Mat& ShowHistImage)
{
cv::Mat maker = HistImage.clone();
int histSize = MAX(maker.rows, maker.cols);
int hist_w = 512, hist_h = 400;
int bin_w = cvRound((double)hist_w / histSize);
ShowHistImage = cv::Mat(hist_h, hist_w, CV_8UC3, Scalar(0, 0, 0));
for (int i = 1; i < histSize; i++)
{
line(ShowHistImage, Point(bin_w * (i - 1), hist_h - cvRound(maker.at<float>(i - 1))),
Point(bin_w * (i), hist_h - cvRound(maker.at<float>(i))),
Scalar(255, 0, 0), 2, 8, 0);
}
}
参考资料:直方图计算
新手菜鸟,如有错误欢迎指正!