如何将从url检索到的图像放入图像小部件

2024-10-06 09:44:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我找到了这个代码,它工作得很好。可以检索和显示图像

import IPython
url = 'https://newevolutiondesigns.com/images/freebies/colorful-background-14.jpg'
IPython.display.Image(url, width = 250)

但是,我实际上想将图像放入图像小部件中,因此我尝试了以下方法:

import IPython
from ipywidgets import widgets

url = 'https://newevolutiondesigns.com/images/freebies/colorful-background-14.jpg'
image = IPython.display.Image(url, width = 300)

widgets.Image(
  value=image,
  format='jpg', 
  width=300,
  height=400,
)

但我有一个错误:

---------------------------------------------------------------------------
TraitError                                Traceback (most recent call last)
<ipython-input-45-5011b6084128> in <module>()
     57     format='jpg',
     58     width=300,
---> 59     height=400,
     60 )

________________________________________
7 frames
________________________________________
/usr/local/lib/python3.6/dist-packages/traitlets/traitlets.py in error(self, obj, value)
    623             e = "The '%s' trait must be %s, but a value of %r was specified." \
    624                 % (self.name, self.info(), repr_type(value))
--> 625         raise TraitError(e)
    626 
    627     def get_metadata(self, key, default=None):

TraitError: The 'value' trait of an Image instance must be a bytes object, but a value of 
<IPython.core.display.Image object> <class 'IPython.core.display.Image'> was specified.

所以,我的问题是:如何将图像放入图像小部件中


Tags: ofhttps图像imageimportselfcomurl
1条回答
网友
1楼 · 发布于 2024-10-06 09:44:07

首先,感谢您提供的示例

错误会告诉您需要做什么。您需要将映像文件的bytes传递给ipywidgets.Image类。通过从Ipython.display.Image实例传递image.data来实现这一点

import IPython
from ipywidgets import widgets

url = 'https://newevolutiondesigns.com/images/freebies/colorful-background-14.jpg'
image = IPython.display.Image(url, width = 300)

widgets.Image(
  value=image.data,
  format='jpg', 
  width=300,
  height=400,
)

或者,使用类似requests的包获取映像的bytes,并将它们传递给widgets.Image,而不需要Ipython.display.Image实例

相关问题 更多 >