Gamma校正(C++、OpenCV實現)
1.作用:
Gamma校正是對輸入圖像灰度值進行的非線性操作,使輸出圖像灰度值與輸入圖像灰度值呈指數關系:
伽瑪校正由以下冪律表達式定義:
2.函數原型
1 void calcHist( const Mat* images, int nimages, 2 const int* channels, InputArray mask, 3 OutputArray hist, int dims, const int* histSize, 4 const float** ranges, bool uniform=true, bool accumulate=false ); 5 //1.輸入的圖像數組 2.輸入數組的個數 3.通道數 4.掩碼 5.直方圖 6 //6.直方圖維度 7.直方圖每個維度的尺寸數組 8.每一維數組的范圍 9.直方圖是否是均勻 10.累加標志
參數詳解:
images:輸入的圖像的指針,可以是多幅圖像,所有的圖像必須有同樣的深度(CV_8U or CV_32F)。同時一副圖像可以有多個channes。
nimages:輸入圖像的個數
channels:需要統計直方圖的第幾通道。用來計算直方圖的channes的數組。比如輸入是2副圖像,第一副圖像有0,1,2共三個channel,第二幅圖像只有0一個channel,那么輸入就一共有4個channes,如果int channels[3] = {3, 2, 0},那么就表示是使用第二副圖像的第一個通道和第一副圖像的第2和第0個通道來計算直方圖。
3.實現:
1 void GetGammaCorrection(Mat& src, Mat& dst, const float fGamma) 2 { 3 unsigned char bin[256]; 4 for (int i = 0; i < 256; ++i) 5 { 6 bin[i] = saturate_cast<uchar>(pow((float)(i / 255.0), fGamma) * 255.0f); 7 } 8 dst = src.clone(); 9 const int channels = dst.channels(); 10 switch (channels) 11 { 12 case 1: 13 { 14 MatIterator_<uchar> it, end; 15 for (it = dst.begin<uchar>(), end = dst.end<uchar>(); it != end; it++) 16 *it = bin[(*it)]; 17 break; 18 } 19 case 3: 20 { 21 MatIterator_<Vec3b> it, end; 22 for (it = dst.begin<Vec3b>(), end = dst.end<Vec3b>(); it != end; it++) 23 { 24 (*it)[0] = bin[((*it)[0])]; 25 (*it)[1] = bin[((*it)[1])]; 26 (*it)[2] = bin[((*it)[2])]; 27 } 28 break; 29 } 30 } 31 } 32
33 int main() 34 { 35 Mat image = imread("C:\\Users\\Administrator\\Desktop\\ir\\2ir.bmp"); 36 if (image.empty()) 37 { 38 cout << "Error: Could not load image" << endl; 39 return 0; 40 } 41
42 Mat dst; 43 float fGamma = 1 / 2.0; 44 GetGammaCorrection(image, dst, fGamma); 45 imshow("Source Image", image); 46 imshow("Dst", dst); 47 std::string filename = "C:\\Users\\Administrator\\Desktop\\ir\\dst2ir.bmp"; 48 cv::imwrite(filename, dst); 49
50 cv::waitKey(0); 51
52 return 0; 53 }
4.效果
未經gamma校正和經過gamma校正保存圖像信息如圖:
能夠觀察到,未經gamma校正的情況下,低灰度時,有較大范圍的灰度值被保存成同一個值,造成信息丟失;同一時候高灰度值時,非常多比較接近的灰度值卻被保存成不同的值,造成空間浪費。經過gamma校正后,改善了存儲的有效性和效率。