微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Pytorch 数据集一旦捕获异常,项目似乎不会添加到列表

如何解决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,INFO Real Image not found: nvptcoxzah\nvptcoxzah_260.png

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。