LoginSignup
7
7

More than 5 years have passed since last update.

Dot言語で記述されたファイルをPythonのpydotで画像化する

Posted at

Chainerのextensions.dump_graphを利用するとDot言語で記述されたファイルを出力してくれる。このDotファイルはgraphvizで画像化できるが、今回はPythonを利用して画像化する。

動作環境

  • Ubuntu 16.04
  • Python 3.5.2
  • graphviz
  • pydot

使用例

以下はMNIST実行時に生成されたDotファイルを可視化した結果

コード

複数のDotファイルを読み込みたかったので、入力はDotファイルのファイルパスのリスト。extは使用する拡張子で、png、pdf、svg形式での出力に対応している。

import os
import pydot

def main(name_list, ext):
    for name in name_list:
        # dot言語で記述されたファイルを読み込む
        (graph,) = pydot.graph_from_dot_file(name)
        # 保存用の名前を抽出する
        name, _ = os.path.splitext(os.path.basename(name))
        # 形式を選択して保存する
        if(ext == 'png'):
            graph.write_png(getFilePath(args.out_path, name, '.png'))
        elif(ext == 'pdf'):
            graph.write_pdf(getFilePath(args.out_path, name, '.pdf'))
        elif(ext == 'svg'):
            graph.write_svg(getFilePath(args.out_path, name, '.svg'))
        else:
            print('[ERROR] ext option miss:', args.ext)

getFilePathはos.path.joinのオレオレラッパーなので不要な場合は置き換えて問題なし。

def getFilePath(folder, name, ext):
    if not os.path.isdir(folder):
        os.makedirs(folder)

    return os.path.join(folder, name + ext)
7
7
2

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
7