Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image upload in Jupyter Notebook using ipywidgets.FileUpload()

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:

  • Extracting text from MS Word Document uploaded through FileUpload from ipyWidgets in Jupyter Notebook
  • https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20List.html#File-Upload
  • Access the content from multiple uploaded files from ipywidgets FileUpload
  • https://github.com/jupyter-widgets/ipywidgets/pull/2258
like image 432
Angel Leon Avatar asked Oct 28 '25 10:10

Angel Leon


1 Answers

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>
like image 57
kHarshit Avatar answered Oct 30 '25 14:10

kHarshit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!