LoginSignup
1
2

More than 5 years have passed since last update.

Jupyterで文字列から画像を生成する

Posted at

インストールされているフォントの確認

in[1]

JupyterNotebook

import matplotlib.font_manager as fm

fonts = fm.findSystemFonts()
for f in fonts:
    font = fm.FontProperties(fname=f)
    print(f, font.get_name())

out[1]

/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf DejaVu Sans Mono
/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf DejaVu Sans
/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf DejaVu Sans Mono
/usr/share/fonts/truetype/dejavu/DejaVuSerif-Bold.ttf DejaVu Serif
/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf DejaVu Sans
/usr/share/fonts/xkcd.otf xkcd
/usr/share/fonts/truetype/dejavu/DejaVuSerif.ttf DejaVu Serif

この出力はPynqでの実行結果なのでインストールされているフォントが少ないです.

文字列から画像に変換

in[2]

JupyterNotebook
import IPython
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

import numpy

text = "Helo, world!"

image = Image.new("RGBA", (400, 300))
draw = ImageDraw.Draw(image)
draw.font = ImageFont.truetype("/usr/share/fonts/truetype/DejaVuSans.ttf", 48)

image_size = numpy.array(image.size)
text_size = numpy.array(draw.font.getsize(text))
position = (image_size - text_size) / 2

draw.text(position, text, (0, 0, 0))

表示

in[3]

JupyterNotebook
image.save("image.png")
IPython.display.Image("image.png")

out[3]

Hello.png

1
2
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
1
2