1. 程式人生 > 其它 >Debug筆記:解決AttributeError: ‘bool‘ object has no attribute ‘all‘

Debug筆記:解決AttributeError: ‘bool‘ object has no attribute ‘all‘

技術標籤:Debugnumpynumpydebug影象處理

最近在製作資料集的時候,需要核驗生成的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