我使用此代码通过 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/