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

运行OpenCV人脸识别训练代码触发PIL无法识别Thumbs.db错误如何解决

问题原因

你当前的代码在遍历dataset目录时没有过滤非图片格式文件,会将Windows系统自动生成的缩略图缓存文件Thumbs.db当作图片传入PIL加载,导致无法识别的报错。
报错截图

修复方案

方案1:添加图片后缀过滤(推荐)

修改getImagesAndLabels函数中生成imagePaths的逻辑,只保留常见图片格式的文件,避免加载无关文件。这里使用lower()做后缀小写转换,兼容大写后缀的图片(比如.JPG、.PNG),修改后的代码段如下:

def getImagesAndLabels(path):
    # 定义允许的图片后缀
    valid_extensions = ('.jpg', '.jpeg', '.png', '.bmp', '.pgm')
    # 遍历文件时只保留后缀符合的文件
    imagePaths = [os.path.join(path, f) for f in os.listdir(path) 
                  if f.lower().endswith(valid_extensions)]
    faceSamples = []
    ids = []

    for imagePath in imagePaths:

        PIL_img = Image.open(imagePath).convert('L')  # convert it to grayscale
        img_numpy = np.array(PIL_img, 'uint8')

        id = int(os.path.split(imagePath)[-1].split(".")[1])
        faces = detector.detectMultiScale(img_numpy)

        for (x, y, w, h) in faces:
            faceSamples.append(img_numpy[y:y + h, x:x + w])
            ids.append(id)

    return faceSamples, ids

该方案兼容性最好,除了Thumbs.db之外,其他非图片的无关文件也会被自动过滤。

方案2:单独排除Thumbs.db文件

如果你的数据集只有图片和Thumbs.db这一种无关文件,也可以直接过滤掉该文件名即可:

imagePaths = [os.path.join(path, f) for f in os.listdir(path) if f != 'Thumbs.db']

可选补充操作

你可以先手动删除dataset目录下已生成的Thumbs.db文件,也可以在Windows文件夹选项中关闭缩略图缓存自动生成功能,避免后续目录下再次生成该缓存文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 08:48:00