无法加载图像时继续处理

Continue processing when image cannot be loaded

在 Python 中,我正在使用 wand 获取 exif 数据(图像创建的真实日期),并获取图像的高度和宽度以传递给命令行。这就是我使用魔杖的全部目的。一切正常,除非脚本遇到包含错误数据的图像,这在处理 250,000 多张图像时必然会发生。当文件本身损坏时,会导致整个脚本失败。我需要找到一种方法,即使无法正确加载图像,也能让脚本继续执行。

我正在使用以下导入

import inspect, os, shutil, datetime, time, string, configparser, fnmatch,  os, MySQLdb, sys, ntpath, math
import MySQLdb.cursors as cursors
from wand.image import Image
from wand.display import display
from tendo import singleton

这是失败的行:

with Image(filename=file_original_path) as image:

这是追溯:

Traceback (most recent call last):
  File "process-files.py", line 244, in <module>
    main()
  File "process-files.py", line 216, in main
    with Image(filename=file_original_path) as image:
  File "/home/pc/.local/lib/python2.7/site-packages/wand/image.py", line 2744, in __init__
    self.read(filename=filename, resolution=resolution)
  File "/home/pc/.local/lib/python2.7/site-packages/wand/image.py", line 2822, in read
    self.raise_exception()
  File "/home/pc/.local/lib/python2.7/site-packages/wand/resource.py", line 222, in raise_exception
    raise e
wand.exceptions.CoderError: Not a TIFF or MDI file, bad magic number 1280 (0x500). `assets/output/27/original.tif' @ error/tiff.c/TIFFErrors/566
Exception TypeError: TypeError("object of type 'NoneType' has no len()",) in <bound method Image.__del__ of <wand.image.Image: (empty)>> ignored

顺便说一句,除了通过之外的尝试也没有用。谢谢。

try/except 有效,不会导致整个脚本失败。

import traceback
from wand.image import Image
from wand.display import display

def doSomething(f):
    _status = 'error'
    try:
        print "processing file: %s" % f
        with Image(filename=f) as image:
            print image
        _status = 'processed'
    except:
        traceback.print_exc()
    finally:
        return _status

if __name__ == '__main__':
    result = {}
    images = ['/tmp/foo.png', '/tmp/bar.png', '/usr/share/locale/kde4/l10n/cf/flag.png']

    for i in images:
        status = doSomething(i)
        result[i] = status
    print result

输出:{'/tmp/foo.png': 'error', '/usr/share/locale/kde4/l10n/cf/flag.png': 'processed', '/tmp/bar.png': 'error'}

错了...除了通过之外的尝试确实奏效了。混淆相似的回调。