数字图像处理:一些基本灰度变换
包括图像反转、对数变换、幂律(伽马)变换、分段线性变换函数,测试图选的不咋地
import cv2 import numpy as np #灰度图反转 def grayReversal(gray): gray_reversal = 255 - gray #灰度图反转 return gray_reversal #彩色图像反转 def imgReversal(img): img_reversal = np.zeros(img.shape, np.uint8)#初始模板 for i in range(img.shape[0]): for j in range(img.shape[1]): b, g, r = img[i, j] #注意是bgr,不是rgb img_reversal[i, j] = 255 - b, 255 - g, 255 - r return img_reversal #对数变换 def logTrans(gray, c): gray_log = np.uint8((c * np.log(1.0 + gray))) return gray_log #幂律(伽马)变换 def powerTrans(gray, c, y): gray_power = np.uint8(c * (gray ** y)) return gray_power path = "_kdy.jpg" img = cv2.imread(path) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #转换为灰度图 gray_reversal = grayReversal(gray) img_reversal = imgReversal(img) gray_log = logTrans(gray, c=30) gray_power = powerTrans(gray, c=30, y =0.35) cv2.imshow("img", img) cv2.imshow("gray", gray) cv2.imshow("gray_reversal", gray_reversal) cv2.imshow("img_reversal", img_reversal) cv2.imshow("gray_log", gray_log) cv2.imshow("gray_power", gray_power) cv2.waitKey(0)
(图分别为原图、灰度图、灰度反转图、对数变换图、幂律(伽马)变换图)
————————————————————————————————————
分段线性变换函数
就是用拉格朗日插值法实现分段线性变换函数,然后,注意数据类型的转换就完事了,可用来对比度拉伸和灰度级分层
import cv2 import numpy as np #拉格朗日插值法,对比度拉伸 def plf(x, X, Y): x = np.float32(x)#得把数据类型给转换下 y = 0 for i in range(len(X)): t = 1 for j in range(len(Y)): if j != i: t = t * ((x - X[j]) / (X[i] - X[j])) y = np.uint8(y + t * Y[i])#再把数据类型换下 return y path = "_plf.jpg" img = cv2.imread(path) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #转换为灰度图 #参数设置 X = [0, 60, 190, 255] Y = [0, 30, 230, 255] gray_plf = plf(gray, X, Y) cv2.imshow("gray", gray) cv2.imshow("gray_plf", gray_plf) cv2.waitKey(0)
左图是灰度图,右图是对比图拉伸图