出现问题:IndexError: list index out of range

错误原因:

E:\Anaconda\envs\DL\python.exe E:\AnomalyCLIP\AnomalyCLIP-main\generate_dataset_json\isbi.py Traceback (most recent call last): File "E:\AnomalyCLIP\AnomalyCLIP-main\generate_dataset_json\isbi.py", line 48, in <module> runner.run() File "E:\AnomalyCLIP\AnomalyCLIP-main\generate_dataset_json\isbi.py", line 30, in run mask_path=f'{cls_name}/ISBI2016_ISIC_Part1_Test_GroundTruth/{mask_names[idx]}' if is_abnormal else '', IndexError: list index out of range 进程已结束,退出代码为 1

原因分析:

出现 IndexError: list index out of range 错误,表示代码尝试访问 mask_names 列表中不存在的索引。这个错误可能是由于 mask_names 的长度与 img_names 的长度不一致导致的。

为了防止这种错误,我们可以在访问 mask_names 时添加一个检查,确保索引不超出范围。此外,确保 mask_namesis_abnormalTrue 时确实被正确加载。

源代码为:

import os
import json


class IsbiSolver(object):
    CLSNAMES = ['skin']

    def __init__(self, root='E:/AnomalyCLIP/AnomalyCLIP-main/data/ISBI'):
        self.root = root
        self.meta_path = f'{root}/meta.json'

    def run(self):
        info = dict(train={}, test={})
        anomaly_samples = 0
        normal_samples = 0
        for cls_name in self.CLSNAMES:
            cls_dir = f'{self.root}/{cls_name}'
            for phase in ['test']:
                cls_info = []
                species = os.listdir(f'{cls_dir}/{phase}')
                for specie in species:
                    is_abnormal = True if specie not in ['good'] else False
                    img_names = os.listdir(f'{cls_dir}/{phase}/{specie}')
                    mask_names = os.listdir(f'{cls_dir}/ISBI2016_ISIC_Part1_Test_GroundTruth/') if is_abnormal else None
                    img_names.sort()
                    mask_names.sort() if mask_names is not None else None
                    for idx, img_name in enumerate(img_names):
                        info_img = dict(
                            img_path=f'{cls_name}/{phase}/{specie}/{img_name}',
                            mask_path=f'{cls_name}/ISBI2016_ISIC_Part1_Test_GroundTruth/{mask_names[idx]}' if is_abnormal else '',
                            cls_name=cls_name,
                            specie_name=specie,
                            anomaly=1 if is_abnormal else 0,
                        )
                        cls_info.append(info_img)
                        if phase == 'test':
                            if is_abnormal:
                                anomaly_samples = anomaly_samples + 1
                            else:
                                normal_samples = normal_samples + 1
                info[phase][cls_name] = cls_info
        with open(self.meta_path, 'w') as f:
            f.write(json.dumps(info, indent=4) + "\n")
        print('normal_samples', normal_samples, 'anomaly_samples', anomaly_samples)

if __name__ == '__main__':
    runner = IsbiSolver(root='E:/AnomalyCLIP/AnomalyCLIP-main/data/ISBI')
    runner.run()

修改为:

import os
import json

class IsbiSolver(object):
    CLSNAMES = ['skin']

    def __init__(self, root='E:/AnomalyCLIP/AnomalyCLIP-main/data/ISBI'):
        self.root = root
        self.meta_path = f'{root}/meta.json'

    def run(self):
        info = dict(train={}, test={})
        anomaly_samples = 0
        normal_samples = 0
        for cls_name in self.CLSNAMES:
            cls_dir = f'{self.root}/{cls_name}'
            for phase in ['test']:
                cls_info = []
                species = os.listdir(f'{cls_dir}/{phase}')
                for specie in species:
                    is_abnormal = True if specie not in ['good'] else False
                    img_names = os.listdir(f'{cls_dir}/{phase}/{specie}')
                    mask_names = os.listdir(f'{cls_dir}/ISBI2016_ISIC_Part1_Test_GroundTruth/') if is_abnormal else []
                    img_names.sort()
                    mask_names.sort()
                    for idx, img_name in enumerate(img_names):
                        mask_path = f'{cls_name}/ISBI2016_ISIC_Part1_Test_GroundTruth/{mask_names[idx]}' if is_abnormal and idx < len(mask_names) else ''
                        info_img = dict(
                            img_path=f'{cls_name}/{phase}/{specie}/{img_name}',
                            mask_path=mask_path,
                            cls_name=cls_name,
                            specie_name=specie,
                            anomaly=1 if is_abnormal else 0,
                        )
                        cls_info.append(info_img)
                        if phase == 'test':
                            if is_abnormal:
                                anomaly_samples += 1
                            else:
                                normal_samples += 1
                info[phase][cls_name] = cls_info
        with open(self.meta_path, 'w') as f:
            f.write(json.dumps(info, indent=4) + "\n")
        print('normal_samples', normal_samples, 'anomaly_samples', anomaly_samples)

if __name__ == '__main__':
    runner = IsbiSolver(root='E:/AnomalyCLIP/AnomalyCLIP-main/data/ISBI')
    runner.run()

修改的地方在于:mask_path 添加索引检查

mask_path = f'{cls_name}/ISBI2016_ISIC_Part1_Test_GroundTruth/{mask_names[idx]}' if is_abnormal and idx < len(mask_names) else ''

 

    • 只有在 is_abnormalTrueidx 小于 mask_names 的长度时,才设置 mask_path
    • 否则,mask_path 设置为空字符串 ''

这将防止因索引超出范围导致的 IndexError。请运行修改后的代码,检查是否解决了问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值