代码:
import cv2
import imutils
import numpy as np
def l_s_b(arg):
# 图像归一化,且转换为浮点型, 颜色空间转换 BGR转为HLS
# astype用于转换数组的数据类型
fImg = img.astype(np.float32)
fImg = fImg / 255.0
# HLS空间,三个通道分别是: Hue色相、lightness明度、saturation饱和度
# 通道0是色相、通道1是明度、通道2是饱和度
hlsImg = cv2.cvtColor(fImg, cv2.COLOR_BGR2HLS)
"""HSL--明亮度和饱和度"""
"""
函数 cv2.getTrackbarPos():
功能:得到滑动条的数值
参数:1.滑动条名字 2.窗口名
"""
lnum = cv2.getTrackbarPos('lightness', wname)
snum = cv2.getTrackbarPos('saturation', wname)
cnum = cv2.getTrackbarPos('contrast', wname)
# 1.调整亮度饱和度(线性变换)、 2.将hlsCopy[:,:,1]和hlsCopy[:,:,2]中大于1的全部截取
hlsImg[:, :, 1] = (1.0 + lnum / float(MAX_VALUE)) * hlsImg[:, :, 1]
hlsImg[:, :, 1][hlsImg[:, :, 1] > 1] = 1
# HLS空间通道2是饱和度,对饱和度进行线性变换,且最大值在255以内,这一归一化了,所以应在1以内
hlsImg[:, :, 2] = (1.0 + snum / float(MAX_VALUE)) * hlsImg[:, :, 2]
hlsImg[:, :, 2][hlsImg[:, :, 2] > 1] = 1
# HLS2BGR
lsImg = cv2.cvtColor(hlsImg, cv2.COLOR_HLS2BGR)
"""BGR--对比度"""
h, w, ch = lsImg.shape # 获取shape的数值,height和width、通道
# 新建全零图片数组img2,将height和width,类型设置为原图片的通道类型(色素全为零,输出为全黑图片)
img2 = np.zeros([h, w, ch], lsImg.dtype)
dst = cv2.addWeighted(lsImg, cnum, img2, 1 - cnum, 0) # addWeighted函数说明如下
# 显示调整后的效果
cv2.imshow(wname, imutils.resize(dst, 400))
wname = 'simple_edit'
img = cv2.imread('hh.jpg')
if __name__ == '__main__':
MAX_VALUE = 100
cv2.namedWindow(wname, cv2.WINDOW_AUTOSIZE)
# 第一个数为默认值,第二个数为最大范围
cv2.createTrackbar("lightness", wname, 0, MAX_VALUE, l_s_b)
cv2.createTrackbar("saturation", wname, 0, MAX_VALUE, l_s_b)
cv2.createTrackbar('contrast', wname, 1, 10, l_s_b)
l_s_b(0)
if cv2.waitKey(0) == 27:
cv2.destroyAllWindows()
效果: