损坏的 JPEG 数据:标记 0xd9 之前有 214 个无关字节,但没有 JPEG 图像

问题描述 投票:0回答:1

我正在使用下面的代码,并且我确信我的 data_dir 没有任何 jpeg 图像,全部为 jpg 格式。但不确定是否存在损坏的 JPEG 数据错误。

#image standard
image_exts = ['jpeg','jpg', 'bmp', 'png']
#remove the image which outside the standard
for image_class in os.listdir(data_dir): #looping through every single of directory (cat/dog)
    for image in os.listdir(os.path.join(data_dir, image_class)): #loop through every single image inside the subdir
        #join -> data->cat, data->dog
        image_path = os.path.join(data_dir, image_class, image) #grabbing every single image
        try: 
            img = cv2.imread(image_path) #allow open up an image
            tip = imghdr.what(image_path) #check the type of img
            if tip not in image_exts: 
                print('Image not in ext list {}'.format(image_path))
                os.remove(image_path) #if not a valid image, extension-> delete the file
        except Exception as e: 
            print('Issue with image {}'.format(image_path))
            # os.remove(image_path)

python image error-handling jpeg jupyter-lab
1个回答
0
投票

您共享的代码旨在迭代图像目录并删除不在指定图像扩展名列表中的任何文件 (

image_exts
)。但是,有一些潜在问题可能会导致错误:

  1. 未定义的变量:确保

    data_dir
    变量已定义并指向包含图像子目录的正确目录。

  2. 不正确的图像扩展名:

    image_exts
    列表包含“jpeg”、“jpg”、“bmp”和“png”。确保您的所有图像都具有这些扩展名之一。此外,
    imghdr.what()
    函数返回小写的扩展名,因此请确保
    image_exts
    中的扩展名也是小写的。

  3. 损坏或不受支持的图像:如果图像损坏或格式不受支持,则

    cv2.imread()
    功能可能无法读取图像。这可能会导致引发异常。您可能需要添加更详细的错误处理,以查看图像发生的具体问题。

  4. 文件权限问题:如果脚本没有删除目录中文件的权限,则在尝试删除图像时可能会引发异常。确保脚本具有必要的权限。

  5. 目录结构:确保您的

    data_dir
    包含子目录(例如“cat”、“dog”),并且每个子目录都包含图像。如果结构不同,您可能需要相应地调整代码。

如果您遇到特定的错误消息,请提供它,我可以

© www.soinside.com 2019 - 2024. All rights reserved.