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 { 3for (int i = 0; i < height; i++){ 4for (int j = 0; j <width; j++) 5out_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 { 3for (int i = 0; i < height; i++){ 4for (int j = 0; j <width; j++) 5out_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 { 3for (int i = 0; i < height; i++){ 4for (int j = 0; j <width; j++) 5out_array[i][j] = (short)pow(in_array[i][j], 1.2); 6} 7 }
直方圖均衡化
直方圖為離散函式h(r k ) = n k , 其中r k 是第k級灰度值,n k 是影象中h灰度為r k 的畫素個數
現在給出上面幾幅影象的直方圖
可以明顯看出,對比度越高的影象,直方圖的分佈越均衡,因此直方圖均衡化演算法可以顯著提高影象對比度
直方圖均衡化演算法推導(需一定高等數學及概率論知識)
演算法實現
1 void calculate_histogram(long height, long width, short **image, unsigned long histogram[]) 2 { 3short k; 4for(int i=0; i < height; i++){ 5for(int j=0; j < width; j++){ 6k = image[i][j]; 7histogram[k] = histogram[k] + 1; 8} 9} 10 } 11 12 void histogram_equalization(short** in_array, short** out_array, long height, long width) 13 { 14unsigned long sum, sum_of_h[GRAY_LEVELS]; 15double constant; 16unsigned long histogram[GRAY_LEVELS] = {}; 17 18calculate_histogram(height, width, in_array, histogram); 19sum = 0; 20for(int i=0; i < GRAY_LEVELS; i++){ 21sum= sum + histogram[i]; 22sum_of_h[i] = sum; 23} 24 25constant = (double)(GRAY_LEVELS)/(double)(height*width); 26for(int i = 0, k = 0; i < height; i++){ 27for(int j = 0; j < width; j++){ 28k = in_array[i][j]; 29out_array[i][j] = sum_of_h[k] * constant; 30} 31} 32 }