LoginSignup
7
8

More than 5 years have passed since last update.

Pythonを使った多言語テキスト画像の生成

Last updated at Posted at 2016-01-03

エクセルから様々な言語のテキストを読み込んで画像を生成する.

例として以下の様な画像を生成します.
فارسی.png

ipython notebookで実行例を公開.

言語リスト

アラビア語 カタロニア語 英語 スペイン語 ペルシア語 フランス語 イタリア語 韓国語 ロシア語 スウェーデン語 タイ語 ウクライナ語 中国語
العربية Català English Español فارسی Français Italiano 한국어 Русский Svenska ไทย Українська 中文
التعلم المتعمق Aprenentatge profund Deep learning Aprendizaje profundo یادگیری عمیق Deep learning Apprendimento approfondito 딥 러닝 Глубинное обучение Deep learning การเรียนรู้เชิงลึก Глибинне навчання 深度学习

スクリプト

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')

参考

7
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
8