Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display table with text and images in Jupyter notebook?

I would like to display image samples and some related textual information with them, in table.

Is it possible to do this in jupyter notebook?

I tried to mix pandas and PIL, but it didn't work:

import pandas as pd
d = {
    'band1': data.to_images(band_1[random_indices]),
    'band2': data.to_images(band_2[random_indices]),
    'is_iceberg': is_iceberg[random_indices]
    }
pd.DataFrame(data=d)

output was

enter image description here

i.e. it displayed __str__ of images, not images themselves.

How to overcome?

like image 933
Dims Avatar asked Nov 04 '17 18:11

Dims


1 Answers

How about this?

I'm sure that setting escape in to_html is somewhat of a security risk maybe but if you know the data and know where it is coming from it is hopefully not that bad. If you change escape to True it will not work because the html is escaped by pandas. And this sets the same image in every row but that can be easily adjusted.

from IPython.core.display import display, HTML
import pandas as pd
data = pd.DataFrame({"A":[1,2,3,4,5], "B":[10,20,30,40,50]})
data.loc[:,'img'] = '<img src="Pictures/Capture.PNG" alt="img">'
display(HTML(data.to_html(escape=False)))

[EDIT] A better alternative would be

from IPython.core.display import display, HTML
from PIL import Image
import cStringIO
import base64
import pandas as pd

img = Image.open("Pictures/Capture.PNG")
img_buffer = cStringIO.StringIO()
img.save(img_buffer, format="PNG")
imgStr = base64.b64encode(img_buffer.getvalue())

data = pd.DataFrame({"A":[1,2,3,4,5], "B":[10,20,30,40,50]})
data.loc[:,'img'] = '<img src="data:image/png;base64,{0:s}">'
html_all = data.to_html(escape=False).format(imgStr)
display(HTML(html_all))

enter image description here

like image 141
Tasko Olevski Avatar answered Nov 14 '22 21:11

Tasko Olevski