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)

 

  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 14
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值