20 lines of Python code to shape yourself into a sketch master

The origin of the matter:

There are still about three months before the Chinese New Year. The worst thing when I go home is that my parents are urging a blind date and urging to find a partner. No, I was pulled into a blind date group by my mother. I just entered a blind date. Can you imagine? My mother introduced my photos and information like a product, and finally said: Come on, say hello to all the aunts and beauties.
insert image description here

All right! I was in my youth, and my mother disliked being single. After a warm greeting, a young lady with a caricature head added me, oh well, my photo is attractive.

insert image description here

After agreeing to add Miss Sister, I chatted with Miss Sister and was asked what I do for work, huh? Thinking of an example on the Internet, I can’t ask him to know that I am a code farmer. I have a flash of inspiration. I am a painter. The sketch was completed in five minutes, and the young lady was fascinated. To say that I am like Tang Bohu reincarnated, this bragging can be called a word!
insert image description here

Original image:

insert image description here

After conversion:

insert image description here

source code:

from PIL import Image  #图像处理模块
import numpy as np
 
a = np.asarray(Image.open("这里是原图片的路径").convert('L')).astype('float')  
#将图像以灰度图的方式打开并将数据转为float存入np中
 
depth = 10.           # (0-100)
grad = np.gradient(a)       #取图像灰度的梯度值
grad_x, grad_y =grad        #分别取横纵图像梯度值
grad_x = grad_x*depth/100.
grad_y = grad_y*depth/100.
A = np.sqrt(grad_x**2 + grad_y**2 + 1.)
uni_x = grad_x/A
uni_y = grad_y/A
uni_z = 1./A
#建立一个位于图像斜上方的虚拟光源
vec_el = np.pi/2.2          # 光源的俯视角度,弧度值
vec_az = np.pi/4.          # 光源的方位角度,弧度值
dx = np.cos(vec_el)*np.cos(vec_az)  #光源对x 轴的影响
dy = np.cos(vec_el)*np.sin(vec_az)  #光源对y 轴的影响
dz = np.sin(vec_el)         #光源对z 轴的影响
#计算各点新的像素值
b = 255*(dx*uni_x + dy*uni_y + dz*uni_z)   #光源归一化
b = b.clip(0,255)  #clip函数将区间外的数字剪除到区间边缘
 
im = Image.fromarray(b.astype('uint8')) #重构图像
im.save("这里是输出图片的路径")

Guess you like

Origin blog.csdn.net/weixin_57577264/article/details/121103860