Search code examples
pythonimagebase64random-forestgraphviz

How can i convert type IPython.core.display.Image to base64 string using tempfile?


I am trying to visualize a Decision Tree from a Random Forest Classifier. However the type of the image that is being generated is of the type IPython.core.display.Image I wish to convert this into a base64 string by using the tempfile library

import tempfile
import base64
from IPython.display import Image  
from sklearn import tree
import pydotplus

dot_data = tree.export_graphviz(model.best_estimator_[0], out_file=None, 
                                feature_names=X_train.columns,  
                                class_names=unique_target)

graph = pydotplus.graph_from_dot_data(dot_data)  

# Show graph
image= Image(graph.create_png())

with tempfile.TemporaryFile(suffix=".png") as tmpfile:
    fig = image.get_figure()

"AttributeError: 'Image' object has no attribute 'get_figure'"

type(image)
Out[32]: IPython.core.display.Image


I am getting the error as:

"AttributeError: 'Image' object has no attribute 'get_figure'"

I am kind of lost on how to convert this into a base64 without explicitly saving the file.


Solution

  • It worked. I tried with a friend for a couple of hours.

    import base64
    from IPython.display import Image  
    from sklearn import tree
    import pydotplus
    
    dot_data = tree.export_graphviz(model.best_estimator_[0], out_file=None, 
                                    feature_names=X_train.columns,  
                                    class_names=unique_target)
    
    graph = pydotplus.graph_from_dot_data(dot_data)  
    
    
    image= Image(graph.create_png())
    
    Encoded_Image=str(base64.b64encode(image.data)) ##That's the line you add before you save it as an Encoded String
    

    There is no need to add the tempfile part of the code.