Google Colab读取Drive图像报错:未检测到图像与类别
问题描述
在Google Colab中运行图像分类代码时,执行model.fit(train_generator, epochs=10, validation_data=test_generator)前持续出现如下错误:
Found 0 images belonging to 0 classes. Found 0 images belonging to 0 classes.
已调整batch尺寸为10、将所有图像resize至100×100,训练/测试图像分别存入training_data和testing_data文件夹,但问题未解决。相关代码如下:
!pip install tensorflow import cv2 from tensorflow.keras.preprocessing.image import img_to_array import numpy as np import tensorflow as tf from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.applications import EfficientNetB0 from tensorflow.keras.layers import Dense, GlobalAveragePooling2D from tensorflow.keras.models import Model from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score #uploads the image def load_image(image_location): # Load the image using OpenCV image = cv2.imread(image_location) #checks if image is uploaded or not if image is None: print("Error: image not found from", image_location) return None resized_image= cv2.resize(image, (100, 100)) image_array = img_to_array(resized_image) image_array /= 255.0 return image_array example_image_location = '/content/drive/MyDrive/Machine Learning Folder/training_data/LightGreen_Crayon_Testing.jpg' # Load and preprocess the example image example_image = load_image(example_image_location) if example_image is not None: # collecting/processing data train_dir = '/content/drive/MyDrive/Machine Learning Folder/training_data' test_dir = '/content/drive/MyDrive/Machine Learning Folder/testing_data' train_datagen = ImageDataGenerator(rescale=1. / 255) test_datagen = ImageDataGenerator(rescale=1. / 255) train_generator = train_datagen.flow_from_directory(train_dir, target_size=(100, 100), batch_size=10, class_mode='binary') test_generator = test_datagen.flow_from_directory(test_dir, target_size=(100, 100), batch_size=10, class_mode='binary') # model building base_model = EfficientNetB0(weights='imagenet', include_top=False) x = base_model.output x = GlobalAveragePooling2D()(x) x = Dense(1024, activation='relu')(x) predictions = Dense(1, activation='sigmoid')(x) model = Model(inputs=base_model.input, outputs=predictions) for layer in base_model.layers: layer.trainable = False model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) model.fit(train_generator, epochs=10, validation_data=test_generator)
问题排查与解决
1. 修复目录结构(核心问题)
flow_from_directory要求每个类别必须存放在单独的子文件夹中,不能直接将图像放在training_data或testing_data的根目录下。正确的目录结构应为:
Machine Learning Folder/ ├── training_data/ │ ├── LightGreen_Crayon/ # 类别1文件夹 │ │ ├── LightGreen_Crayon_Testing.jpg │ │ └── 其他同类别图像... │ └── 其他类别文件夹/ # 比如DarkGreen_Crayon │ └── ... └── testing_data/ ├── LightGreen_Crayon/ └── 其他类别文件夹/
原目录将图像直接放在根目录,导致flow_from_directory无法识别类别和图像,因此输出"Found 0 images belonging to 0 classes"。
2. 修正代码缩进错误
代码中model.compile()和model.fit()被错误嵌套在for layer in base_model.layers:循环内部,会导致每遍历一个模型层就编译一次模型、触发一次训练,逻辑完全错误。需将这两行移至循环外部:
for layer in base_model.layers: layer.trainable = False # 编译与训练代码移至循环外 model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) model.fit(train_generator, epochs=10, validation_data=test_generator)
3. 删除冗余代码
自定义的load_image函数及示例图像加载逻辑属于冗余操作——ImageDataGenerator+flow_from_directory已自动完成图像加载、resize和归一化,可直接删除这部分代码,避免混淆。
4. 验证路径有效性
可添加代码确认目录路径正确且包含内容:
import os # 打印训练目录下的内容,确认存在类别子文件夹 print("训练目录内容:", os.listdir(train_dir)) print("测试目录内容:", os.listdir(test_dir))
若输出为空或无类别子文件夹,需检查路径拼写或目录结构是否正确。
内容的提问来源于stack exchange,提问作者zaelyn
相关产品推荐
相关产品推荐

