【pytorch】图像分割中IOU等评价指标的计算
【pytorch】图像分割中IOU等评价指标的计算
理论理解参考:
"""
refer to github/jfzhang95/pytorch-deeplab-xception/blob/master/utils/metrics.py
"""
import numpy as np
import cv2
__all__ =['SegmentationMetric']
"""
confusionMetric  # 注意:此处横着代表预测值,竖着代表真实值,与之前介绍的相反
P\L    P    N
P      TP    FP
N      FN    TN
"""
class SegmentationMetric(object):
def__init__(self, numClass):
self.numClass = numClass
def pixelAccuracy(self):
# return all class overall pixel accuracy 正确的像素占总像素的⽐例
#  PA = acc = (TP + TN) / (TP + TN + FP + TN)
acc = np.fusionMatrix).sum()/ fusionMatrix.sum()
return acc
def classPixelAccuracy(self):
# return each category pixel accuracy(A more accurate way to call it precision)
# acc = (TP) / TP + FP
classAcc = np.fusionMatrix)/ fusionMatrix.sum(axis=1)
return classAcc  # 返回的是⼀个列表值,如:[0.90, 0.80, 0.96],表⽰类别1 2 3各类别的预测准确率
def meanPixelAccuracy(self):
"""
Mean Pixel Accuracy(MPA,均像素精度):是PA的⼀种简单提升,计算每个类内被正确分类像素数的⽐例,之后求所有类的平均。        :return:
"""
classAcc = self.classPixelAccuracy()
meanAcc = np.nanmean(classAcc)# np.nanmean 求平均值,nan表⽰遇到Nan类型,其值取为0
return meanAcc  # 返回单个值,如:np.nanmean([0.90, 0.80, 0.96, nan, nan]) = (0.90 + 0.80 + 0.96) / 3 =  0.89
def IntersectionOverUnion(self):
# Intersection = TP Union = TP + FP + FN
# IoU = TP / (TP + FP + FN)
intersection = np.fusionMatrix)# 取对⾓元素的值,返回列表
union = np.fusionMatrix, axis=1)+ np.fusionMatrix, axis=0)- np.diag(
IoU = intersection / union  # 返回列表,其值为各个类别的IoU
return IoU
def meanIntersectionOverUnion(self):
mIoU = np.nanmean(self.IntersectionOverUnion())# 求各类别IoU的平均
return mIoU
def genConfusionMatrix(self, imgPredict, imgLabel):#
"""
同FCN中score.py的fast_hist()函数,计算混淆矩阵
:param imgPredict:
:param imgLabel:
:return: 混淆矩阵
"""
"""
# remove classes from unlabeled pixels in gt image and predict
mask =(imgLabel >=0)&(imgLabel < self.numClass)
label = self.numClass * imgLabel[mask]+ imgPredict[mask]
count = np.bincount(label, minlength=self.numClass **2)
confusionMatrix = shape(self.numClass, self.numClass)
# print(confusionMatrix)
return confusionMatrix
def Frequency_Weighted_Intersection_over_Union(self):
"""
FWIoU,频权交并⽐:为MIoU的⼀种提升,这种⽅法根据每个类出现的频率为其设置权重。
FWIOU =    [(TP+FN)/(TP+FP+TN+FN)] *[TP / (TP + FP + FN)]
"""
freq = np.fusion_matrix, axis=1)/ np.fusion_matrix)
iu = np.fusion_matrix)/(
np.fusion_matrix, axis=1)+ np.fusion_matrix, axis=0)-
np.fusion_matrix))
FWIoU =(freq[freq >0]* iu[freq >0]).sum()
return FWIoU
def addBatch(self, imgPredict, imgLabel):
assert imgPredict.shape == imgLabel.shape
def reset(self):
# 测试内容
if __name__ =='__main__':
imgPredict = cv2.imread('1.png')
imgLabel = cv2.imread('2.png')
imgPredict = np.array(cv2.cvtColor(imgPredict, cv2.COLOR_BGR2GRAY)/255., dtype=np.uint8)    imgLabel = np.array(cv2.cvtColor(imgLabel, cv2.COLOR_BGR2GRAY)/255., dtype=np.uint8) # imgPredict = np.array([0, 0, 1, 1, 2, 2])  # 可直接换成预测图⽚
# imgLabel = np.array([0, 0, 1, 1, 2, 2])  # 可直接换成标注图⽚
metric = SegmentationMetric(2)# 2表⽰有2个分类,有⼏个分类就填⼏
hist = metric.addBatch(imgPredict, imgLabel)
pa = metric.pixelAccuracy()
cpa = metric.classPixelAccuracy()
mpa = anPixelAccuracy()
IoU = metric.IntersectionOverUnion()
dde指标mIoU = anIntersectionOverUnion()
print('hist is :\n', hist)
print('PA is : %f'% pa)
print('cPA is :', cpa)# 列表
print('mPA is : %f'% mpa)
print('IoU is : ', IoU)
print('mIoU is : ', mIoU)
输出:
hist is:
[[43466.11238.]
[11238.2582058.]]
PA is:0.991512
cPA is:[0.794567120.99566652]
mPA is:0.895117
IoU is:[0.659155020.99137043]
mIoU is:0.8252627241326803
1.png
在这⾥插⼊图⽚描述
2.png
在这⾥插⼊图⽚描述
在⽹络中使⽤时要保证调⽤的addBatch()的输⼊shape相同,数据类型相同(np.int32) from metrics import SegmentationMetric
# 局部代码
for x, mask in dataloaders:
out = model(x)# ⽹络的输出
#---------------------------------------------------------
pred = torch.where(out >0.5, s_like(out), s_like(out))# 0.5为阈值
pred, y = pred.cpu().numpy(), mask.cpu().numpy() # 转化为ndarray类型才能进⾏计算
pred, y = pred.astype(np.int32), y.astype(np.int32)# 转化为整型
metric = SegmentationMetric(2)# 2个分类
hist = metric.addBatch(pred, y)
pa = metric.pixelAccuracy()
cpa = metric.classPixelAccuracy()
mpa = anPixelAccuracy()
IoU = metric.IntersectionOverUnion()
mIoU = anIntersectionOverUnion()
print('--'*20)
print(
'hist:{},\niou:{},\nmiou:{},\nPA:{},\ncPA:{},\nmPA:{}'.format(hist, IoU, mIoU, pa, cpa,
mpa))
#---------------------------------------------------------

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。