使用Google Colaboratory中的PIL无法从响应对象打开图像

时间:2019-07-17 20:14:50

标签: python python-3.x python-requests python-imaging-library google-colaboratory

我正在学习有关Udemy的“深度学习和计算机视觉PyTorch”课程,并按照指示将代码输入到Google Colaboratory。

但是,在代码的一部分中,PIL旨在从响应对象读取图像,但是我出现了错误“ AttributeError:无法设置属性”

我在python 3.6上使用枕头4.0.0 我曾尝试将resonse.raw更改为response.content,response.text和just response。我尝试删除stream = True属性,并尝试将网址直接输入Image.open方法

!pip3 install pillow==4.0.0

import PIL.ImageOps

import requests
from PIL import Image

url = 'https://c8.alamy.com/comp/DYC06A/hornless-reindeer-at-zoo-DYC06A.jpg'
response = requests.get(url, stream = True)
img = Image.open(response.raw)
plt.imshow(img)

我希望有一个带有鹿图像且url变量中有url的图。

相反,我收到此错误消息:

---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-85-059526041234> in <module>()
      4 url = 'https://c8.alamy.com/comp/DYC06A/hornless-reindeer-at-zoo-DYC06A.jpg'
      5 response = requests.get(url, stream = True)
----> 6 img = Image.open(response.raw)
      7 plt.imshow(img)

5 frames

/usr/local/lib/python3.6/dist-packages/PIL/Image.py in open(fp, mode)

/usr/local/lib/python3.6/dist-packages/PIL/Image.py in _open_core(fp, filename, prefix)

/usr/local/lib/python3.6/dist-packages/PIL/JpegImagePlugin.py in jpeg_factory(fp, filename)
    750 # Factory for making JPEG and MPO instances
    751 def jpeg_factory(fp=None, filename=None):
--> 752     im = JpegImageFile(fp, filename)
    753     try:
    754         mpheader = im._getmp()

/usr/local/lib/python3.6/dist-packages/PIL/ImageFile.py in __init__(self, fp, filename)
     95 
     96         try:
---> 97             self._open()
     98         except (IndexError,  # end of data
     99                 TypeError,  # end of data (ord)

/usr/local/lib/python3.6/dist-packages/PIL/JpegImagePlugin.py in _open(self)
    321                 # print(hex(i), name, description)
    322                 if handler is not None:
--> 323                     handler(self, i)
    324                 if i == 0xFFDA:  # start of scan
    325                     rawmode = self.mode

/usr/local/lib/python3.6/dist-packages/PIL/JpegImagePlugin.py in SOF(self, marker)
    144     n = i16(self.fp.read(2))-2
    145     s = ImageFile._safe_read(self.fp, n)
--> 146     self.size = i16(s[3:]), i16(s[1:])
    147 
    148     self.bits = i8(s[0])

AttributeError: can't set attribute

1 个答案:

答案 0 :(得分:0)

升级枕头为我解决了

pip install pillow --upgrade