我一直在努力使用 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),我一直使用的引用资料是:
- 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
最佳答案
您可以使用 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/