c語言數字圖像處理(四):灰度變換


灰度變換

灰度變換函數 s = T(r)   其中r為輸入圖像在(x, y)點處的灰度值,s為輸出圖像在(x, y)點處的灰度值

灰度變換的作用

 

上圖所示的兩幅T(s)函數的圖像曲線,第一幅圖可以增強圖像對比度,第二幅圖可以對圖像進行二值化處理

灰度變換函數

反轉函數

1 void reverse(short** in_array, short** out_array, long height, long width)
2 {
3     for (int i = 0; i < height; i++){
4         for (int j = 0; j <width; j++)
5             out_array[i][j] = GRAY_LEVELS - in_array[i][j];
6     }
7 }

最簡單的灰度變換函數,將圖像中的每個像素點處的顏色值反轉,對於8位灰度圖片,用255減去原灰度值

原圖

 

反轉圖

對數變換

s = clog(1 + r)  c為常數,本次測試中c取10

1 void logarithm(short** in_array, short** out_array, long height, long width)
2 {
3     for (int i = 0; i < height; i++){
4         for (int j = 0; j <width; j++)
5             out_array[i][j] = (short)(10 * log((1 + in_array[i][j])));
6     }
7 }

可以看出,對數變換降低了圖像的對比度

冪律(伽馬)變換

s = crγ  其中 c 和 γ 為正常數

其中γ<1時,降低對比度,γ>1時,提高對比度

γ = 1.2

1 void gamma(short** in_array, short** out_array, long height, long width)
2 {
3     for (int i = 0; i < height; i++){
4         for (int j = 0; j <width; j++)
5             out_array[i][j] = (short)pow(in_array[i][j], 1.2);
6     }
7 }

直方圖均衡化

 直方圖為離散函數h(rk) = nk, 其中rk是第k級灰度值,nk是圖像中h灰度為rk的像素個數

現在給出上面幾幅圖像的直方圖

可以明顯看出,對比度越高的圖像,直方圖的分布越均衡,因此直方圖均衡化算法可以顯著提高圖像對比度

直方圖均衡化算法推導(需一定高等數學及概率論知識)

算法實現

 1 void calculate_histogram(long height, long width, short **image, unsigned long histogram[])
 2 {
 3     short k;
 4     for(int i=0; i < height; i++){
 5         for(int j=0; j < width; j++){
 6             k = image[i][j];
 7             histogram[k] = histogram[k] + 1;
 8         }
 9     }
10 } 
11 
12 void histogram_equalization(short** in_array, short** out_array, long height, long width)
13 {
14     unsigned long sum, sum_of_h[GRAY_LEVELS];
15     double constant;
16     unsigned long histogram[GRAY_LEVELS] = {};
17 
18     calculate_histogram(height, width, in_array, histogram);
19     sum = 0;
20     for(int i=0; i < GRAY_LEVELS; i++){
21         sum         = sum + histogram[i];
22         sum_of_h[i] = sum;
23     }
24 
25     constant = (double)(GRAY_LEVELS)/(double)(height*width);
26     for(int i = 0, k = 0; i < height; i++){
27         for(int j = 0; j < width; j++){
28             k = in_array[i][j];
29             out_array[i][j] = sum_of_h[k] * constant;
30         }
31     }
32 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM