直方图处理
直方图
直方图是图像像素灰度级的统计数目的直观表示。本文将从像素级操作完成直方图显示、直方图均衡、直方图规定(匹配)、直方图局部均衡以及直方图统计测试实验。
直方图显示
对于直方图的计算,我们需要统计各个灰度级上像素的数目,然后根据此关系勾画出直方图。直方图能够直观的显示图像像素在各个灰度级的分布,是其余实验的基础。
参考代码
#include<iostream>
#include<string>
#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/opencv.hpp>
using namespace cv;
using namespace std;
void test1();
double* computeHist(Mat src);
void showHist(double* rank, string name);
double findNumber(double* num, int start, int end, int n);
void test2();
Mat myBalanceHist(Mat &src);
double* standHist(double* rank);
double* balanceHist(double* rank);
Mat mapping(Mat &src, double* rank);
void test3();
void standardImageSingleArray(Mat &src, double* num, int rank);
void gama_image(Mat &img, double gama, double rate);
Mat myMatchHist(Mat &src, double* dstHist);
void test4();
Mat myLocalBalance(Mat &src, int size);
void test5();
Mat statisticHist(Mat &src, double rate, double muk0, double sigmak1, double sigmak2, bool dark, int size);
Mat countMV(double* num, int nums);
int main()
{
test1();
test2();
test3();
test4();
test5();
return 0;
}
// 测试一
void test1()
{
// 读取灰度图像
Mat img = imread("D:/lena.jpg", 0);
// 显示直方图
double* rank = computeHist(img);
showHist(rank, "原图直方图");
imshow("原图", img);
waitKey(0);
destroyAllWindows();
}
// 计算直方图
double* computeHist(Mat src)
{
double* rank = new double[256];
// 初始化
for (int n = 0; n < 256; n++)
rank[n] = 0;
// 计算灰度分布
for (int i = 0; i < src.rows; i++)
for (int j = 0; j < src.cols; j++)
{
rank[src.at<uchar>(i, j)]++;
}
return rank;
}
// 显示直方图
void showHist(double* rank, string name)
{
Mat hist = Mat::zeros(255, 255, CV_8UC1);
// 深拷贝
double* rankCopy = new double[256];
for (int n = 0; n < 256; n++)
rankCopy[n] = rank[n];
double min = findNumber(rankCopy, 0, 256, 0);
double max = findNumber(rankCopy, 0, 256, 255);
for (int i = 0; i < 256; i++)
{
line(hist, Point(i, 255), Point(i, saturate_cast<int>(255 - (rank[i] - min) * 255 / (max - min))), Scalar(255));
}
imshow(name, hist);
}
// 寻找序列值
double findNumber(double* num, int start, int end, int n)
{
int p = start;
double stand = num[start];
for (int i = start + 1; i < end; i++)
{
if (num[i] < stand)
{
num[p] = num[i];
p++;
num[i] = num[p];
}
}
if (p == n)
return stand;
else if (p > n)
return findNumber(num, start, p, n);
else
return findNumber(num, p