1 from PIL import Image 2 import numpy as np 3 4 def paint(oname,sname): 5 a = np.asarray(Image.open(oname).convert('L')).astype('float') 6 7 depth = 15. # (0-100)基础灰度值 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 A = np.sqrt(grad_x**2 + grad_y**2 + 1.) 13 uni_x = grad_x/A 14 uni_y = grad_y/A 15 uni_z = 1./A 16 17 vec_el = np.pi/2.2 # 光源的俯视角度,弧度值 18 vec_az = np.pi/4. # 光源的方位角度,弧度值 19 dx = np.cos(vec_el)*np.cos(vec_az) #光源对x 轴的影响 20 dy = np.cos(vec_el)*np.sin(vec_az) #光源对y 轴的影响 21 dz = np.sin(vec_el) #光源对z 轴的影响 22 23 b = 255*(dx*uni_x + dy*uni_y + dz*uni_z) #光源归一化 24 b = b.clip(0,255) 25 26 im = Image.fromarray(b.astype('uint8')) #重构图像 27 im.save(sname) 28 if __name__=='__main__': 29 try: 30 oname=input('please input the name of a image:') 31 while True: 32 sname=input('please input the name to save the image:') 33 if oname == sname: 34 ans =input('cover the original image?(y of n)') 35 print(ans) 36 if ans =='n' : 37 continue 38 elif ans == 'y' : 39 break 40 else: 41 print('the format is wrong!') 42 else : 43 break 44 paint(oname,sname) 45 except: 46 print('There is an error')