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;

}

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

相关推荐
阿闽ooo5 分钟前
外观模式:从家庭电源控制看“简化接口“的设计智慧
c++·设计模式·外观模式
你的冰西瓜1 小时前
C++中的list容器详解
开发语言·c++·stl·list
懷淰メ3 小时前
python3GUI--基于YOLOv8深度学习的车牌识别系统(详细图文介绍)
深度学习·opencv·yolo·pyqt·图像识别·车牌识别·pyqt5
小鸡吃米…4 小时前
带Python的人工智能——计算机视觉
人工智能·python·计算机视觉
CC.GG4 小时前
【C++】哈希表的实现
java·c++·散列表
bkspiderx5 小时前
C++变量生命周期:从创建到销毁的完整旅程
c++·生命周期·作用域·变量生命周期
T0uken6 小时前
现代 C++ 项目的 CMake 工程组织
c++
H CHY7 小时前
C++代码
c语言·开发语言·数据结构·c++·算法·青少年编程
xiaolang_8616_wjl7 小时前
c++题目_传桶(改编于atcoder(题目:Heavy Buckets))
数据结构·c++·算法
小小8程序员7 小时前
除了 gcc/g++,还有哪些常用的 C/C++ 编译器?
c语言·开发语言·c++