見出し画像

Figure に画像を貼り付ける(matplotlib)

引き続き Figure で遊んでいきます。
昨日は空のFigure に文字を書き入れてみましたが、図を直接貼り付けることもできるようです。Matplotlib は 画像処理に Pillow を利用しているそうで、Pillowで開いたり処理した画像をそのまま貼り付けられます。

#"Figure_with_Image.py"

import matplotlib.pyplot as plt
from PIL import Image

width_px= 1280
height_px = 670

dpi = 300 #default value: 100

width_inch = width_px / dpi
height_inch = height_px / dpi

fig = plt.figure(figsize = [width_inch, height_inch], dpi=dpi)

im = Image.open("./Figure_with_Text.png")
im_resized = im.resize((im.width//2, im.height//2))

fig.figimage(im_resized,50,50)
fig.figimage(im_resized.rotate(45,expand=True),200,-30)

fig.savefig("Figure_with_Image.png", backend="AGG")
Figure_with_image.png

入力画像には昨日作成したものを使い回しました。

Axes にも画像を貼り付けられますが、その場合はAxes のサイズに合わせて画像がリサンプリングされるという違いがあるようです。

文字も絵も入れられるとなると、プレゼン資料の作成や写真の文字入れなどができそうですね。

参考URL︰
https://matplotlib.org/stable/api/_as_gen/matplotlib.figure.Figure.figimage.html
https://pillow.readthedocs.io/en/stable/reference/Image.html



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