Debug笔记:解决AttributeError: ‘bool‘ object has no attribute ‘all‘

最近在制作数据集的时候,需要核验生成的patch是否包含有用的信息,而在执行以下代码的时候发生了错误

black = np.zeros((256, 256), dtype="uint8")
for file in tqdm(mask_list):
    img = np.array(Image.open(file))
    if (img == black).all:
        bcnt = bcnt + 1
    else:
        wcnt = wcnt + 1

这里的mask_list是一个我要核验的grounth truth文件的列表,代码在if (img == black).all:报错,提示AttributeError: 'bool' object has no attribute 'all'这就很让人迷惑:我之前执行这段代码从来没有报过错,而且我的代码并不是一开始就报错,而是执行到某个样本时报错

这告诉我:应该是有一些样本的格式出了问题,进行以下测试

>>> t2=np.zeros([4,4])
>>> t3=t2
>>>> t3==t2
array([[ True,  True,  True,  True],
       [ True,  True,  True,  True],
       [ True,  True,  True,  True],
       [ True,  True,  True,  True]])
>>> (t3==t2).all()
True
>>> t4 = np.zeros([3,3])
>>> t3==t4
False

答案很明显了:

  1. 当判断两个形状相同的矩阵是否相等时,返回一个相同形状的矩阵(np.ndarray),每个位置是一个bool值
  2. 当判断两个形状不同的矩阵是否相等时,不论两个矩阵的元素如何,都返回一个bool值—False。原因显而易见

因此显然是我在制作数据集的时候生成了一些格式不对的ground truth,将代码改成如下形式,可以运行

mask_list = glob.glob(os.path.join(mask_path, "*.png"))
# print(path_list)
for file in tqdm(mask_list):
    img = np.array(Image.open(file))
    if type(img == black) == bool:
        os.remove(file)
        # print('{} has been removed'.format(os.path.basename(file)))
        dcnt = dcnt + 1
        continue
    if (img == black).all:
        bcnt = bcnt + 1
    else:
        wcnt = wcnt + 1
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值