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

Python如何导入文件夹图像并划分训练/测试集及解决调用报错

报错原因

TypeError: 'list' object is not callable 触发的直接原因是代码最后两行对image_list变量使用了()调用语法:

image_list是你之前定义的存储PIL图像对象的普通列表,不属于可调用的函数/类实例,加括号执行会直接抛出类型错误。

现有代码的其他遗留问题

  • glob路径书写错误:/home/user/mydirectory*.gif 漏了路径和通配符之间的斜杠,匹配不到目标文件夹下的gif文件,正确路径应为/home/user/mydirectory/*.gif
  • 未存储图像对应的标签:当前只把图像本身存入了列表,没有对应分类标签,无法完成有监督的图像分类训练
  • 没有做训练集/测试集拆分:未对60000张样本做5:1的比例拆分,直接两次对image_list赋值不可能得到独立的训练、测试集
  • 读取的PIL对象没有转成numpy数组:TensorFlow/Keras训练时接收的是数值型数组输入,直接用PIL图像对象无法参与训练

正确实现代码

import numpy as np                                                
import keras                                                      
from keras.models import Sequential                               
from keras.layers import Dense, Dropout, Activation, Flatten     
from keras.layers import Conv2D, MaxPooling2D                    
from keras.preprocessing.image import ImageDataGenerator         
import matplotlib.pyplot as plt                                  
from keras.utils import np_utils          

from PIL import Image
import glob
import os
from sklearn.model_selection import train_test_split

# 基础配置,可根据实际情况修改
img_dir = "/home/user/mydirectory/"
# 分类数量,按你的实际任务调整
num_classes = 10
# 统一输入图像的尺寸
img_size = (32, 32)

X = []
y = []

# 读取所有图像和对应标签
# 以下逻辑默认你的数据集按子文件夹存分类,即每个类别的图像存在img_dir下对应类名的子文件夹里
# 如果标签是通过文件名标注的,可自行修改y的赋值逻辑
for class_idx, class_name in enumerate(os.listdir(img_dir)):
    class_path = os.path.join(img_dir, class_name)
    if not os.path.isdir(class_path):
        continue
    for filename in glob.glob(os.path.join(class_path, "*.gif")):
        im = Image.open(filename).convert('RGB') # 统一为三通道格式,避免灰度图通道不一致
        im = im.resize(img_size) # 统一尺寸
        img_arr = np.array(im)
        X.append(img_arr)
        y.append(class_idx)

# 转成numpy数组并做像素值归一化
X = np.array(X).astype('float32') / 255.0
y = np_utils.to_categorical(y, num_classes)

# 按5:1比例拆分训练集、测试集,固定random_state可复现拆分结果
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=1/6, random_state=42)

# 验证拆分结果
print(f"训练集样本数:{len(x_train)},测试集样本数:{len(x_test)}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 03:27:03