File not found error 即使我没有在代码中提到或使用错误文件名或目录名

问题描述 投票:0回答:2

对于代码中不存在的文件名找不到文件的错误。我没有在整个代码中使用文件或目录名,仍然抛出错误。

# Extract the features from the images
def extract_features(image_paths):
    features = []
    for image_path in image_paths:
        image = Image.open(image_path)
        image = image.resize((224, 224))
        image = np.array(image)
        image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))
        image = vgg.predict(image)
        image = np.reshape(image, image.shape[1]*image.shape[2]*image.shape[3])
        features.append(image)
    return np.array(features)

features_train = extract_features(image_paths_train)
features_test = extract_features(image_paths_test)

上面代码的错误是-

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
/tmp/ipykernel_785/4261382143.py in <module>
     12     return np.array(features)
     13 
---> 14 features_train = extract_features(image_paths_train)
     15 features_test = extract_features(image_paths_test)

/tmp/ipykernel_785/4261382143.py in extract_features(image_paths)
      3     features = []
      4     for image_path in image_paths:
----> 5         image = Image.open(image_path)
      6         image = image.resize((224, 224))
      7         image = np.array(image)

/opt/conda/lib/python3.7/site-packages/PIL/Image.py in open(fp, mode, formats)
   3129 
   3130     if filename:
-> 3131         fp = builtins.open(filename, "rb")
   3132         exclusive_fp = True
   3133 

FileNotFoundError: [Errno 2] No such file or directory: 't'

请帮忙

python machine-learning kaggle
2个回答
1
投票

调试问题会更容易,因为错误出现在 Image.open(image_path) 线上

使用以下行进行调试:

print("Image paths for training set:")
print(image_paths_train)
print("\nImage paths for testing set:")
print(image_paths_test)

features_train = extract_features(image_paths_train)
features_test = extract_features(image_paths_test)

如果打印的文件路径不正确或不存在,您将需要调查这些变量是如何创建的,并确保它们包含正确的文件路径。


0
投票

我建议使用断言进行调试以确保您的路径有效。正如之前其他人所说,它们应该有问题,可能是文件名中的空格,或者其他什么。

from os import path


def extract_features(image_paths):
    features = []
    for image_path in image_paths:
        assert path.exists(image_path), f'Path {image_path} does not exist!'
        image = Image.open(image_path)
        image = image.resize((224, 224))
        image = np.array(image)
        image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))
        image = vgg.predict(image)
        image = np.reshape(image, image.shape[1]*image.shape[2]*image.shape[3])
        features.append(image)
    return np.array(features)
© www.soinside.com 2019 - 2024. All rights reserved.