Python PIL - 属性错误: 'NoneType' object has no attribute 'save'

标签 python border python-imaging-library crop trim

我使用此代码通过 PIL 删除图像的边框:

def RemoveBlackBorders(img):
    bg = Image.new(img.mode, img.size, img.getpixel((0,0)))
    diff = ImageChops.difference(img, bg)
    diff = ImageChops.add(diff, diff, 2.0, -100)
    bbox = diff.getbbox()
    if bbox:
        return img.crop(bbox)

来自here

我用它来处理文件夹中包含的所有图像:

def CropImages():
    global FOLDER
    for i in range(1, len(os.listdir(FOLDER))+1):
        image = FOLDER + "\\" + str(i) + ".jpg"
        img = Image.open(image)
        img = RemoveBlackBorders(img)
        img.save(image, "JPEG")

一切正常,程序完成了他的工作。问题是,如果文件夹中有全黑图像(被检测为“边框”),程序就会卡住并给出错误:

 AttributeError: 'NoneType' object has no attribute 'save'

文件夹中的任何图像都不会被裁剪,即使黑色图像是该系列的最后一张图像。有没有办法跳过此图像或将其删除(这会更好)?

最佳答案

Python原理EAFP可以在这里申请。

基本上,您应该让代码尝试执行,然后捕获 AttributeError,告诉它跳过该图像。

像这样:

def CropImages():
    global FOLDER
    for i in range(1, len(os.listdir(FOLDER))+1):
        image = FOLDER + "\\" + str(i) + ".jpg"
        img = Image.open(image)
        img = RemoveBlackBorders(img)

        try:
            img.save(image, "JPEG")
        except AttributeError:
            print("Couldn't save image {}".format(image))

这只是意味着,如果它发现该错误,它将打印该消息,然后继续循环其余部分。

关于Python PIL - 属性错误: 'NoneType' object has no attribute 'save' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30327423/

相关文章:

python - 没有名为 PIL 的模块

python - 如何从不是 django 项目文件夹的文件夹运行 gunicorn

python - 动态创建文件的缓存系统?

javascript - 悬停时动画菜单边框

html - Div 未与其他内容对齐但仍在包装器中

python - 如何将原始 .NEF 文件加载到 QImage 中而不将其保存在 Python 中

Python 3.3 TKinter 图像不存在

python - 在 Cassandra 中只保留最新的 N 行

python - 在 Django 翻译 (.po) 文件中指定版权和作者

css - IE 中的边框缺口