0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python matplotlib : テキストを画像にする(表出力のイメージ)

Posted at

久々の投稿である。
ちょっとしたものを作ったので紹介する。

報告書に貼り付ける簡単な表を画像として作成したい場合の方法。
標準出力(ターミナルに print で出力)したものと同じ文字列を jpg 画像として保存する。
ターミナルに出力するための加工過程は省略する。

ターミナル出力のスクリーンショットが下の写真。
Screenshot 2025-06-19 at 15.26.47.png

作成したプログラムによる jpg画像が下のもの。
fig_frame_tbl_1.jpg

プログラムは以下の通り。

inp_dataで入力したテキストを一度ターミナルに出力し、文字列のリストをfig_tblに渡して画像出力する。余白ができるので、fig_trimで余白を削除して完成。

import matplotlib.pyplot as plt
from PIL import Image, ImageChops


def fig_trim(fig):
    def trim(im, border):
        bg = Image.new(im.mode, im.size, border)
        diff = ImageChops.difference(im, bg)
        bbox = diff.getbbox()
        return im.crop(bbox)

    img_org=Image.open(fig,'r')
    img_new=trim(img_org,'#ffffff')
    img_new.save(fig, 'JPEG', quality=100, optimize=True)


def fig_tbl(nnn,mlen,text):
    mrow=len(text)
    fsz=10
    xmin,xmax,dx=0,mlen,1
    ymin,ymax,dy=0,mrow,1
    iw=float(mlen)/10
    ih=float(mrow)/5
    plt.figure(figsize=(iw,ih),facecolor='w')
    plt.rcParams['font.size']=fsz
    plt.rcParams['font.family']='monospace'

    plt.xlim([xmin,xmax])
    plt.ylim([ymax,ymin])
    plt.axis('off')

    for i in range(0,mrow):
        xs,ys,ss=0,i+0.5,text[i]
        plt.text(xs,ys,ss,ha='left',va='center',fontsize=fsz)

    plt.tight_layout()
    fnameF='fig_frame_tbl_{0}.jpg'.format(nnn)
    plt.savefig(fnameF, dpi=200, bbox_inches="tight", pad_inches=0.1)
    return fnameF


def inp_data():
    s=[]
    s.append('-'*47)
    s.append('Equivalent stress      dismax    sige1    sige2')
    s.append('                         (mm)    (MPa)    (MPa)')
    s.append('-'*47)
    s.append('With water  D=1.9GPa   19.705   52.422  172.664')
    s.append('pressure    D=3.7GPa   10.996   45.719  169.683')
    s.append('-'*47)
    s.append('dismax : maximum displacement')
    s.append('sige1  : equivalent stress due to only concrete deformation')
    s.append('sige2  : equivalent stress including the effect of water pressure')
    s.append('For calculation of sige2, followings are assumed.')
    s.append('+ Hoop tension is reached to allowable stress of 175 MPa.')
    s.append('+ Poisson\'s stress of 0.3 x 175 MPa in axial direction is considered.')
    ss='\n'.join(s)
    print(ss)
    text=ss.split('\n')
    mlen=0
    for i in range(0,len(text)):
        k=len(text[i])
        if mlen<k: mlen=k
    print('mlen=',mlen)
    return mlen,text


def main():
    nnn=1
    mlen,text=inp_data()
    fnameF=fig_tbl(nnn,mlen,text)
    fig_trim(fnameF)


#---------------
# Execute
#---------------
if __name__ == '__main__': main()

以 上

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?