本文主要是介绍Python图像高光调整,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
看了这个文章,里面有专门的c++的实现,我这边简单的使用python进行了实现,实现了两个版本,一个是python遍历像素,一个是使用numpy加速,代码如下:
import time
import numpy as np
import cv2def lighting(img, light):assert -100 <= light <= 100max_v = 4bright = (light/100.0)/max_vmid = 1.0+max_v*brightprint('bright: ', bright, 'mid: ', mid)gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY).astype(np.float32)/255.0thresh = gray*grayt = 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] = midbrightrate[i, j] = brightelse:mask[i, j] = (mid-1.0)/t*thresh[i, j]+1.0brightrate[i, j] = (1.0/t*thresh[i, j])*brightimg = img/255.0img = np.power(img, 1.0/mask[:, :, np.newaxis])*(1.0/(1.0-brightrate[:, :, np.newaxis]))img = np.clip(img, 0, 1.0)*255.0return img.astype(np.uint8)def lighting_fast(img, light):assert -100 <= light <= 100max_v = 4bright = (light/100.0)/max_vmid = 1.0+max_v*brightprint('bright: ', bright, 'mid: ', mid)gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY).astype(np.float32)/255.0thresh = gray*grayt = 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.0img = np.power(img, 1.0/mask[:, :, np.newaxis])*(1.0/(1.0-brightrate[:, :, np.newaxis]))img = np.clip(img, 0, 1.0)*255.0return img.astype(np.uint8)if __name__ == '__main__':input_img = cv2.imread('tmp/302.png')light = 50start_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++原文对比是一致的
这篇关于Python图像高光调整的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!