jupyter-notebook - 使用 ipywidgets.FileUpload() 在 Jupyter Notebook 中上传图片

标签 jupyter-notebook ipywidgets gcp-ai-platform-notebook

我一直在努力使用 ipywidgets.FileUpload() 将图像上传到我的 Jupyter 笔记本中,它对文本文件工作正常,但对于二进制文件,内容总是损坏。特别是对于图像,它们总是存储为“数据”,因此 keras.preprocessing.image.load_img() 无法使用它们。我使用的代码是:

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'])

我尝试了多种解决方案,但没有任何方法可以处理二进制文件,任何提示或帮助都很受欢迎。我的环境是 GCP AI Platform Notebooks(JupyterLabs 1.2.16,ipywidgets 7.5.1),我一直使用的引用资料是:

最佳答案

您可以使用 PIL 或任何其他带有 io.BytesIO 的库以字节数据读取图像。然后,将图像传递给 Keras。例如

import io
from PIL import Image

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

输出:

<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=430x128 at 0x7FBC8AAD9310>

关于jupyter-notebook - 使用 ipywidgets.FileUpload() 在 Jupyter Notebook 中上传图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62492878/

相关文章:

python - 在前进到下一个单元之前,强制 matplotlib 在 IPython/Jupyter 笔记本单元中完全渲染绘图

python - 如何在 Jupyter-notebook Markdown 代码片段中使用 $

r - 谷歌云AI平台jupyter notebook实例重启后也打不开,正在运行

google-cloud-platform - AI平台笔记本虚拟机 `jupyter`用户默认密码是多少?

html - <code> 标签在 ipython notebook 中的样式不正确

python - Ipywidgets 生态系统中用于中断循环的停止按钮

python - 每次运行时清除小部件以前的输出

python - 如何使用谷歌云自动化我的 jupyter 笔记本?

jupyter-notebook - Jupyter Notebook 幻灯片离线