在很多图像处理的软件有柔光的效果,,这里就很好奇是怎么实现的,于是就看了一些gimp的源码,然后使用python进行复现了一下,这里会稍微有点差异,因为为了省事就直接使用的cv2的高斯模糊,没有想gimp里面直接分x和y方向单独实现高斯模糊,不过效果基本上还是在的,
实现主要分为3步:
(1)计算锐化和亮度
(2)对(1)的图进行高斯模糊
(3)将原图和(2)的结果进行合并
下面是python代码:
import math
import cv2
import numpy as np
def sharpness_brightness(img, sharpness=0.85, brightness=0.65):
h, w = img.shape[:2]
dest_img = img.copy()
for row in range(h):
for col in range(w):
val = img[row, col]/255.0
val = 255.0 / (1 + np.exp(-(2 + (sharpness * 20)) * (val - 0.5)))
val = val * brightness
dest_img[row, col] = np.clip(val, 0, 255)
return dest_img
def int_mult(a, b):
t = (a * b) + 128
return ((t >> 8) + t) >> 8
def get_dest(src_img, blur_img):
h, w = src_img.shape[:2]
dest_img = src_img.copy()
for row in range(h):
for col in range(w):
dest_img[row, col, 0] = 255-int_mult((255-src_img[row, col, 0]), (255-blur_img[row, col, 0]))
dest_img[row, col, 1] = 255 - int_mult((255 - src_img[row, col, 1]), (255 - blur_img[row, col, 1]))
dest_img[row, col, 2] = 255 - int_mult((255 - src_img[row, col, 2]), (255 - blur_img[row, col, 2]))
return dest_img
def soft_glow(img, glow_radius=10.0):
sb = sharpness_brightness(img)
radius = int(abs(glow_radius) + 1.0)
std_dev = math.sqrt(-(radius * radius) / (2 * math.log(1.0 / 255.0)))
# print(radius, std_dev)
blur_res = cv2.GaussianBlur(sb, (radius, radius), sigmaX=std_dev, sigmaY=std_dev)
res = get_dest(img, blur_res)
return res
if __name__ == '__main__':
img = cv2.imread('7c.jpg')
res = soft_glow(img)
cv2.imwrite('7c_soft_glow.jpg', res)
效果如下:
注意的是sharpness, brightness和glow_radius都是可以进行自己设置的,就和gimp里面一样,针对不同的图可以调节成自己想要的效果,不过还是大分辨率会比较慢,可以自己加速一下。