根据以下博客代码翻译成了python
https://blog.csdn.net/c80486/article/details/52505061
代码如下:
import cv2 as cv
import math
import numpy as np
brightness = 255
contrast = 255
window_name = 'adjust_B&C'
def CLIP_RANGE(value,min,max):
if value > max:
return max
else:
if value<min:
return min
else:
return value
def COLOR_RANGE(value):
return CLIP_RANGE(value, 0, 255)
def adjustBrightnessContrast(arg):
brightness = cv.getTrackbarPos('brightness', window_name) - 255
contrast = cv.getTrackbarPos('contrast', window_name) - 255
brightness = CLIP_RANGE(brightness,-255,255)
contrast = CLIP_RANGE(contrast,-255,255)
'''
Algorithm of Brightness Contrast transformation
The formula is:
y = [x - 127.5 * (1 - B)] * k + 127.5 * (1 + B);
x is the input pixel value
y is the output pixel value
B is brightness, value range is [-1,1]
k is used to adjust contrast
k = tan( (45 + 44 * c) / 180 * PI );
c is contrast, value range is [-1,1]
'''
B = brightness / 255
c = contrast / 255
k = math.tan(( 45 + 44 * c) / 180 * math.pi)
# LUT(LOOK -UP-TABLE)查找表
ListaVred = [0] * 256
for i in range(0, 256):
ListaVred[i] = int(COLOR_RANGE((i - 127.5 * (1 - B)) * k + 127.5 * (1 + B)))
ListaVred = np.array(ListaVred)
new_image = cv.LUT(image,ListaVred)
# 显示结果图像
cv.imshow(window_name,new_image.astype(np.uint8))
if __name__ == '__main__':
# read image
image = cv.imread("g:/hand.jpg")
cv.namedWindow(window_name)
# create trackbars
cv.createTrackbar('brightness', window_name, brightness, brightness*2, adjustBrightnessContrast)
cv.createTrackbar('contrast', window_name, contrast, contrast*2, adjustBrightnessContrast)
adjustBrightnessContrast(0)
cv.waitKey(0)
cv.destroyAllWindows()
运行效果
前一张为原图,后一张为亮度对比度调节后图像