FileNotFoundError: [Errno 2] No such file or directory: '2007_009096.jpg'

FileNotFoundError: [Errno 2] No such file or directory: '2007_009096.jpg'

我最近做了这个 class :

class RealPhotosDataset(Dataset):
    def __init__(self, directory):
        self.files = os.listdir(directory)

    def __getitem__(self, index):
        print(self.files[index])
        img = Image.open(self.files[index]).convert('RGB')
        return T.ToTensor()(img)
    
    def __len__(self):
      return len(self.files)

data_set = RealPhotosDataset("targetdir/JPEGImages/")

train_len = int(len(data_set)*0.7)
train_set, test_set = random_split(data_set, [train_len, len(data_set) - train_len])

kwargs = {'num_workers': 1, 'pin_memory': True}
train_loader = DataLoader(train_set, batch_size=1, shuffle=True, **kwargs)
test_loader = DataLoader(test_set, batch_size=64, shuffle=True, **kwargs)

我在 colab 中加载了我的数据集:

我有一个for循环,即

for x, y in test_loader:
   ...

这会带来修复错误的挑战。

FileNotFoundError: Caught FileNotFoundError in DataLoader worker process 0.
Original Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/torch/utils/data/_utils/worker.py", line 198, in _worker_loop
    data = fetcher.fetch(index)
  File "/usr/local/lib/python3.6/dist-packages/torch/utils/data/_utils/fetch.py", line 44, in fetch
    data = [self.dataset[idx] for idx in possibly_batched_index]
  File "/usr/local/lib/python3.6/dist-packages/torch/utils/data/_utils/fetch.py", line 44, in <listcomp>
    data = [self.dataset[idx] for idx in possibly_batched_index]
  File "/usr/local/lib/python3.6/dist-packages/torch/utils/data/dataset.py", line 272, in __getitem__
    return self.dataset[self.indices[idx]]
  File "<ipython-input-58-be7e605a57d0>", line 7, in __getitem__
    img = Image.open(self.files[index]).convert('RGB')
  File "/usr/local/lib/python3.6/dist-packages/PIL/Image.py", line 2809, in open
    fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: '2007_009096.jpg'

我不知道如何解决这个错误。 2007_009096.jpg 确实是 targetdir/JPEGImages 中的现有文件。我该如何修复该错误

替换

self.files = os.listdir(directory)

来自

self.files = [os.path.join(directory, f) for f in os.listdir(directory)]

正确注册文件的完整路径。