1. 绘制直方图

api不在做详细介绍,具体看以下代码例子

#include <iostream>
#include<opencv.hpp>
#include<opencv2\highgui\highgui.hpp>

using namespace std;
using namespace cv;

int main()
{

	Mat src = imread("src.jpg");
	if (src.empty())
	{
		cout << "could not open file!";
		cout << endl;
		return -1;
	}
	imshow("src", src);
	//分离
	vector<Mat>mv;
	split(src, mv);

	//1. 计算直方图
	int histSize = 256;
	Mat b_hist, g_hist, r_hist;
	float range[] = { 0,255 };
	const float* histRanges = { range };

	calcHist(&mv[0], 1, 0, Mat(), b_hist, 1, &histSize, &histRanges, true, false);
	calcHist(&mv[1], 1, 0, Mat(), g_hist, 1, &histSize, &histRanges, true, false);
	calcHist(&mv[2], 1, 0, Mat(), r_hist, 1, &histSize, &histRanges, true, false);

	Mat result = Mat::zeros(Size(600, 400), CV_8UC3);
	int margin = 50;
	int nm = result.rows - 2 * margin;
	normalize(b_hist, b_hist, 0, nm, NORM_MINMAX, -1, Mat());
	normalize(g_hist, g_hist, 0, nm, NORM_MINMAX, -1, Mat());
	normalize(r_hist, r_hist, 0, nm, NORM_MINMAX, -1, Mat());

	float step = 500.0 / 256.0;
	for (int i = 0; i < 255; i++)
	{
		line(result, Point(step * i, 50 + (nm - b_hist.at<float>(i, 0))), Point(step * (i + 1), 50 + (nm - b_hist.at<float>(i + 1, 0))), Scalar(255, 0, 0), 2, 8, 0);
		line(result, Point(step * i, 50 + (nm - g_hist.at<float>(i, 0))), Point(step * (i + 1), 50 + (nm - g_hist.at<float>(i + 1, 0))), Scalar(0, 255, 0), 2, 8, 0);
		line(result, Point(step * i, 50 + (nm - r_hist.at<float>(i, 0))), Point(step * (i + 1), 50 + (nm - r_hist.at<float>(i + 1, 0))), Scalar(0, 0, 255), 2, 8, 0);
	}
	imshow("hist-result", result);
	waitKey(0);
	destroyAllWindows();
	return 0;

}

2. 直方图均衡化

作用:它通过重新分布图像的像素值,使得图像的直方图在整个灰度范围内均匀分布。
好处:增加对比度,增加细节,在处理灰色图像的时候经常会用到这个方法来做图像增强
api很简单,下面是个例子。

#include <iostream>
#include<opencv.hpp>
#include<opencv2\highgui\highgui.hpp>

using namespace std;
using namespace cv;

int main()
{

	Mat src = imread("src.jpg");
	if (src.empty())
	{
		cout << "could not open file!";
		cout << endl;
		return -1;
	}
	imshow("src", src);
	Mat gray, dst;

	//转成灰度图
	cvtColor(src, gray, COLOR_BGR2GRAY);
	imshow("gray", gray);
	//均衡化
	equalizeHist(gray, dst);
	imshow("dst", dst);
	waitKey(0);
	destroyAllWindows();
	return 0;

}

结果:可以明显看到图片的细节变多了,图像对比度增加了。
opencv c++ (6):直方图-LMLPHP

02-03 06:46