PythonがPILを介して画像を読み取ると、エラーが報告されます:OSError:画像ファイルを識別できません



When Python Reads Picture Through Pil



原因:オペレーティング・システムは、指定されたタスク(ファイルを開くなど)を実行できませんでした。
多数の画像を処理するためにここにいますが、一部の画像を開くことができないため、OSErrorエラーが発生します。

解決策:tryacceptを使用してこの例外を解決します。この画像を直接削除することもできます。



import os from PIL import Image import shutil '''train''' Path = '/Users/xuqiong/AgeGender/test_img_process/1_allface/valid/' # indicates the folder that needs to be named pathnew = '/Users/xuqiong/AgeGender/test_img_process/2_allcrop/valid/' Filelist = os.listdir(path) #Get the file 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)