import os
import argparse
from PIL import Image, UnidentifiedImageError
#进度条
from tqdm import tqdm
#读取的包括这里面的 jpg jpeg png bmp格式的
def check_image_folder(root_dir, extensions=('.jpg', '.jpeg', '.png', '.bmp')):
#给坏图像弄一个列表,总数设置为0
bad_images = []
total = 0
收集所有图像路径
image_paths = []
#os.walk(root_dir)这是一个生成器函数,它会递归遍历指定目录 (root_dir)及其所有子目录
#每次迭代返回三个值,当前遍历到的目录路径 _ 当前目录下的子目录列表(这里表示不关心,不需要,因为我只看文件夹中的图像是否有损坏) files当前目录下的文件列表
for root, _, files in os.walk(root_dir):
#遍历当前目录下的每一个文件名
for f in files:
#将文件名转化为小写,后面跟一个extensions 检查是不是以extensions中的任意一个后缀结尾,上面有写extensions
if f.lower().endswith(extensions):
#如果满足,将这个路径拼接好,加到列表中
image_paths.append(os.path.join(root, f))
print(f"🔍 Found {len(image_paths)} images in {root_dir}. Starting verification...")
#对于每一个列表中的
for img_path in tqdm(image_paths, desc="Checking images"):
try:
#image.open 使用pillow打开图像文件,image.open是默认延迟加载,只读取文件头信息,不立即读取像素数据
with Image.open(img_path) as img:
#img.load加载图像的全部像素数据,会触发图像完整性的检查,如果图像文件是截断的(或者结构损坏) 会抛出oserror
img.load() # 强制加载像素(触发 truncated 检测)
img.convert("RGB") # 模拟训练时的转换
except (OSError, UnidentifiedImageError, ValueError) as e:
bad_images.append((img_path, str(e)))#这个就是将坏图像存在bad_images列表中
except Exception as e:
bad_images.append((img_path, f"Unexpected error: {e}"))
return bad_images
def main():
parser = argparse.ArgumentParser(description="Check for corrupted or unreadable images in a dataset.")
parser.add_argument("root_dir", type=str, help="Root directory of the dataset (e.g., /path/to/train)")
parser.add_argument("--output", type=str, default="corrupted_images.txt", help="Output file to save bad image paths")
args = parser.parse_args()#命令行输入
bad_images = check_image_folder(args.root_dir)
#下面这部分就是打印前三个坏图像信息,如果没坏图像,就打印绿色对号
if bad_images:
print(f"\n⚠️ Found {len(bad_images)} problematic images. Saving list to {args.output}")
with open(args.output, "w") as f:
for path, err in bad_images:
f.write(f"{path}\t{err}\n")
print(f"First 3 bad images:")
for path, _ in bad_images[:3]:
print(f" - {path}")
else:
print("✅ All images loaded successfully! No corruption detected.")
if name == "main":
main()