import numpy as np
def simple_balance(img, s1, s2): # 线性增强,s1和s2为低高分段阈值百分比
h, w = img.shape[:2]
res = img.copy()
one_dim_array = res.flatten() # 转化为一维数组
sort_array = sorted(one_dim_array) # 对一维数组按升序排序
print(len(sort_array))
per1 = int((h * w) * s1 / 100)
print(per1/len(sort_array))
minvalue = sort_array[per1]
per2 = int((h * w) * s2 / 100)
print(((h * w) - 1 - per2)/len(sort_array))
maxvalue = sort_array[(h * w) - 1 - per2]
# 实施简单白平衡算法
if (maxvalue <= minvalue):
for i in range(h):
for j in range(w):
res[i, j] = maxvalue
else:
scale = 255.0 / (maxvalue - minvalue)
for m in range(h):
for n in range(w):
if img[m, n] < minvalue:
res[m, n] = 0
elif img[m, n] > maxvalue:
res[m, n] = 255
else:
res[m, n] = scale * (img[m, n] - minvalue) # 映射中间段的图像像素
return res
def ALTM(img):
h, w = img.shape[:2]
res = np.float32(img) # res = np.array(img, dtype=np.float32) # 转换为32位图像
Lwmax = res.max()
log_Lw = np.log(0.001 + res)
Lw_sum = log_Lw.sum()
Lwaver = np.exp(Lw_sum / (h * w))
Lg = np.log(res / Lwaver + 1) / np.log(Lwmax / Lwaver + 1)
res = Lg * 255.0 # 不使用分段线性增强
# res = simple_balance(Lg, 2, 3) # 使用线性增强,该算法比较耗时
dst = np.uint8(res) # dst = cv2.convertScaleAbs(res)
return dstleAbs(res) return