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