InvalidArgumentError: Invalid PNG(JPG). Failed to initialize decoder. [[{{node DecodePng}}]]

**

InvalidArgumentError: Invalid PNG(JPG). Failed to initialize decoder. [[{{node DecodePng}}]] [[IteratorGetNext]] [Op:__inference_train_function_10350]

出现这种文件,是因为文件中的png(jpg)图片出错,或者说不完整,把文件中出错的图片删除即可,代码如下:

import os,glob



def is_valid_jpg(jpg_file):
    with open(jpg_file, 'rb') as f:
        f.seek(-2, 2)
        buf = f.read()
        return buf ==  b'\xff\xd9'

def is_valid_png(png_file):
    with open(png_file, 'rb') as f:
        f.seek(-2, 2)
        buf = f.read()
        return buf == b'\x60\x82'

        

if __name__ == "__main__":
    
    png_path = glob.glob('/home/china/图片/*.png')
    jpg_path = glob.glob('/home/china/图片/*.jpg')
    print('png_num:', len(png_path), 'jpg_num:', len(jpg_path))
    
    
    for file_name in png_path:
        # 不是完整的png文件,打印路径,并删除
        
        if not is_valid_png(file_name):
            print(file_name)
            #os.remove(file_name)
            
    for file_name in jpg_path:
        # 不是完整的jpg文件,打印路径,并删除
        
        if not is_valid_jpg(file_name):
            print(file_name)
            #os.remove(file_name)
    


你可能感兴趣的:(python,tensorflow,python)