Convert text to image font in python,
The previous blog post mentioned how to get a Chinese Character Font. This article describes how to convert words into images one by one, which is useful in machine learning.
In a word, use pygame to render text to the image.
The code below.
Import osimport pygamechinese_dir = 'China' if not OS. path. exists (chinese_dir): OS. mkdir (chinese_dir) pygame. init () start, end = (0x4E00, 0x9FA5) # Chinese character encoding range: for codepoint in range (int (start), int (end): word = unichr (codepoint) font = pygame. font. font ("msyh. ttc ", 22) # The current directory must contain the font file msyh of. or go to the c: \ Windows \ Fonts directory to find rtext = font. render (word, True, (0, 0, 0), (255,255,255) pygame. image. save (rtext, OS. path. join (chinese_dir, word + ". png "))
The following figure shows the effect.