test000000

本文介绍了一个Python函数`validate_images`,用于在指定目录及其子目录中检查并验证图片文件(如.jpg,.jpeg等),捕获加载过程中出现的错误。它适用于检查图像数据集的完整性。
摘要由CSDN通过智能技术生成
import os
from PIL import Image


def validate_images(directory, recursive=True, extensions=None):
    if extensions is None:
        extensions = ('.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.gif')  # Add more extensions if needed

    error_log = []

    for root, dirs, files in os.walk(directory):
        if not recursive and root != directory:
            break

        for file in files:
            file_path = os.path.join(root, file)

            if file_path.endswith(extensions):
                try:
                    img = Image.open(file_path)
                    img.verify()  # Optionally verify that the image is intact (slower)
                    img.close()
                    print(f"Validated: {file_path}")
                except Exception as e:
                    error_log.append((file_path, str(e)))
                    print(f"Error loading image: {file_path} - {str(e)}")

    return error_log


if __name__ == "__main__":
    directory_to_validate = "../dataset/train2014"
    recursive_search = True  # Set to False to only check the specified directory (no subdirectories)

    error_log = validate_images(directory_to_validate, recursive=recursive_search)
    print("\nValidation complete.")

    if error_log:
        print("\nErrors encountered:")
        for file_path, error_msg in error_log:
            print(f"{file_path}: {error_msg}")
    else:
        print("No errors found.")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值