Home > Article > Backend Development > Detailed explanation of examples of adding Chinese characters to PILLOW pictures
Brief description
Preparation
Example
Rendering
Conclusion
I think when using opencv2 or 3 To add Chinese text to the picture, you need to download the Freetype library, compile it and link it to the opencv library to output Chinese. Most of the tutorials on inserting Chinese into pictures on the Internet are still win+vs configuration tutorials. For people like me who have an environment under win and an environment under linux, it is undoubtedly a bit troublesome to synchronize the code. Fortunately, there is an alternative, which is the example below: pillow.
pillow installation
couldn’t be simpler, you can install it as follows: pip install pillow
Orconda install pillow
The next font library that supports Chinese
Search keywords: ttf font. Download a font style library you like. The suffix of the file is generally ttf
. I downloaded a Microsoft Yahei library. The file name is msyh.ttf
First create a new python file: draw_chinese .py
. For sample code ipython-notebook style, please go here
1. Import library
import cv2from PIL import Image,ImageFont,ImageDrawfrom matplotlib.pyplot import imshowimport numpy as np
Image
: An instance of an object represents an image , you can perform some size transformation and affine transformation operationsImageFont
: Used to load the font library file downloaded in the preparation stageImageDraw
: Based on the image object, create an An object that can draw lines and paste text on Image
instances.
2. Create a picture
img = Image.new(mode="RGB",size=(400,150),color=(120,20,20)) #或者从numpy对象中创建也行。可以把opencv的图片转为numpy,通过numpy连接两个图像处理库。 #img = Image.fromarray(numpy_object) img.show()
3. Load the font library
path_to_ttf = r'data/msyh.ttf' font = ImageFont.truetype(path_to_ttf, size=25) #size 确定一个汉字的大小
4. Create a new canvas
draw = ImageDraw.Draw( img )
6 .Do whatever you want on the canvas
draw.text(xy=(30,30),text='Hello,南墙已破!',font=font) img.show() #当然也可以把这个写好字的图片转换回numpy #img2array = np.asanyarray(img)
pillow is a library that can do some of the work of opencv. So far, I have found a setting that is commonly used but does not exist in pillow. When drawing a rectangular frame, you cannot set the width of the rectangular frame edges. You need to implement it manually: each time based on the original Increase or decrease the coordinate position of a pixel to repeat the frame to achieve the effect of increasing the width. Opencv only needs to give a width parameter.
The above is the detailed content of Detailed explanation of examples of adding Chinese characters to PILLOW pictures. For more information, please follow other related articles on the PHP Chinese website!