You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

图片损坏检测异常:正常图片均被判定为损坏,求问题排查

问题分析与修复方案
  • 核心错误:传入错误的文件名参数
    你的循环里调用verify_image('image')时,传的是字符串'image',不是循环变量image。函数每次都在尝试打开一个名为image的文件,这个文件不存在,所以每次都会触发异常返回False。

  • 次要问题:图片验证不彻底
    PIL的Image.open()是懒加载机制,仅读取文件头,不会立即加载所有像素数据。有些损坏的图片能通过Image.open()但实际数据已损坏,需要额外步骤验证完整性。


修正后的代码

import glob
from PIL import Image
import os

directory = r'C:\Users\Jim Schmitz\Documents\Pyro\dogs-vs-cats\train\dogs'
os.chdir(directory)

images = glob.glob("*.jpg")

def verify_image(img_file):
    try:
        img = Image.open(img_file)
        # 验证文件结构完整性
        img.verify()
        # verify后图片对象无法再加载,需重新打开
        img = Image.open(img_file)
        # 强制加载所有像素,确认数据正常
        img.load()
        return True
    except Exception as e:
        print(f"图片 {img_file} 损坏或无法打开: {e}")
        return False
    
for image in images:
    result = verify_image(image)
    print(f"图片 {image} 验证结果: {result}")

内容的提问来源于stack exchange,提问作者keith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 01:09:52