Generating multilingual text images using Python

Images are generated by reading texts in various languages from Excel.

As an example, the following image is generated. فارسی.png

An execution example is published in ipython notebook.

Language list

Arabic Catalan English Spanish Persian French Italian Korean < th> Russian Swedish Thai Ukrainian Chinese
العربية Català English Español فارسی Français Italiano 한국어 Русский Svenska ไทย Українська Chinese
التعلم المتعمق Aprenentatge profund Deep learning Aprendizaje profundo یادگیری عمیق Deep learning Apprendimento approfondito 딥 러닝 Глубинное обучен Deep learning d> การ เรียนรู้ เชิงลึก Глибинне навчання Deep Learning

script

python


from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import numpy as np
import pandas as pd

#Load text list
df = pd.read_excel('example_words.xlsx', sheetname='Sheet1')
indices = df.columns.tolist()

#Generate text images
def generate_text_img(text, fontname='Arial', fontsize=64):
    font = ImageFont.truetype(fontname, fontsize, encoding="utf-8")
    img_size = np.ceil(np.array(font.getsize(text))*1.1).astype(int)
    img=Image.new('L', img_size, 'white')
    draw = ImageDraw.Draw(img)
    text_offset = (img_size - font.getsize(text))/2
    draw.text(text_offset, text, font=font, fill='#000')
    return img
    
fontname = '/Library/Fonts/Arial Unicode.ttf'
for index in indices:
    for text in df[index]:
        txt_img = generate_text_img(text, fontname=fontname, fontsize=64)
        txt_img.save(text+'.png', 'png')

reference

Recommended Posts