首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在except中捕获PIL.UnidentifiedImageError

如何在except中捕获PIL.UnidentifiedImageError
EN

Stack Overflow用户
提问于 2020-08-30 17:39:57
回答 1查看 2.3K关注 0票数 2

我有一个巨大的Zip文件,里面有数十万张图片。我正在尝试读取内存中的这些图像,并将像素数据提取到一个数组中。其思想是在模型构建中使用平面化的图像阵列。PIL.Image无法读取一些文件,在这种情况下会引发UnidenfitiedImageError。我想在try-except中捕获它,并将所有问题图像的路径放入一个单独的列表中。我是python和编程的新手。我尝试使用try-except子句,但它不起作用。请帮助:

代码语言:javascript
运行
复制
with ZipFile('/XXXXX/YYYYY/ZZZZZ/AI_ML/Project2/words.zip') as myzip:
  contents = myzip.namelist()
  for i in range(0,len(contents)-1):
    text = str(contents[i])
    if '.png' in text:
      if 'MACOSX' not in text:
        file_paths.append(contents[i])
  for path in file_paths:
    img = myzip.read(path)

    try:
      img_data = Image.open(BytesIO(img))
    except UnidentifiedImageError:
      problem_files.append(path)

    img_data = img_data.convert('L')              # 2
    image_as_array = np.array(img_data, np.uint8) # 3
    img_list.append(image_as_array)

这会产生一个错误-

代码语言:javascript
运行
复制
UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7f63ef5154c0>

During handling of the above exception, another exception occurred:

NameError                                 Traceback (most recent call last)
<ipython-input-8-23281c9e5d49> in <module>()
     16     try:
     17       img_data = Image.open(BytesIO(img))
---> 18     except UnidentifiedImageError:
     19       problem_files.append(path)
     20     img_data = img_data.convert('L')              # 2

NameError: name 'UnidentifiedImageError' is not defined
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-30 18:40:45

您将获得一个NameError,因为您的名称空间中没有定义UnidentifiedImageError。通过检查the documenation,您可以看到可以在PIL.UnidentifiedImageError中访问异常,因此您可以插入

代码语言:javascript
运行
复制
from PIL import UnidentifiedImageError

在代码的开头,或者只使用import PIL,以及

代码语言:javascript
运行
复制
try:
    img_data = Image.open(BytesIO(img))
except PIL.UnidentifiedImageError:
    problem_files.append(path)

最后,因为UnidentifiedImageError继承自OSError,所以您也可以编写except OSError:,尽管在指定要捕获哪些异常时最好缩小范围而不是扩大范围,这样其他问题就不会被忽略,比如打开文件引发的其他异常。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63656089

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档