This article is one of the actual combat projects of the numpy library. For specific knowledge points , please see the following link: From getting started to giving up: python data analysis series-numpy
. Before writing, please make sure you have configured the python environment and downloaded the numpy library.
The original picture is as follows:
This is an effect picture:
Observe the hand drawing before drawing, you can find that it has the following characteristics:
- The main color is black, white and gray
- Heavier border lines
- The same or similar colors tend to be white
- Slight light source effect
The libraries that need to be used are: - numpy
Since the code of PIL is relatively short, the blogger commented the main code as follows:
import numpy as np
from PIL import Image
baseImg = Image.open("./img/myimg2.jpg").convert("L") # 这里放置你要手绘的图片原图
a = np.array(baseImg).astype("float")
depth = 8.
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.sin(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) # 限制
img = Image.fromarray(b.astype("uint8")) # 重构图像
img.save("./toImg/myImage1.jpg") # 保存图像
Give it a try!