python通过PIL读入图片时,报错:OSError: cannot identify image file

出现原因:操作系统不能执行指定的任务(如打开文件)时引发的。
我这里,是要处理大量的图片,然而有的图片无法打开,所以会出现OSError错误。

解决办法:使用try accept解决这个异常。也可以直接将这个图片删除。

import os
from PIL import Image
import shutil

'''train'''
path = '/Users/xuqiong/AgeGender/test_img_process/1_allface/valid/'  #表示需要命名处理的文件夹
pathnew = '/Users/xuqiong/AgeGender/test_img_process/2_allcrop/valid/'
filelist = os.listdir(path) #获取文件路径
#cbox = [0,0,0,0]
i = 0
for item in filelist:
    i = i + 1
    if i%500 == 0:
        print(i)
    if item == '.DS_Store':
        continue
    imgpath = path+item
    imgpathnew = pathnew + item

    try:
        img = Image.open(imgpath)
        h = img.height
        w = img.width

        if (h > 5*w) or (w > 5*h):
            os.remove(imgpath)
            continue
        else:
            shutil.move(imgpath, imgpathnew)

    except(OSError, NameError):
        print('OSError, Path:',imgpath)

猜你喜欢

转载自blog.csdn.net/weixin_41770169/article/details/87940744