Author: Ding Yanjun

Images from the Internet

\

In recent days, many cities have welcomed the first snow of 2019

\

A few mornings ago, when Beijing residents opened their curtains, they found that snowflakes were falling in the sky

The trees, the grass, the roofs, the roads… All covered with snow

The capital is covered in snow. It is the second snowfall in Beijing this winter

When it snows, Beijing becomes Peiping and the Forbidden City becomes the Forbidden City

\

Eighty thousand tickets were booked well before the snow fell

\

\

Looking at circle of friends, micro blog friends are in print, the author can only envy unceasingly.

\

However, it occurred to me that I could use Python to turn the pictures of the buildings of the Forbidden City into hand-drawn drawings (sketch effect). The renderings are as follows:

\

I. Concept and principle

* * * *

We all know that the main features of hand-drawn drawing effect are:

  • Black and white gray; The boundary line is heavier; The same or similar color tends to white; Light source effect

\

Core principle: the gradient value and virtual depth value between pixels are used to reconstruct the image, and the simulation degree of human vision is simulated according to the change of gray level

\

The image is regarded as a two-dimensional discrete function, and the gray gradient is actually the derivative of the two-dimensional discrete function. The gray gradient of the image is obtained by using difference instead of differentiation. Some commonly used gray gradient templates are: Roberts gradient, Sobel gradient, Prewitt gradient, Laplacian gradient.

\

Explained by Sobel gradient calculation:

* * * *

So let’s figure out,And then calculate the gradient Angle

The gradient direction and the direction of gray increase of the image, in which the gradient Angle of the gradient direction is greater than that of the flat area. As shown in the figure below, the gradient Angle in the direction of gray value increase is large, and the direction with large gradient Angle is the gradient direction. To find the gradient direction of a certain point in the image, that is, calculate the gradient Angle of the point and its 8 neighborhood points, and the maximum gradient Angle is the gradient direction.

* * * * \

Second, the image array form and transformation

\

\

Among them, methods need to be used:

  • Image.open(): Opens the Image
  • Np.array () : Converts an image to an array
  • Convert (“L”): Convert images to two-dimensional grayscale images
  • Image.fromarray(): Restores the array to the Image uint8 format

\

The code is as follows:

from PIL import Image import numpy as np im = Image. The open (r "C: UsersAdministratorDesktopgugong WeChat picture _20190216152248. The JPG"). The convert (' L ') a = np. Asarray (im) astype (' float ') Print (a.shape, a.type) (1080, 608) float64 #(1080, 608) print(a.shape, a.type) (1080, 608) float64 #(1080, 608Copy the code

\

Three, the hand-painted image effect processing

\

Steps to achieve the idea:

* * * *

1. Reconstruction of gradient

* * * *

Numpy gradient function introduction

* * * *

Np.gradient (a) : Calculates the gradient of elements in array A, and returns the gradient of each dimension when f is multidimensional

Discrete gradient: the Y-axis values corresponding to the three consecutive X-axis coordinates of the XY coordinate axis: A, B, and C where the gradient of B is (c-A) /2

And the gradient of C is c minus b over 1

\

When it is a two-dimensional array, Np.gradient (a) obtains two arrays, the first array corresponds to the gradient of the outermost dimension, and the second array corresponds to the gradient of the second dimension.

\

The code is: \

Grad =np.gradient(a) grad_x,grad_y=grad grad_x * depth / 100 # Normalize the grad_y valueCopy the code

\

2, structure guan light source effect \

\

A virtual light source located above the oblique image is designed. The Angle of view of the light source relative to the image is Elevation, and the Azimuth is Azimuth. The influence function of the light source on the gradient value of each point is established and the new pixel value of each point is calculated

Among them:

Np. cos(evC.el) : The projection length of a unit ray on the ground plane

Dx,dy,dz: degree of influence of light source on x, Y and Z directions

\

3. Gradient normalization

  • The three-dimensional normalized unit coordinate system of x and y axis gradient is constructed.
  • The gradient interacts with the light source to transform the gradient into grayscale.

\

4. Image generation

* * * *

The detailed code is as follows:

from PIL import Image import numpy as np import os import join import time def image(sta,end,depths=10): A = Np.asarray (image.open (sta).convert('L')).astype('float') depth = unimpressed # 10 grad = NP.gradient (a) # Take grad_x of image gray scale, Grad_y = grad_y * depth / 100.# Normalize grad_y = grad_y * depth / 100 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 # The overlooking Angle of the light source, radian value vec_az = Np.pi / 4. Cos (vec_EL) * Np.cos (vec_az) # Effect of light source on X-axis DY = Np.cos (VEC_EL) * NP.sin (vec_az) # Effect of light source on Y-axis Dz = Np.sin (vec_el) # Effect of light source on z-axis b = 255 * (dx * uni_x + dy * uni_y + dz * uni_z) # Light source normalization b = B.lip (0, 255) im = image.fromarray (b.uint8 ('uint8')) # im.save(end) def main(): xs=10 start_time = time.clock() startss = os.listdir(r"C:UsersAdministratorDesktopgugong") time.sleep(2) for starts in startss: start = ''.join(starts) sta = 'C:/Users/Administrator/Desktop/gugong/' + start end = 'C:/Users/Administrator/Desktop/gugong/' + 'HD_' + start image(sta=sta,end=end,depths=xs) end_time = time.clock() Print (' run ----' + STR (end_time-start_time) + 'seconds ') time.sleep(3) main() run ----43.01828205879955 secondsCopy the code

\

Comparison of final renderings:

Other pictures are not listed, if you need to get more pictures, scan and follow the public account below reply to the Palace Museum can be obtained; You can also use this code to draw a sketch of yourself; You can also paint for your hometown or Alma mater.

\

References:

www.icourse163.org/learn/BIT-1…

\

\

Python Chinese community as a decentralized global technology community, to become the world’s 200000 Python tribe as the vision, the spirit of Chinese developers currently covered each big mainstream media and collaboration platform, and ali, tencent, baidu, Microsoft, amazon and open China, CSDN industry well-known companies and established wide-ranging connection of the technical community, Have come from more than 10 countries and regions tens of thousands of registered members, members from the Ministry of Public Security, ministry of industry, tsinghua university, Beijing university, Beijing university of posts and telecommunications, the People’s Bank of China, the Chinese Academy of Sciences, cicc, huawei, BAT, represented by Google, Microsoft and other government departments, scientific research institutions, financial institutions, and well-known companies at home and abroad, nearly 200000 developers to focus on the platform.

\

Click below to read the original article and become a free community member at ****