opencv c++ (6):直方图

1. 绘制直方图

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

cpp 复制代码
#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很简单,下面是个例子。

cpp 复制代码
#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;

}

结果:可以明显看到图片的细节变多了,图像对比度增加了。

相关推荐
qq_192779874 小时前
C++模块化编程指南
开发语言·c++·算法
代码村新手4 小时前
C++-String
开发语言·c++
管牛牛5 小时前
图像的卷积操作
人工智能·深度学习·计算机视觉
历程里程碑6 小时前
滑动窗口---- 无重复字符的最长子串
java·数据结构·c++·python·算法·leetcode·django
roman_日积跬步-终至千里6 小时前
【计算机视觉-作业1】从图像到向量:kNN数据预处理完整流程
人工智能·计算机视觉
2501_940315267 小时前
航电oj:首字母变大写
开发语言·c++·算法
lhxcc_fly7 小时前
手撕简易版的智能指针
c++·智能指针实现
浒畔居7 小时前
泛型编程与STL设计思想
开发语言·c++·算法
Fcy6488 小时前
C++ 异常详解
开发语言·c++·异常
机器视觉知识推荐、就业指导8 小时前
Qt 和 C++,是不是应该叫 Q++ 了?
开发语言·c++·qt