見出し画像

Figure + 画像 + 文字(matplotlib)

先日掲載した Figure への文字入れ図入れを組み合わせて、タイトル画像っぽいものが作れたので記録に残しておます。
文字は、path_effect という機能を使うことでフチ取りにすることができました(1番目のこコード)。
記事の見出し画像は、path_effect をかけた文字を重ねて、作成しました(2番目のコード)。
グラデーションのバックグラウンドも matplotlib で作成しましたが、Axes を使用したのと、コードが長くなってしまうので、気が向いたら後日別記事に残します。

#"path_effext.py"

import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
import matplotlib.patheffects as pe
from PIL import Image

font_files = fm.findSystemFonts(fontpaths="./")
for font_file in font_files:
    fm.fontManager.addfont(font_file)

width_px= 1280
height_px = 670

dpi = 300 #default value: 100

title="""文字のフチどりも
できたよ"""

width_inch = width_px / dpi
height_inch = height_px / dpi

fig = plt.figure(figsize = [width_inch, height_inch], dpi=dpi, facecolor="#99FFFF")

im = Image.open("./bgimage.png")

fig.figimage(im)

text = fig.text(0.5, 0.5, title, ha="center",va="center", ma="left", fontsize="36", fontname="IPAexGothic", linespacing=1.8, path_effects=[pe.withStroke(linewidth=3,
                                                        foreground="w")])

fig.savefig("path_effext.png")
path_effect.png
#"path_effext2.py"

import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
import matplotlib.patheffects as pe
from PIL import Image


font_files = fm.findSystemFonts(fontpaths="./")
for font_file in font_files:
    fm.fontManager.addfont(font_file)

width_px= 1280
height_px = 670

dpi = 300 #default value: 100

title1="matplotlib で"
title2="フチ文字"


width_inch = width_px / dpi
height_inch = height_px / dpi

fig = plt.figure(figsize = [width_inch, height_inch], dpi=dpi, facecolor="#99FFFF")

im = Image.open("./gradation_framespringalpha0_5and0_0.png")

fig.figimage(im)

fig.text(0.5, 0.7, title1, ha="center",va="center", ma="left", fontsize="24", fontname="IPAexGothic", linespacing=1.8)
fig.text(0.5, 0.35, title2, ha="center",va="center", ma="left", fontsize="36", fontname="IPAexGothic", linespacing=1.8, path_effects=[pe.withStroke(linewidth=10,
                                                        foreground="w")])
fig.text(0.5, 0.35, title2, ha="center",va="center", ma="left", fontsize="36", fontname="IPAexGothic", linespacing=1.8, path_effects=[pe.withStroke(linewidth=1,
                                                        foreground="black")])

fig.savefig("path_effext2.png")
path_effect2.png

参考URL:https://matplotlib.org/stable/gallery/misc/patheffect_demo.html

この記事が気に入ったらサポートをしてみませんか?