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

缩减UTKFace数据集后遇IndexError: list index out of range报错求助

问题分析与解决

报错IndexError: list index out of range的核心原因是部分文件不符合预期的"年龄_性别_..."命名格式,或是目录中存在非图片文件(比如隐藏文件、子文件夹),导致img.split("_")得到的列表长度不足2,访问索引0或1时触发越界。

修复后的代码

import os
import cv2
import numpy as np
from sklearn.model_selection import train_test_split

path = "/content/drive/MyDrive/Colab Notebooks/UTKFace/UTKFace"
images = []
age = []
gender = []

# 定义支持的图片格式
valid_extensions = ('.jpg', '.jpeg', '.png', '.bmp')

for img_name in os.listdir(path):
    # 跳过非图片文件
    if not img_name.lower().endswith(valid_extensions):
        continue
    # 拆分文件名,先判断格式是否合法
    parts = img_name.split("_")
    if len(parts) < 2:
        print(f"跳过格式异常的文件: {img_name}")
        continue
    try:
        ages = int(parts[0])
        genders = int(parts[1])
    except ValueError:
        print(f"跳过年龄/性别无法转换为数字的文件: {img_name}")
        continue
    # 读取并处理图片
    img_path = os.path.join(path, img_name)
    img = cv2.imread(img_path)
    if img is None:
        print(f"无法读取图片: {img_name}")
        continue
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    images.append(img)
    age.append(ages)
    gender.append(genders)

# 转换为数组并完成图片缩放
age = np.array(age, dtype=np.int64)
images = np.array(images) / 255.0  # 按提示完成归一化缩放
gender = np.array(gender, dtype=np.uint64)

# 划分数据集
x_train_age, x_test_age, y_train_age, y_test_age = train_test_split(images, age, random_state=42)
x_train_gender, x_test_gender, y_train_gender, y_test_gender = train_test_split(images, gender, random_state=42)

关键修复点

  • 增加图片格式过滤,只处理常见图片后缀的文件,避免目录中其他文件干扰
  • 对文件名拆分结果做长度判断,跳过格式异常的文件
  • 增加异常捕获,处理年龄/性别无法转为数字的情况
  • 用os.path.join拼接路径,避免因路径分隔符导致的错误
  • 补充图片缩放步骤(除以255),满足模型训练的归一化要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 05:55:45