import cv2 as cv
import numpy as np
import random
def random_gamma(src_image):
# gamma变换通过OpenCV中的LUT函数完成,其功能是通过一个映射表,把原图的像素诸逐个映射
if random.random() < 0.9:
if src_image.mean() < 128:
gamma_val = max(random.random() / 2, 0.15)
else:
gamma_val = min(random.random() / 2 + 0.5, 0.85)
print(gamma_val)
gamma_table = [np.power(x / 255.0, gamma_val) * 255.0 for x in range(256)] # 对原来每个像素值建立映射
gamma_table = np.round(np.array(gamma_table)).astype(np.uint8) # 转换为图像显示的格式
src_image = cv.LUT(src_image, gamma_table)
return src_image
if __name__ == "__main__":
image = "./data/phone.jpg"
src = cv.imread(image, cv.IMREAD_GRAYSCALE)
src = cv.resize(src, dsize=None, fx=0.5, fy=0.5)
cv.imshow("src", src)
while True:
res = random_gamma(np.copy(src))
cv.imshow("res", res)
if cv.waitKey() & 0xFF == ord('q'):
break
cv.destroyAllWindows()