首页 > 解决方案 > Pytorch 数据集。一旦捕获异常,项目似乎没有添加到列表中

问题描述

我有一个包含大量图片(200 万张)的数据集。做了很多预处理,图片用id标识。一些 id 不存在,但它们是生成的(仅供参考,更容易编码)。这意味着当我尝试打开图像时,我会在它周围加上一个 try/except 块。如果图片不存在,我会写入日志文件并尝试将该图像标识符的名称添加到列表中。我可能会尝试打开同一个文件两次(实际上是存在的文件需要),我的理由是,如果我将图片的标识符添加到列表中,我将不需要捕获异常并且代码将运行得更快,因为我可以检查是否不存在的文件的名称在列表中,如果是,那么我可以返回 None。

我提供了一些代码:

     def __init__(self, real_frames_dataframe, fake_frames_dataframe,
                 augmentations, image_size=224):

        # Should increase training speed as on second epoch will not need to catch exceptions
        self.non_existent_files = []

    def __getitem__(self, index):
        row_real = self.real_df.iloc[index]
        row_fake = self.fake_df.iloc[index]

        real_image_name = row_real["image_path"]
        fake_image_name = row_fake["image_path"]

        # Will go here from second epoch
        if real_image_name in self.non_existent_files or fake_image_name in self.non_existent_files:
            return None

        try:
            img_real = Image.open(real_image_name).convert("RGB")
        except FileNotFoundError:
            log.info("Real Image not found: {}".format(real_image_name))
            self.non_existent_files.append(real_image_name)
            return None
        try:
            img_fake = Image.open(fake_image_name).convert("RGB")
        except FileNotFoundError:
            log.info("Fake Image not found: {}".format(fake_image_name))
            self.non_existent_files.append(fake_image_name)
            return None

问题是我可以多次在日志文件中看到相同的标识符。例如:

Line 3201: 20:56:27, training.DeepfakeDataset, INFO Real Image not found: nvptcoxzah\nvptcoxzah_260.png
Line 3322: 21:23:13, training.DeepfakeDataset, INFO Real Image not found: nvptcoxzah\nvptcoxzah_260.png

我认为标识符将附加到non_existent_files并且下次我什至不会尝试打开此文件。但是,这不会发生。谁能解释为什么?

标签: pythonlistpytorchdataloader

解决方案


推荐阅读