我正在进行机器学习项目,我在使用Python和PIL时遇到了一些麻烦。 我从谷歌下载了一些图片,我正在尝试使用PIL调整大小,但我收到了一个错误,我不明白,我不知道该怎么办。
path = '.../Dataset'
for folder_name in breeds:
for image in os.listdir(path + '/' + folder_name):
img = Image.open(path + '/' + folder_name + '/' + image)
new_width = 200
new_height = 200
img = img.resize((new_width, new_height), Image.ANTIALIAS)
img = img.convert("RGB")
img.save(path + '/' + folder_name + '/' + image)
我想加载图像然后调整大小,以便我拥有的所有图像都是固定大小的(200,200)。 (我使用爬虫下载的所有图像至少为200x200)。 我得到了一些奇怪的错误,但谷歌后,我看到我必须将图像转换为RGB。 之后我尝试保存它。在像30-40k图像处理后,我收到了这个错误:
.../.local/lib/python3.6/site-packages/PIL/Image.py:916: UserWarning: Palette images with Transparency expressed in bytes should be converted to RGBA images
'to RGBA images')
.../.local/lib/python3.6/site-packages/PIL/TiffImagePlugin.py:742: UserWarning: Corrupt EXIF data. Expecting to read 12 bytes but only got 6.
warnings.warn(str(msg))
.../.local/lib/python3.6/site-packages/PIL/TiffImagePlugin.py:742: UserWarning: Corrupt EXIF data. Expecting to read 12 bytes but only got 10.
warnings.warn(str(msg))
---------------------------------------------------------------------------
OSError Traceback (most recent call last)
<ipython-input-3-6016015ffe6f> in <module>()
6 new_width = 200
7 new_height = 200
----> 8 img = img.resize((new_width, new_height), Image.ANTIALIAS)
9 img = img.convert("RGB")
10 img.save(path + '/' + folder_name + '/' + image)
~/.local/lib/python3.6/site-packages/PIL/Image.py in resize(self, size, resample, box)
1743 return self.convert('RGBa').resize(size, resample, box).convert('RGBA')
1744
-> 1745 self.load()
1746
1747 return self._new(self.im.resize(size, resample, box))
~/.local/lib/python3.6/site-packages/PIL/ImageFile.py in load(self)
231 else:
232 raise IOError("image file is truncated "
--> 233 "(%d bytes not processed)" % len(b))
234
235 b = b + s
OSError: image file is truncated (9 bytes not processed)
任何想法如何处理? 谢谢!
答案 0 :(得分:0)
你当然可以捕获抛出的OSError,如下所示:
#!/usr/bin/env python3
from PIL import Image
import os
try:
fn = "earthmap.tiff"
im = Image.open(fn)
im = im.resize(200, 200)
im.save("eartmap-output.tiff")
except OSError:
print(f"Error processing '{fn}', deleting...")
os.unlink(fn)