如何在 except 中捕获 PIL.UnidentifiedImageError

Raj*_*ala 4 python error-handling

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

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)
Run Code Online (Sandbox Code Playgroud)

这给出了一个错误 -

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
Run Code Online (Sandbox Code Playgroud)

xav*_*avc 8

你得到的是NameError因为UnidentifiedImageError没有在你的命名空间中定义。通过检查文档,您可以看到您可以访问 中的异常PIL.UnidentifiedImageError,因此您可以插入

from PIL import UnidentifiedImageError
Run Code Online (Sandbox Code Playgroud)

在代码的开头,或者只是import PIL, 和

try:
    img_data = Image.open(BytesIO(img))
except PIL.UnidentifiedImageError:
    problem_files.append(path)
Run Code Online (Sandbox Code Playgroud)

最后,因为UnidentifiedImageError继承自OSError,所以您也可以编写except OSError:,尽管在指定要捕获的异常时最好是更窄而不是更宽,这样其他问题就不会被忽视,例如打开文件引发的其他异常。