NotFoundError:已创建目录仍提示不存在的肺炎检测代码求助
我遇到了NotFoundError错误:Could not find directory D:/Języki programowania/Python/Projekty/Pneumonia_detection/chest_xray/chest_xray/train。尽管我手动创建了该目录,但仍不清楚错误出现的原因。
以下是我的代码:
import pandas as pd import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') from tensorflow import keras from keras import layers from tensorflow.keras.models import Sequential # type: ignore from tensorflow.keras.layers import Activation, Dropout, Flatten, Dense # type: ignore from tensorflow.keras.layers import Conv2D, MaxPooling2D # type: ignore from tensorflow.keras.utils import image_dataset_from_directory # type: ignore from tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img # type: ignore from tensorflow.keras.preprocessing import image_dataset_from_directory # type: ignore import os import matplotlib.image as mpimg # Importing dataset import zipfile dataset = zipfile.ZipFile("D:/Downloads/archive.zip", 'r') dataset.extractall() dataset.close() # Read the image data path = 'D:/Downloads/chest_xray/chest_xray/train' path = 'D:/Języki programowania/Python/Projekty/Pneumonia_Detection_CNN/kaggle/chest_xray/chest_xray/train' classes = os.listdir(path) print(classes) # Define directories for X-ray Images PNEUMONIA_dir = os.path.join(path + '/' + 'PNEUMONIA') NORMAL_dir = os.path.join(path + '/' + 'NORMAL') # Create list of files names in each directory pneumonia_names = os.listdir(PNEUMONIA_dir) normal_names = os.listdir(NORMAL_dir) print("There is", len(pneumonia_names), "images of pneumonia infected in training dataset") print("There is", len(normal_names), "normal images in training dataset") # Plot the Pneumonia infected Chest X-Ray images fig = plt.gcf() fig.set_size_inches(24, 12) pic_index = 210 pneumonia_images = [os.path.join(PNEUMONIA_dir, fname) for fname in pneumonia_names[pic_index-8:pic_index]] for i, img_path in enumerate(pneumonia_images): sp = plt.subplot(2, 4, i+1) sp.axis('Off') img = mpimg.imread(img_path) plt.imshow(img) plt.show() # Plot the Normal Chest X-Ray Images fig = plt.gcf() fig.set_size_inches(24, 12) pic_index = 210 normal_images = [os.path.join(NORMAL_dir, fname) for fname in normal_names[pic_index-8:pic_index]] for i, img_path in enumerate(normal_images): sp = plt.subplot(2, 4, i+1) sp.axis('Off') img = mpimg.imread(img_path) plt.imshow(img) plt.show() base_dir = 'D:/Języki programowania/Python/Projekty/Pneumonia_detection/chest_xray/chest_xray' Train_dir = os.path.join(base_dir + '/' + 'train') if not os.path.exists(Train_dir): os.mkdir(Train_dir) Test_dir = os.path.join(base_dir + '/' + 'test') if not os.path.exists(Test_dir): os.mkdir(Test_dir) Val_dir = os.path.join(base_dir + '/' + 'val') if not os.path.exists(Val_dir): os.mkdir(Val_dir) Train = keras.utils.image_dataset_from_directory( Train_dir, labels = "inferred", label_mode = "categorical", batch_size = 32, image_size = (256, 256) ) Test = keras.utils.image_dataset_from_directory( Test_dir, labels = "inferred", label_mode = "categorical", batch_size = 32, image_size = (256, 256) ) Validation = keras.utils.image_dataset_from_directory( Val_dir, labels = "inferred", label_mode = "categorical", batch_size = 32, image_size = (256, 256) )
期望得到的输出如下:
Found 5216 files belonging to 2 classes.
Found 624 files belonging to 2 classes.
Found 16 files belonging to 2 classes.
错误原因排查
空目录无有效数据
你仅用os.mkdir(Train_dir)创建了空目录,但image_dataset_from_directory要求目标目录下必须存在对应类别的子目录(如NORMAL和PNEUMONIA),且子目录下要有图片文件。你从zip包提取的数据在其他路径下,并未复制到新创建的Pneumonia_detection目录中,导致目录存在但无有效内容。路径拼接写法错误
使用os.path.join(base_dir + '/' + 'train')是错误用法,os.path.join会自动处理路径分隔符,正确写法应为os.path.join(base_dir, 'train'),虽然这不会直接导致目录不存在,但可能引发其他路径异常。目录名大小写不一致
注意路径中的目录名大小写:之前用的是Pneumonia_Detection_CNN,后来的路径是Pneumonia_detection(小写d),Windows系统虽默认不区分大小写,但部分场景下可能出现识别问题,建议保持名称大小写完全一致。权限限制
检查程序是否有访问D:/Języki programowania/Python/Projekty/Pneumonia_detection/目录的权限,若目录设为只读或当前用户无访问权限,也会触发NotFoundError。
修复建议
- 直接使用已提取好的数据集路径,将
base_dir设置为D:/Downloads/chest_xray/chest_xray,无需重新创建空目录。 - 若要迁移数据集,需将原目录下的
train、test、val文件夹完整复制到Pneumonia_detection/chest_xray/chest_xray/路径下,确保每个目录下都有NORMAL和PNEUMONIA子目录及对应图片。 - 修正路径拼接方式,统一使用
os.path.join(base_dir, 'train')这类标准写法。
内容的提问来源于stack exchange,提问作者Jakub Krzysztof Woźniak

