看了这个文章,里面有专门的c++的实现,我这边简单的使用python进行了实现,实现了两个版本,一个是python遍历像素,一个是使用numpy加速,代码如下:
import time
import numpy as np
import cv2
def lighting(img, light):
assert -100 <= light <= 100
max_v = 4
bright = (light/100.0)/max_v
mid = 1.0+max_v*bright
print('bright: ', bright, 'mid: ', mid)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY).astype(np.float32)/255.0
thresh = gray*gray
t = np.mean(thresh)
mask = np.where(thresh > t, 255, 0).astype(np.float32)
brightrate = np.zeros_like(mask).astype(np.float32)
h, w = img.shape[:2]
# 遍历每个像素点
for i in range(h):
for j in range(w):
if mask[i, j] == 255.0:
mask[i, j] = mid
brightrate[i, j] = bright
else:
mask[i, j] = (mid-1.0)/t*thresh[i, j]+1.0
brightrate[i, j] = (1.0/t*thresh[i, j])*bright
img = img/255.0
img = np.power(img, 1.0/mask[:, :, np.newaxis])*(1.0/(1.0-brightrate[:, :, np.newaxis]))
img = np.clip(img, 0, 1.0)*255.0
return img.astype(np.uint8)
def lighting_fast(img, light):
assert -100 <= light <= 100
max_v = 4
bright = (light/100.0)/max_v
mid = 1.0+max_v*bright
print('bright: ', bright, 'mid: ', mid)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY).astype(np.float32)/255.0
thresh = gray*gray
t = np.mean(thresh)
# 使用numpy来计算可以加速,速度远快于上面的遍历
mask = np.where(thresh > t, 255, 0).astype(np.float32)
brightrate = np.where(mask == 255.0, bright, (1.0/t*thresh)*bright)
mask = np.where(mask == 255.0, mid, (mid-1.0)/t*thresh+1.0)
img = img/255.0
img = np.power(img, 1.0/mask[:, :, np.newaxis])*(1.0/(1.0-brightrate[:, :, np.newaxis]))
img = np.clip(img, 0, 1.0)*255.0
return img.astype(np.uint8)
if __name__ == '__main__':
input_img = cv2.imread('tmp/302.png')
light = 50
start_time = time.time()
res = lighting(input_img, light)
print('time: {:.3f} s'.format(time.time() - start_time))
cv2.imwrite('tmp/302_lighting_{}.jpg'.format(light), res)
start_time = time.time()
res = lighting_fast(input_img, light)
print('fast time: {:.3f} s'.format(time.time() - start_time))
cv2.imwrite('tmp/302_lighting_fast_{}.jpg'.format(light), res)
运行结果如下:
bright: 0.125 mid: 1.5
time: 6.454 s
bright: 0.125 mid: 1.5
fast time: 0.280 s
可以看到numpy加速很多倍,运行图的结果如下
原图:
python版结果:
+50
-50:
可以和c++原文对比是一致的