import os
from PIL import Image
from tqdm import tqdm
def check_images(root_dir):
broken_files = []
for subdir, dirs, files in os.walk(root_dir):
for file in tqdm(files):
if file.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.bmp', '.gif')):
file_path = os.path.join(subdir, file)
try:
img = Image.open(file_path) # 打开图像
img.verify() # 验证图像完整性
except (IOError, SyntaxError) as e:
print(f'损坏的文件: {file_path}')
broken_files.append(file_path)
return broken_files
# 设置你的数据集目录
dataset_directory = 'path/to/your/dataset' # 替换为你的数据集路径
broken_files = check_images(dataset_directory)
# 可选:将损坏的文件列表保存到文本文件中
with open('broken_files.txt', 'w') as file:
for item in broken_files:
file.write("%s\n" % item)
print(f'检查完成。发现 {len(broken_files)} 个损坏的文件。')
for subdir, dirs, files in os.walk(root_dir):
– 这行代码使用 os.walk
函数遍历 root_dir
指定的根目录。os.walk
会生成一个三元组 (subdir, dirs, files)
,其中:
subdir
是当前正在遍历的子目录的路径。
dirs
是该子目录中所有子目录的名称列表(这个例子中未使用)。
files
是该子目录中所有文件的名称列表。
for file in tqdm(files):
– 这个循环遍历 files
列表中的每个文件名。tqdm
是一个进度条库,用于显示处理进度。
if file.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.bmp', '.gif')):
– 这个条件判断当前文件名(转换为小写)是否以常见的图像文件扩展名结束。这确保了只有图像文件被进一步处理。
file_path = os.path.join(subdir, file)
– 这行代码将子目录的路径和文件名组合成完整的文件路径。