gamma校正可使得图像看起来更符合人眼的特性。gamma校正公式常写为Out= Ingamma或者Out= In1/gamma形式,式中,In表示Input image, Out 表示Output image。本文采用第一种形式。gamma校正前后图像的亮度对比如下图所示。本文分别用opencv-python和MATLAB实现了gamma校正。
1. opencv-python实现gamma校正
1 import cv2 2 import numpy as np 3 import matplotlib.pyplot as plt 4 5 gamma1 = 0.4 6 gamma2 = 2.5 7 8 imgIn = cv2.imread('messi.jpg', 0) 9 imgIn = imgIn.astype(float) / 255 10 11 out1 = imgIn ** gamma1 12 out2 = imgIn ** gamma2 13 14 out1 *= 255 15 out1[out1 < 0] = 0 16 out1[out1 > 255] = 255 17 out1 = out1.astype(np.uint8) 18 19 out2 *= 255 20 out2[out2 < 0] = 0 21 out2[out2 > 255] = 255 22 out2 = out2.astype(np.uint8) 23 24 # show images 25 plt.subplot(131) 26 plt.title('gamma=0.4') 27 plt.xticks([]) # 去除刻度 28 plt.yticks([]) 29 plt.imshow(out1, cmap='gray') 30 31 plt.subplot(132) 32 plt.title('original image') 33 plt.xticks([]) 34 plt.yticks([]) 35 plt.imshow(imgIn, cmap='gray') 36 37 plt.subplot(133) 38 plt.title('gamma=2.5') 39 plt.xticks([]) 40 plt.yticks([]) 41 plt.imshow(out2, cmap='gray') 42 plt.show()
效果如下:
2. MATLAB实现gamma校正
clear; img_ori = imread('Fig0308(a)(fractured_spine).tif'); img_mat = mat2gray(img_ori, [0 255]); c = 1; gamma03 = 0.3; gamma06 = 0.6; gamma25 = 2.5; img_gam03 = c*(img_mat.^gamma03); img_gam06 = c*(img_mat.^gamma06); img_gam25 = c*(img_mat.^gamma25); % show images figure; subplot(1,4,1); imshow(img_mat, [0, 1]); title('original image'); subplot(1,4,2); imshow(img_gam03, [0, 1]); title('gamma=0.3'); subplot(1,4,3); imshow(img_gam06, [0, 1]); title('gamma=0.6'); subplot(1,4,4); imshow(img_gam25, [0, 1]); title('gamma=2.5');
效果如下: