如题,以下代码可以根据预测图片和GT得到mPA和mIoU的值。
注:使用此代码进行计算时,GT中的标签值需为从(0,0,0)递增至(n,n,n),n为类别的数量。
import numpy as np
from PIL import Image
from os.path import join
def fast_hist(a, b, n):
k = (a >= 0) & (a < n)
return np.bincount(n * a[k].astype(int) + b[k], minlength=n ** 2).reshape(n, n)
def per_class_iu(hist):
return np.diag(hist) / np.maximum((hist.sum(1) + hist.sum(0) - np.diag(hist)), 1)
def per_class_PA(hist):
return np.diag(hist) / np.maximum(hist.sum(1), 1)
def compute_mIoU(gt_dir, pred_dir, png_name_list, num_classes, name_classes):
print('Num classes', num_classes)
hist = np.zeros((num_classes, num_classes))
gt_imgs = [join(gt_dir, x + ".png") for x in png_name_list]
pred_imgs = [join(pred_dir, x + ".png") for x in png_name_list]
for ind in range(len(gt_imgs)):
pred = np.array(Image.open(pred_imgs[ind]))
label = np.array(Image.open(gt_imgs[ind]))
if len(label.flatten()) != len(pred.flatten()):
print(
'Skipping: len(gt) = {:d}, len(pred) = {:d}, {:s}, {:s}'.format(
len(label.flatten()), len(pred.flatten()), gt_imgs[ind],
pred_imgs[ind]))
continue
hist += fast_hist(label.flatten(), pred.flatten(), num_classes)
if ind > 0 and ind % 10 == 0:
print('{:d} / {:d}: mIou-{:0.2f}; mPA-{:0.2f}'.format(ind, len(gt_imgs),
100 * np.nanmean(per_class_iu(hist)),
100 * np.nanmean(per_class_PA(hist))))
mIoUs = per_class_iu(hist)
mPA = per_class_PA(hist)
for ind_class in range(num_classes):
print('===>' + name_classes[ind_class] + ':\tmIoU:' + str(round(mIoUs[ind_class] * 100, 2)) + '; mPA:' + str(
round(mPA[ind_class] * 100, 2)))
print('===> mIoU: ' + str(round(np.nanmean(mIoUs) * 100, 2)) + '; mPA: ' + str(round(np.nanmean(mPA) * 100, 2)))
return mIoUs
png_name_list = [""]
name_classes = [""]
compute_mIoU("./gt", "./pred", png_name_list, 3, name_classes)
参考资料:
https://wenku.baidu.com/view/95bd23cd1ae8b8f67c1cfad6195f312b3169eb33.html