1 from PIL import Image 2 import numpy as np 3 vec_el = np.pi / 2.2 # 光源的俯视角度,弧度值 4 vec_az = np.pi / 4. # 光源的方位角度,弧度值 5 depth = 10. # (0-100) 6 im = Image.open('555.jpg').convert('L') 7 a = np.asarray(im).astype('float') 8 grad = np.gradient(a) # 取图像灰度的梯度值 9 grad_x, grad_y = grad # 分别取横纵图像梯度值 10 grad_x = grad_x * depth / 100. 11 grad_y = grad_y * depth / 100. 12 dx = np.cos(vec_el) * np.cos(vec_az) # 光源对 x轴的影响 13 dy = np.cos(vec_el) * np.sin(vec_az) # 光源对 y轴的影响 14 dz = np.sin(vec_el) # 光源对z 轴的影响 15 A = np.sqrt(grad_x ** 2 + grad_y ** 2 + 1.) 16 uni_x = grad_x / A 17 uni_y = grad_y / A 18 uni_z = 1. / A 19 p = 255 * (dx * uni_x + dy * uni_y + dz * uni_z) # 光源归一化 20 p = p.clip(0, 255) 21 im2 = Image.fromarray(p.astype('uint8')) # 重构图像 22 im2.save("666.jpg")