一般而言,圖片有RGB三通道,每個通道用一個byte表示,取值範圍在0到255之間。對於每個通道,我們都可以計算映像的長條圖,其實就是統計每個像素值的出現頻率,如所示:
長條圖均衡化的效果,即把原圖的三通道的長條圖變成均勻分布,每種像素值出現的次數都差不多,下面是長條圖均衡化後的效果(長條圖是用光影查看的,產生的程式碼見後):
可以看到,圖片的長條圖很均勻。
長條圖均衡化的代碼:
bool GFImage::HistogramEqualization(){vector<vector<uchar> > pixMaps;CalculateMapFunByHisEq(pixMaps);for (int ch = 0; ch < GetChannel(); ch++){uchar * pData = GetData();for (int r = 0;r < GetHeight(); r++){uchar * pLine = pData + r * GetWidthStep();for (int c = 0; c < GetWidth(); c++){uchar val = pLine[GetChannel() * c + ch];pLine[GetChannel() * c + ch] = pixMaps[ch][val];}}}return true;}
bool GFImage::CalculateMapFunByHisEq(vector<vector<uchar> >& vMappings) const{vMappings.resize(GetChannel());for (int i = 0; i < vMappings.size(); i++){vMappings[i].resize(256);}vector<GFHistogram> vHistograms;vHistograms.resize(GetChannel());for (int i = 0;i < GetChannel(); i++){vHistograms[i].Calculate(*this, 256, i);}double tmp;for (int ch = 0; ch < GetChannel(); ch++){tmp = vHistograms[ch].GetFrequencyAt(0) * 255;vMappings[ch][0] = (uchar)tmp;for (int j = 1;j < 256; j++){tmp = tmp + vHistograms[ch].GetFrequencyAt(j) * 255;vMappings[ch][j] = (uchar)tmp;}}return true;}
調用時
string strImagePath = "lena.jpg";GFImage image1(strImagePath);image1.ShowImage("ori");image1.HistogramEqualization();image1.ShowImage("res");cv::waitKey();
其中GFImage封裝了opencv的映像類,GFHistogram是自訂的長條圖類。詳細代碼可參考這裡