使用to_categorical对图像数据集独热编码时遇FileNotFoundError求助
解决FileNotFoundError:图像路径拼接错误问题
问题根源很明确:你生成图像路径时,没有包含数据集的根目录/content/imdadulhaque/,导致程序尝试读取的是相对路径BL_Healthy/BL_Healthy_0_451.jpg,而当前工作目录并非该根目录,自然找不到文件。
修正方案
- 先定义根目录变量,避免重复书写路径,减少出错概率
- 遍历类文件夹时,拼接出完整的类目录路径
- 构建图像路径时,基于完整的类目录路径拼接文件名
修改后的完整代码
import os import numpy as np from PIL import Image from keras.utils import to_categorical # Define the classes in the dataset classes = ['BL_Healthy'] # 定义数据集根目录 root_dir = '/content/imdadulhaque/' # Initialize the arrays to store the image data and labels X = [] y = [] # Loop through the dataset and load each image for class_id, class_name in enumerate(classes): # 拼接完整的类目录路径 class_dir = os.path.join(root_dir, class_name) # 遍历类目录下的图像文件 for image_file in os.listdir(class_dir): # 拼接完整的图像路径 image_path = os.path.join(class_dir, image_file) image = Image.open(image_path) X.append(np.array(image)) y.append(class_id) # Convert the labels to one-hot encoded labels num_classes = len(classes) y = to_categorical(y, num_classes)
额外调试建议
- 在打开图像前,可以先打印
image_path,确认路径是否正确,比如添加print(image_path),方便排查路径问题 - 确保
root_dir的拼写完全正确,包括大小写(Linux系统路径区分大小写)
内容的提问来源于stack exchange,提问作者Imdadul Haque
相关产品推荐
相关产品推荐

