FileNotFoundError: 系统无法找到指定路径:'D:\\MS Data\\CI Papers\\My Paper\\LungCancerDataset\\Benign_cases

-1 投票
1 回答
35 浏览
提问于 2025-04-12 22:46

我一直在尝试在我的jupyter notebook中加载数据,但总是遇到FileNotFoundError错误。因为我对这个还不太熟悉,所以遇到了困难。我有一个名为LungCancerDataset的文件夹,里面有三个子文件夹,分别叫做Bengin_cases、Malignant_cases和Normal_cases。

我想把这些数据加载进来,并进行预处理,以便用Alexnet进行分类。

文件夹的截图: 这里是图片描述

import os
import cv2
import numpy as np
from sklearn.model_selection import train_test_split

dataset_path = r'D:\MS Data\CI Papers\My Paper\LungCancerDataset'

def load_and_preprocess_images(folder_path):
    images = []
    labels = []

# Iterate over files in the folder
for label, filename in enumerate(os.listdir(folder_path)):
    # Construct the full path to the image file
    image_path = os.path.join(folder_path, filename)

    # Read the image using OpenCV
    image = cv2.imread(image_path)

    # Check if the image was successfully loaded
    if image is not None:
        # Resize image to 227x227 (AlexNet input size)
        image = cv2.resize(image, (227, 227))

        # Normalize pixel values to range [0, 1]
        image = image.astype('float32') / 255.0

        # Append the image and its label to the lists
        images.append(image)
        labels.append(label)  # Assign label based on folder (0: normal, 1: benign, 2: malignant)

return images, labels

normal_images, normal_labels = load_and_preprocess_images(os.path.join(dataset_path, 'Normal_cases'))
benign_images, benign_labels = load_and_preprocess_images(os.path.join(dataset_path, 'Benign_cases'))
malignant_images, malignant_labels = load_and_preprocess_images(os.path.join(dataset_path, 'Malignant_cases'))

错误信息

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-7-8858f2466543> in <module>
      1 normal_images, normal_labels = load_and_preprocess_images(os.path.join(dataset_path, 'Normal_cases'))
----> 2 benign_images, benign_labels = load_and_preprocess_images(os.path.join(dataset_path, 'Benign_cases'))
      3 malignant_images, malignant_labels = load_and_preprocess_images(os.path.join(dataset_path, 'Malignant_cases'))

<ipython-input-6-ae38c4e28bac> in load_and_preprocess_images(folder_path)
      4 
      5     # Iterate over files in the folder
----> 6     for label, filename in enumerate(os.listdir(folder_path)):
      7         # Construct the full path to the image file
      8         image_path = os.path.join(folder_path, filename)

FileNotFoundError: [WinError 3] The system cannot find the path specified: 'D:\\MS Data\\CI Papers\\My Paper\\LungCancerDataset\\Benign_cases'

我尝试向chat gpt寻求帮助,但没有成功 (聊天链接)。我也试着在这里找一些问题,但都没有用 (问题链接) (问题链接)

1 个回答

1

你把文件夹的名字写错了,写成了Bengin,但你的代码里用的是Benign

这个问题在评论里也被@John Gordon提到过。

记得让你的文件名和你想要找的东西的名字一致哦。

撰写回答