4

I have been struggling to upload images into my Jupyter notebook using ipywidgets.FileUpload(), it works ok with text files but with binary files the content is always corrupted. Particularly with images, those are always stored as "data" so keras.preprocessing.image.load_img() is unable to use them. The code I am using is:

import ipywidgets as widgets

uploader = widgets.FileUpload()
uploader

for name, file_info in uploader.value.items():
    with open(name, 'wb') as fp:
        fp.write(file_info['content'])

I have tried multiple solutions but nothing is working with binary files, any hint or help is well received. My environment is GCP AI Platform Notebooks (JupyterLabs 1.2.16, ipywidgets 7.5.1) and the references I have been using are:

Angel Leon
  • 101
  • 2
  • 5

1 Answers1

5

You can read the image in bytes data using PIL or any other library with io.BytesIO. Then, pass the image to Keras. e.g.

import io
from PIL import Image

for name, file_info in uploader.value.items():
    img = Image.open(io.BytesIO(file_info['content']))
    
print(img)

Output:

<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=430x128 at 0x7FBC8AAD9310>
gaya
  • 463
  • 2
  • 6
  • 22
kHarshit
  • 11,362
  • 10
  • 52
  • 71
  • It didn't work, same problem, Image.open() is unable to identify the format. I think the problem is within the ipywidgets.FileUpload() function. Error message: ` ---> 13 img = Image.open(io.BytesIO(file_info['content'])) UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7f752e149e90> ` – Angel Leon Jun 22 '20 at 03:05
  • Strange, it works fine on my system as well as on colab, can you try https://stackoverflow.com/questions/23587426/pil-open-method-not-working-with-bytesio and https://stackoverflow.com/questions/31077366/pil-cannot-identify-image-file-for-io-bytesio-object – kHarshit Jun 22 '20 at 04:53