【pytorch】图像分割中IOU等评价指标的计算

理论理解参考:【语义分割】评价指标:PA、CPA、MPA、IoU、MIoU详细总结和代码实现(零基础从入门到精通系列!)


"""
refer to https://github.com/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
        self.confusionMatrix = np.zeros((self.numClass,) * 2)  # 混淆矩阵(空)

    def pixelAccuracy(self):
        # return all class overall pixel accuracy 正确的像素占总像素的比例
        #  PA = acc = (TP + TN) / (TP + TN + FP + TN)
        acc = np.diag(self.confusionMatrix).sum() / self.confusionMatrix.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.diag(self.confusionMatrix) / self.confusionMatrix.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.diag(self.confusionMatrix)  # 取对角元素的值,返回列表
        union = np.sum(self.confusionMatrix, axis=1) + np.sum(self.confusionMatrix, axis=0) - np.diag(
            self.confusionMatrix)  # axis = 1表示混淆矩阵行的值,返回列表; axis = 0表示取混淆矩阵列的值,返回列表
        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 = count.reshape(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.sum(self.confusion_matrix, axis=1) / np.sum(self.confusion_matrix)
        iu = np.diag(self.confusion_matrix) / (
                np.sum(self.confusion_matrix, axis=1) + np.sum(self.confusion_matrix, axis=0) -
                np.diag(self.confusion_matrix))
        FWIoU = (freq[freq > 0] * iu[freq > 0]).sum()
        return FWIoU

    def addBatch(self, imgPredict, imgLabel):
        assert imgPredict.shape == imgLabel.shape
        self.confusionMatrix += self.genConfusionMatrix(imgPredict, imgLabel)  # 得到混淆矩阵
        return self.confusionMatrix

    def reset(self):
        self.confusionMatrix = np.zeros((self.numClass, self.numClass))

# 测试内容
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 = metric.meanPixelAccuracy()
    IoU = metric.IntersectionOverUnion()
    mIoU = metric.meanIntersectionOverUnion()
    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.79456712 0.99566652]
mPA is : 0.895117
IoU is :  [0.65915502 0.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, torch.ones_like(out), torch.zeros_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 = metric.meanPixelAccuracy()
     IoU = metric.IntersectionOverUnion()
     mIoU = metric.meanIntersectionOverUnion()
     print('--' * 20)
     print(
         'hist:{},\niou:{},\nmiou:{},\nPA:{},\ncPA:{},\nmPA:{}'.format(hist, IoU, mIoU, pa, cpa,
                                                                       mpa))
     #---------------------------------------------------------
  • 17
    点赞
  • 115
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 10
    评论
### 回答1: conda install pytorch torchvision torchaudio pytorch-cuda=11.7 -c pytorch -c是一个用于安装PyTorch深度学习框架及其相关扩展库的命令。其pytorch、torchvision和torchaudio是三个主要的扩展库,用于提供PyTorch的视觉、音频处理功能;而pytorch-cuda=11.7则是一个用于支持GPU加速的扩展库,确保PyTorch能够充分利用CUDA 11.7的性能优势。 可以看到,此命令含有两个-c参数,分别指定了PyTorch安装包的两个源。第一个-c指定了pytorch源,该源提供了存储在PyTorch官方网站上的最新版本的PyTorch包;第二个-c指定了空间,该源提供了存储在空间镜像上的PyTorch包和其他扩展包。通过这两个源的组合使用,可以确保在安装PyTorch时获取最新版本的软件包。 总之,这个命令让用户可以方便地从官方网站和其他社区获取安装PyTorch所需的所有组件,并支持GPU加速。安装完成后,用户可以快速地开始使用PyTorch进行深度学习相关的研究和应用。 ### 回答2: “conda install pytorch torchvision torchaudio pytorch-cuda=11.7 -c pytorch -c” 这段命令的作用是在 Anaconda 环境安装 PyTorch 及其各项相关组件。 PyTorch 是一个由 Facebook 开源的深度学习框架,它拥有灵活的可扩展性和易于使用的接口。而 torchvision 和 torchaudio 则是 PyTorch 官方提供的图像和语音处理库,可以帮助用户轻松地进行图像和语音相关的操作。 “pytorch-cuda=11.7” 指定了 CUDA 版本为 11.7,CUDA 是 NVIDIA 提供的并行计算平台和编程模型,让数据科学家可以高效地利用 NVIDIA GPU 的性能。而 PyTorch-cuda 则是 PyTorch 的 CUDA 版本,它可以运行在 NVIDIA GPU 上,提升模型的训练和推断速度。 “-c pytorch -c” 是指通过 PyTorch 官方的 conda 渠道来安装 PyTorch。在 Anaconda 的 channels ,-c 可以指定要安装的软件包来源,PyTorch 的 channel 是 pytorch,所以这里指定为 -c pytorch。 总之,这条命令的作用是在 Anaconda 环境安装 PyTorch 及其相关组件,并通过 PyTorch 官方渠道来安装。而且,通过指定 CUDA 的版本为 11.7,还可以利用 NVIDIA GPU 来加速模型的训练和推断。 ### 回答3: conda 是一个开源的包管理器,能够帮助我们安装、管理和维护数据科学相关的软件包。PyTorch 是一种深度学习框架,主要用于构建各种类型的神经网络模型。PyTorch 包含了许多功能强大的库,例如 torchvision 和 torchaudio,它们都可以用来帮助我们处理图像和声音数据。而 pytorch-cuda 是一个可选的包,可以让我们在 GPU 上实现更快的计算,提高程序的性能。 如果想要使用这些包,我们可以在命令行输入以下命令来安装: “conda install pytorch torchvision torchaudio pytorch-cuda=11.7 -c pytorch -c” 其,“conda install” 是安装包的命令,“pytorch torchvision torchaudio” 是需要安装的包的名称,“pytorch-cuda=11.7” 是可选的 GPU 包,“-c pytorch -c” 则是指定 PyTorch 的安装源。 需要注意的是,这个安装命令的版本号“11.7”是 CUDA 的版本号,如果你的电脑上安装的是其它版本的 CUDA,你需要更改这个版本号来匹配你的 CUDA 版本。同时,如果你没有安装 CUDA,可以不安装 pytorch-cuda,这样就不需要指定 CUDA 的版本号了。 总结来说,运行这个命令可以安装 PyTorch 及其配套的库,同时也能实现在 GPU 上进行加速计算的功能。安装完成后,你就可以使用 PyTorch 来构建和训练自己的深度学习模型了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Shine.Zhang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值