赞
踩
现在我也是一枚苦逼的研究生啦,然后现在的研究方向是图像增强,这篇博客算是我研究生写博客生涯的开篇吧。
网上有很多关于平台直方图均衡化的,我就不再赘述了,直接放代码:
#include<opencv2/opencv.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
#include<iostream>
using namespace std;
using namespace cv;
int main(){
//视频读取
VideoCapture cap;
cap.open("0.avi");
while(1)
{
Mat frame; //定义Mat变量,用来存储每一帧
cap>>frame; //读取当前帧
imshow("frame",frame);
Mat dest;
//平台直方均衡化
MatND hist;
const int histSize = 256;
float range[] = { 0, 255 };
const float *ranges[] = { range };
const int channels = 0;
cv::calcHist(&frame, 1, &channels, Mat(), hist, 1, &histSize, ranges);//计算图像直方图,hist为计算出来的直方图
float total = frame.size().width*frame.size().height;
float bins[histSize] = { 0 };
float binsAcc[histSize] = { 0 };
Mat lut(1, 256, CV_8U);
vector<float> vectorBins;
vector<float> maxBins;
float sumBins = 0.0;
int countMax = 0;
float TValue = 0;
// Find the mapping table
for (int i = 0; i<histSize; i++)
{
float bin_val = hist.at<float>(i); // 第i灰度级上的数
bins[i] = bin_val / total;
if (bins[i] > 0)
{
vectorBins.push_back(bins[i]);
}
}
// Calculate the Meadin value by 3 sapce
for (int i = 1; i < vectorBins.size() - 1; i++)
{
if (vectorBins[i] < vectorBins[i - 1] && vectorBins[i - 1] < vectorBins[i + 1] || vectorBins[i] > vectorBins[i - 1] && vectorBins[i - 1] > vectorBins[i + 1])
{
vectorBins[i] = vectorBins[i - 1];
}
else if (vectorBins[i] < vectorBins[i + 1] && vectorBins[i + 1] < vectorBins[i - 1] || vectorBins[i] > vectorBins[i + 1] && vectorBins[i + 1] > vectorBins[i - 1])
{
vectorBins[i] = vectorBins[i + 1];
}
}
// Calculate the max peak value
for (int i = 1; i < vectorBins.size() - 1; i++)
{
if (vectorBins[i] - vectorBins[i - 1] >= 0 && vectorBins[i + 1] - vectorBins[i] <= 0)
{
maxBins.push_back(vectorBins[i]);
sumBins += vectorBins[i];
countMax++;
}
}
TValue = sumBins / countMax;
//TValue = L.rows* L.cols*0.002;
// Find the mapping table
for (int i = 0; i<histSize; i++)
{
if (bins[i] > TValue)
{
bins[i] = TValue;
}
if (i>=1)
{
binsAcc[i] = binsAcc[i-1] + bins[i];//图像累积直方图
}
else
{
binsAcc[0] = bins[0];
}
}
for (int i = 0; i < histSize; i++)
{
lut.at<uchar>(i) = static_cast<uchar>(cvFloor(binsAcc[i] * 255 / (binsAcc[255])));
}
LUT(frame, lut, dest);//查找表,根据直方图生成新的图像
imshow("dset", dest);
if(waitKey(30)>=0) break; //延时30ms
}
//waitKey(0);
return 0;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。