代码分析 关于看图像是否包括损坏

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()

相关推荐
plainGeekDev8 小时前
Gson → kotlinx.serialization
android·java·kotlin
神奇的程序员16 小时前
我的软件冲进苹果商店下载榜前 50 了
前端
小bo波16 小时前
Java Swing 图形用户界面实验 —— 从算术练习到游戏开发的完整实践
java·课程设计·gui·游戏开发·扫雷·swing
阳光是sunny17 小时前
别再被 worktree 绕晕了!AI 编程时代你必须掌握的 Git 隔离神器
前端·人工智能·后端
万少18 小时前
万少的博客 - 技术分享与解决方案
前端·javascript·后端
咖啡八杯18 小时前
GoF设计模式——备忘录模式
java·后端·spring·设计模式
尘世中一位迷途小书童20 小时前
用 Cesium 撸了一个森林火情监控大屏,弧线、粒子、发光效果都齐了
前端·javascript
IT_陈寒21 小时前
垃圾回收器选错了,我的Java服务内存炸了
前端·人工智能·后端
月光下的丝瓜21 小时前
Flutter 国内安装指南
前端·flutter