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

批量调整文件夹内图片尺寸时触发IndexError: list index out of range错误

问题分析与修复

错误原因

  1. return语句缩进错误:return data写在了for循环内部,导致循环仅执行一次就直接返回结果。如果第一个文件读取失败,data会是空列表,后续访问data[0]必然触发IndexError。
  2. 无差别异常捕获:空的except:会吞掉所有错误,比如cv2.imread读取非图片文件返回None时,cv2.resize会报错,但错误被隐藏,无法定位问题。
  3. 未过滤非图片文件:os.listdir会返回文件夹内所有文件(包括文件夹、非图片格式文件),这类文件无法被cv2.imread正确读取,导致无效操作。

修复后的代码

import os
import cv2

def resize():
    data = []
    img_size = 244
    data_dir = r'C:\technocolab project2\archive'
    # 定义支持的图片格式
    valid_extensions = ('.png', '.jpg', '.jpeg', '.bmp', '.tiff')
    
    for img_name in os.listdir(data_dir):
        # 过滤非图片文件
        if not img_name.lower().endswith(valid_extensions):
            continue
        img_path = os.path.join(data_dir, img_name)
        try:
            images = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
            # 检查图片是否读取成功
            if images is None:
                print(f"无法读取图片: {img_path}")
                continue
            image_resized = cv2.resize(images, (img_size, img_size))
            data.append(image_resized)
        except Exception as e:
            # 打印具体错误信息,便于排查
            print(f"处理图片 {img_path} 时出错: {str(e)}")
    # 循环结束后再返回结果
    return data

data = resize()
print(f"成功处理的图片数量: {len(data)}")

if data:
    sample = data[0]
    print(sample.shape)
else:
    print("没有成功加载任何图片")

关键修改点

  • 将return data移到for循环外部,确保遍历完所有文件后再返回结果。
  • 添加图片格式过滤,只处理常见的图片文件。
  • 检查cv2.imread的返回值,避免对None进行resize操作。
  • 替换空except为except Exception as e,打印具体错误信息,方便排查问题。
  • 在访问data[0]前先判断data是否为空,避免索引越界。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 19:09:31