Ai
1 Star 0 Fork 0

BreezeKevin/opencv

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
contrast_enhance.cpp 2.78 KB
一键复制 编辑 原始数据 按行查看 历史
BreezeKevin 提交于 2020-11-22 00:12 +08:00 . 首次添加
#include"contrast_enhance.h"
Mat CalcGrayHist(const Mat& image) {
//存储256个灰度级的像素
Mat hist_gram = Mat::zeros(Size(256, 1), CV_32SC1);
//获取图像的行高和列宽
int rows = image.rows;
int cols = image.cols;
//计算每个灰度级的个数
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < cols; c++)
{
int index = int(image.at<uchar>(r, c));
hist_gram.at<int>(0, index) += 1;
}
}
return hist_gram;
}
Mat LinearTransform(const Mat& image, int rtype, double a, double b) {
Mat Out;
image.convertTo(Out, rtype, a, b);
return Out;
}
Mat HistgramNormalization(Mat gray_image)
{
//获取输入矩阵的最大值和最小值
double Imax, Imin;
minMaxLoc(gray_image, &Imin, &Imax, NULL, NULL);
// 定义输出矩阵的最大值和最小值
double Omin = 0, Omax = 255;
// 确定映射关系函数中的系数,其实就是确定线性变换中的系数a和b
double a = (Omax - Omin) / (Imax - Imin);
double b = Omin - a * Imin;
Mat Out;//输出矩阵
convertScaleAbs(gray_image, Out, a, b);//进行线性变换
return Out;
}
Mat GammaTransform(Mat gray_image, double gamma)
{
//1.归一化
Mat fI;
gray_image.convertTo(fI, CV_64F, 1 / 255, 0);
//2.伽马变换,其实就是幂运算,gamma的区间为(0,1)
Mat Out;
pow(fI, gamma, Out);
//3.再次进行线性变换,转换为0,255之间的像素值
Out.convertTo(Out, CV_8U, 255, 0);
return Out;
}
Mat equalHist(Mat image)
{
//检查图像数据类型是否符合要求,如不符合,则抛出异常
// CV_Assert的官方简要说明如下
// Checks a condition at runtime and throws exception if it fails
CV_Assert(image.type() == CV_8UC1);
// 灰度图像的宽和高
int rows = image.rows;
int cols = image.cols;
//第一步:计算图像的灰度直方图
Mat gray_hist = CalcGrayHist(image);
//第二步:计算累加灰度直方图
Mat zero_comu_moment = Mat::zeros(Size(256, 1), CV_32SC1); //生成一行256列的零矩阵
for (int p = 0; p < 256; p++)
{
if (p==0)
{
zero_comu_moment.at<int>(0, p) = gray_hist.at<int>(0, 0);
}
else
{
zero_comu_moment.at<int>(0, p) = zero_comu_moment.at<int>(0, p - 1) + gray_hist.at<int>(0, p);
}
}
//第三步:根据累加直方图得到输入灰度级和输出灰度级直方图的映射关系
Mat output_q = Mat::zeros(Size(256, 1), CV_8UC1);
float cofficient = 256.0 / (rows * cols);
for (int p = 0; p < 256; p++)
{
float q = cofficient * zero_comu_moment.at<int>(0, p) - 1;
if (q>=0)
{
output_q.at<uchar>(0, p) = uchar(floor(q));
}
else
{
output_q.at<uchar>(0, p) = 0;
}
}
//第四步:得到直方图均衡化后的图像
Mat equal_hist_image = Mat::zeros(image.size(), CV_8UC1);
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < cols; c++)
{
int p = image.at<uchar>(r, c);
//根据原像素值p获得新的像素值q重新赋值给对应位置
equal_hist_image.at<uchar>(r, c) = output_q.at<uchar>(0, p);
}
}
return equal_hist_image;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/breezekevin/Cplusplus.git
git@gitee.com:breezekevin/Cplusplus.git
breezekevin
Cplusplus
opencv
master

搜索帮助