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

Jupyter Lab数据加载异常:路径正确仍无法读取部分数据

图像分类项目数据加载错误排查

在Jupyter Lab开展图像分类项目时,已指定正确文件路径,但仍出现部分数据无法读取的错误,报错截图与相关代码如下:

无法读取数据的报错截图

class_names=['mountain','street','glacier','buildings','sea','forest']
class_names_label={class_name: i for i,class_name  in enumerate(class_names)}
nb_classes=len(class_names)
print(class_names_label)
print(nb_classes)
IMAGE_SIZE=(150,150)

#loading data
def load_data():
    DIRECTORY=r"C:\3 symester\4 sym\AI project\image classification"
    CATEGORY=["seg_train","seg_test"]

    output=[]

    for category in CATEGORY:
        path=os.path.join(DIRECTORY,category)
        print(path)
        images=[]
        labels=[]

        print("Loading {}".format(category))

        for folder in os.listdir(path):
            label=class_names_label[folder]

                #iterate througheach image in our folder
                for file in os.listdir(os.path.join(path,folder)):
                    #get path name of img
                    img_path=os.path.join(os.path.join(path,folder),file)
                    
                    #open and resize the image
                    image=cv2.imread(img_path)
                    image=cv2.cvtColor(image,cv2.COLOR_BGR2RGB)
                    image=cv2.resize(image,IMAGE_SIZE)
                    
                    #Append the image and its corresponding label to the output
                    image.append(image)
                    labels.append(label)
                    images=np.array(images,dtype='float32')
                    labels=np.array(labels,dtype='int32')

                    output.append((images,labels))
    return output

错误原因排查:

  • 缩进逻辑错误:内层遍历图片的for循环缩进层级错误,导致代码语法不合法,无法正确执行遍历逻辑。
  • 变量名混淆:将单张图片的变量名设为image,后续错误调用image.append(image)——image是numpy数组而非列表,正确操作应为向列表images(复数)添加元素:images.append(image)。
  • 数组转换时机错误:在遍历单张图片的循环内就将images和labels转为numpy数组,numpy数组不支持直接append操作,且会导致每处理一张图就重复转换,逻辑混乱。应先通过列表收集所有数据,在整个category处理完成后再转换为数组。
  • 结果添加时机错误:在遍历单张图片时就向output添加数据,会导致每一张图片生成一组(images,labels),而非按训练集/测试集分组。应在每个category(seg_train/seg_test)处理完所有图片后,再将该组数据加入output。
  • 缺少异常处理:部分图片可能损坏,cv2.imread会返回None,此时执行cvtColor或resize会直接报错。需添加判断,若读取的image为None则跳过该图片。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 09:07:29