這篇文章主要介紹了python實現圖像自動Gamma校正方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
文章源自四五設計網-http://www.133122.cn/41434.html
python圖像自動Gamma校正
文章源自四五設計網-http://www.133122.cn/41434.html
關于Gamma
Gamma校正是對動態范圍內亮度的非線性存儲/還原算法,即輸入值進行的非線性操作,使輸出值與輸入值呈指數關系;文章源自四五設計網-http://www.133122.cn/41434.html
從效果上來說Gamma校正調整圖像的整體亮度,沒有校正的圖像看起來可能會存在過亮或太暗的情況,所以想要圖像顯示效果更完美,Gamma校正就顯得很重要了。文章源自四五設計網-http://www.133122.cn/41434.html
Gamma矯正的計算過程如下:文章源自四五設計網-http://www.133122.cn/41434.html
1 | output=〖input〗^(1/Gamma) |
使用上面的指數函數把每個像素的RGB值進行變換。文章源自四五設計網-http://www.133122.cn/41434.html
具體執行下列轉換公式(假定像素值的取值范圍為0到255):文章源自四五設計網-http://www.133122.cn/41434.html
1 2 3 | R=〖255X(R/255)〗^((1/gamma))G=〖255X(G/255)〗^((1/gamma))B=〖255X(B/255)〗^((1/gamma)) |
一般處理Gamma矯正都是通過手動調節gamma值來完成的,文章源自四五設計網-http://www.133122.cn/41434.html
但如果圖片多的情況下,手動設置gamma值顯得過于麻煩,文章源自四五設計網-http://www.133122.cn/41434.html
這時候就需要采用自動Gamma矯正,將RGB圖片轉成灰度圖,文章源自四五設計網-http://www.133122.cn/41434.html
計算灰度圖的數據均值,通過下面的計算公式計算gamma值。
1 | gamma_val = math.log10(0.5) / math.log10(mean / 255) |
python實現
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | import cv2import numpy as npimport mathimport osdef gamma_trans(img, gamma):? # gamma函數處理????gamma_table = [np.power(x / 255.0, gamma) * 255.0 for x in range(256)]? # 建立映射表????gamma_table = np.round(np.array(gamma_table)).astype(np.uint8)? # 顏色值為整數????return cv2.LUT(img, gamma_table)? # 圖片顏色查表。另外可以根據光強(顏色)均勻化原則設計自適應算法。def nothing(x):????passdata_base_dir = r'./1'? # 輸入文件夾的路徑outfile_dir = r'./2'? # 輸出文件夾的路徑list = os.listdir(data_base_dir)list.sort()list2 = os.listdir(outfile_dir)list2.sort()for file in list:? # 遍歷目標文件夾圖片????read_img_name = data_base_dir + '/' + file.strip()? # 取圖片完整路徑????image = cv2.imread(read_img_name)? # 讀入圖片????img_gray = cv2.imread(read_img_name, 0)? # 灰度圖讀取,用于計算gamma值????mean = np.mean(img_gray)????gamma_val = math.log10(0.5) / math.log10(mean / 255)? # 公式計算gamma????image_gamma_correct = gamma_trans(image, gamma_val)? # gamma變換????out_img_name = outfile_dir + '/' + file.strip()????cv2.imwrite(out_img_name, image_gamma_correct)????print("The photo which is processed is {}".format(file)) |
總結
以上為個人經驗,希望能給大家一個參考



評論