import cv2
import numpy as np
def imgBrightness(img1, c, b):
rows, cols, channels = img1.shape
blank = np.zeros([rows, cols, channels], img1.dtype)
rst = cv2.addWeighted(img1, c, blank, 1-c, b)
return rst
img = cv2.imread('1.jpg')
rst = imgBrightness(img, 2.0, 3)
cv2.imwrite('2.jpg',rst)
方法二
import numpy as np
import cv2
def compute(img, min_percentile, max_percentile):
"""计算分位点,目的是去掉图1的直方图两头的异常情况"""
max_percentile_pixel = np.percentile(img, max_percentile)
min_percentile_pixel = np.percentile(img, min_percentile)
return max_percentile_pixel, min_percentile_pixel
def aug(src):
"""图像亮度增强"""
if get_lightness(src)>130:
print("图片亮度足够,不做增强")
max_percentile_pixel, min_percentile_pixel = compute(src, 1, 99)
src[src>=max_percentile_pixel] = max_percentile_pixel
src[src<=min_percentile_pixel] = min_percentile_pixel
out = np.zeros(src.shape, src.dtype)
cv2.normalize(src, out, 255*0.1,255*0.9,cv2.NORM_MINMAX)
return out
def get_lightness(src):
hsv_image = cv2.cvtColor(src, cv2.COLOR_BGR2HSV)
lightness = hsv_image[:,:,2].mean()
return lightness
img = cv2.imread("1.jpg")
img = aug(img)
cv2.imwrite('3.jpg', img)
方法三
import numpy as np
import cv2
def gamma_transform(img, gamma):
is_gray = img.ndim == 2 or img.shape[1] == 1
if is_gray:
img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
illum = hsv[..., 2] / 255.
illum = np.power(illum, gamma)
v = illum * 255.
v[v > 255] = 255
v[v < 0] = 0
hsv[..., 2] = v.astype(np.uint8)
img = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
if is_gray:
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
return img
if __name__ == '__main__':
img = cv2.imread('1.jpg')
cv2.imwrite('4.jpg',gamma_transform(img,0.3))