最近在制作数据集的时候,需要核验生成的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
答案很明显了:
- 当判断两个形状相同的矩阵是否相等时,返回一个相同形状的矩阵(
np.ndarray
),每个位置是一个bool值 - 当判断两个形状不同的矩阵是否相等时,不论两个矩阵的元素如何,都返回一个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