将python生成的base64图片,在浏览器上展示出来

2018/10/23 posted in  Python

方便调试

<!DOCTYPE html>
<html>
  <head>
    <title>show base64 pic</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  </head>
  <body>
    <div id='root'>
        <img src="data:image/png;base64,这里是base64的内容,替换掉即可(中文部分)" />
    </div>
  </body>
</html>
#!/usr/bin/env python 

import base64

import pandas as pd
import pydotplus
from IPython.display import Image
from sklearn import tree
from sklearn.tree import DecisionTreeClassifier

data = pd.read_csv("./datas/demos.csv")
train_data = data.drop("label", axis=1)
target = data["label"]

DTmodel = DecisionTreeClassifier(max_depth=4)
DTmodel = DTmodel.fit(train_data, target)
print(DTmodel)

# 将决策树的图片转成base64
dot_data = tree.export_graphviz(DTmodel, out_file=None)
graph = pydotplus.graph_from_dot_data(dot_data)
pic_base64 = base64.b64encode(Image(graph.create_png()).data).decode('utf8')

print(pic_base64)

将打印出来的pic_base64的内容替换到html里面的中文部分,然后用浏览器打开这个html文件即可看到图片