Basic manipulation of images in Python

Commonly used library numpy library and PIL library
PIL library for image reading and display:

from PIL import Image
im=Image.open('/home/np/下载/Lena.jpg')
im.show()

The numpy library converts the image into an array object, the code is as follows:

from PIL import Image
import numpy as np
im=np.array(Image.open('/home/np/下载/Lena.jpg'))

PIL includes an image conversion function, using the convert() function, 'L' mode, converts an RGB image to a grayscale image, the code is as follows:

from PIL import Image
import numpy as np
im=np.array(Image.open('/home/np/下载/Lena.jpg').convert('L'))

The RGB image can be converted into a grayscale image by the following formula:
Gray=R*0.3+G*0.59+B*0.11

Test Example: Converting an Image to a Hand-drawn Image

from PIL import Image
import numpy as np
vec_el = np.pi/2.2 # 光源的俯视角度,弧度值
vec_az = np.pi/4. # 光源的方位角度,弧度值
depth = 10. # (0-100)
im = Image.open('/home/np/下载/Lena.jpg').convert('L')
a = np.asarray(im).astype('float')
grad = np.gradient(a) #取图像灰度的梯度值
grad_x, grad_y = grad #分别取横纵图像梯度值
grad_x = grad_x*depth/100.
grad_y = grad_y*depth/100.
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 轴的影响
A = np.sqrt(grad_x**2 + grad_y**2 + 1.)
uni_x = grad_x/A
uni_y = grad_y/A
uni_z = 1./A
a2 = 255*(dx*uni_x + dy*uni_y + dz*uni_z) #光源归一化
a2 = a2.clip(0,255)
im2 = Image.fromarray(a2.astype('uint8')) #重构图像
im2.save('/home/np/下载/Lenashouhui.jpg')


The basic idea of ​​hand-drawn images is to reconstruct each pixel value using the gradient values ​​between pixels (rather than the pixels themselves).
In order to reflect the lighting effect, a light source is designed, and the influence function of the light source on each gradient value is established to calculate the new pixel value, thereby reflecting the change of the boundary gray level and forming a hand-painted effect.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325474888&siteId=291194637