preface

Python is like a treasure chest of many treasures, covering just about everything. So it’s a great idea for anyone who has zero basic knowledge of Python to explore and learn. You’ll find that the language isn’t as difficult as it looks, and you’ll appreciate its subtlety.

Python may not be the best choice to implement some technologies in our daily work, but it is definitely the most intuitive and “down to earth”. In this article I will start from the image processing aspect, with a few easy to accept code to teach you how to use Python to do image processing, so that you can use it in the future. At the same time, I also sorted out some beginner learning books and materials at the end of the article, which are convenient for you to learn and practice. If you want to learn Python, you can pay attention to it. Send me a message and I will share it with those who need it. The concept of “word cloud” was first put forward by Rich Gordon, associate professor of journalism and director of new media program at Northwestern University. Word Cloud is a visual presentation of text data, which is generally composed of some color graphics extracted from text data. The core of word cloud map is to convey valuable information behind a large amount of text data through the visual expression of high-frequency keywords.

1. The word cloud

Usually used to highlight text keywords and create visual focus, the use of word clouds can make data more convincing.

Python also has a library dedicated to creating word clouds **- WordCloud **, which allows you to customize colors and shapes.

For example, I made a word cloud with the clown’s douban comments.

To compose a word cloud, firstly collect the text, then do word segmentation for the text, and finally generate the word cloud.

There is no detailed analysis of the first two steps, only the word cloud code is given here:

def wordCloudImage(wordlist,width,height,bgcolor,savepath): # cloud_mask = np.array(image.open ('nezha.png')) # wc = WordCloud(width=width, width) # background_color=bgcolor, # background_color= white "black" # mask=cloud_mask, # font_path='./fonts/simhei.ttf', # min_font_size=5, # min_font_size=5, Max_font_size =100, X = wc.generate(wordlist) # generate(image = x.to_image() # show() # Wc.to_file (savepath)Copy the code

2. Generate hand-drawn images

At present, many software can realize the technology of converting photos into hand-drawn form, and here, we can also achieve it with Python. The advantage of using Python is that it is more personalized and can be customized. And can realize batch conversion, convenient and quick.

Here we use the Pillow library, which is a very cool and professional Python image processing library

The original:

After generating hand painted:

Code:

# -*- coding: Utf-8 -*- from PIL import Image import numpy as np # original_image_path = "E:\ Image \ luguizui.jpg" Handdrawn_image_path = "E:\\ image \\ Lujiazui - freehand.jpg" A =np.asarray(image.open (original_image_path).convert('L')).astype('float') depth=10 Grad_y =grad grad_x=grad_x*depth/100. 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 Dx = Np.cos (vec_EL)* NP.cos (vec_az) dy= NP.cos (vec_EL)* NP.sin (vec_az) Dz = Np. sin(vec_EL) # Normalize the light source, convert the gradient to gray level b=255*(dx*uni_x+dy*uni_y+dz*uni_z) # Im = image.fromarray (B.astype ('uint8')) print(' finish ') im.save(handdrawn_image_path)Copy the code

Here you can make batch processing to hand drawn script, you can try.

3. Two-dimensional code of generative art

There are a number of qr code generation tools available. Python also has a qr code generation library – MyQR. You can add an image background to a QR code, which looks very interesting

Installing MyQR using PIP is very simple.

The library can be run in the command line, you only need to pass the url link, picture address and other parameters, you can generate the corresponding TWO-DIMENSIONAL code, two-dimensional code picture is saved in the current directory by default.

Command line input format:

Myqr url linkCopy the code

Such as:

myqr https://zhuanlan.zhihu.com/pydatalysis
Copy the code

Press Enter again, you can generate the corresponding link of the TWO-DIMENSIONAL code.

How do you merge images? Very simple, pass in the image address parameter ‘-p’

For example, if I have a picture of SpongeBob squarepants on disk D and the address is: d:\ hmpb.jpg, I pass in the parameter ‘-pd:\ hmpb.jpg ‘on the command line:

myqr https://zhuanlan.zhihu.com/pydatalysis -p d:\hmbb.jpg -c
Copy the code

Execute to generate the SpongeBob themed QR code shown above.

4. Generate id photos

There are two sets of code, pillow and RemoveBG, used to change the photo size and matting, respectively.

Here, REMOveBG uses AI technology. The edges of matting are soft and the effect is quite good.

Code:

# encoding= UTF-8 from PIL import Image from removebg import removebg # encoding= UTF-8 from PIL import Image 'PysKLJueeoyK9NbJXXXXXXXXX' def change_bgcolor(file_in, file_out, api_key, color): P, s = file_in.split(".") RMBG = RemoveBg(api_key, 'error.log') rmbg.remove_background_from_img_file(file_in) file_no_bg = "{}.{}_no_bg.{}".format(p, s, s) no_bg_image = Image.open(file_no_bg) x, y = no_bg_image.size new_image = Image.new('RGBA', no_bg_image.size, color=color) new_image.paste(no_bg_image, (0, 0, x, y), Save (file_out) # def change_size(file_in, file_out, width, height): image = Image.open(file_in) resized_image = image.resize((width, height), Image.ANTIALIAS) resized_image.save(file_out) if __name__ == "__main__": PNG 'file_out = 'E:\ girl_cutout. PNG' # change_size(file_in, file_out, width, Change_bgcolor (file_in, file_out, api_key, color)Copy the code

5. Generate a nine-grid image

There was a period of time when nine-grid pictures were popular in the circle of friends. That is, a picture was divided into nine pictures, which quickly stood out in the circle of friends. It looked particularly artistic and advanced. This grid can also be done in a variety of software, and can be written in less than 50 lines of code if implemented in Python.

Code:

PIL import Image import sys def fill_image(Image) def fill_image(Image) width, New_image_length = width if width > height else height # create a new image New_image = image.new (image.mode, (new_image_length, new_image_length), color='white') # Paste (image, (0, int((new_image_length-height) / 2))) else: paste(image, (0, int((new_image_length-height) / 2)) Paste (image, (int((new_image_length-width) / 2), 0)) def cut_image(image): paste(image, (int(new_image_length-width) / 2), 0)) Item_width = int(width / 3) box_list = [] for I in range(0, 3): for j in range(0, 3): box = (j * item_width, i * item_width, (j + 1) * item_width, (I + 1) * item_width) box_list.append(box) image_list = [image.crop(box) for box in box_list] return image_list # def save_images(image_list): index = 1 for image in image_list: Image. The save (' e: \ \ pictures \ \ '+ STR (index) +' PNG ', 'the PNG') index + = 1 if __name__ = = "__main__ ': File_path = "e:\\ \ image.jpg "image = image.open (file_path) # image.show() image = fill_image(image) image_list = cut_image(image) print(len(image_list)) save_images(image_list)Copy the code

# Write last:

So that’s it for some fun code to process images in Python! Python can also do a lot of interesting graphics, so you can try it out after you’ve learned a little bit. Of course, for novices, blindly contact with these fragments of small knowledge is obviously not enough, we still need a systematic, deep learning, so today xiaobian also sorted out some for everyoneNovice can learn from the learning materials, I hope to be helpful to you, private letter to me, I will share with people in need: The installation package

Video + materials

Finally, I hope you can be calm and persistent at the beginning of your Python learning journey. You can set an acceptable pace of learning and do not be impatient. I believe that with some accumulation, you will succeed in achieving your goals! I hope you can climb high and succeed!