语义分割准确率、精确率、召回率、F1值计算代码

语义分割准确率、精确率、召回率、F1值计算

使用提示

需要opencv库
只需将预测结果文件路径与标签路径改一下
只针对二分类哦
(多分类可稍作修改)
代码里正类的像素值为255,可做修改!

1.精度指标
TP 正类判定为正类

FP 负类判定为正类

FN 正类判定为负类

TN 负类判定为负类

import cv2
import numpy as np
import os

#预测结果路径
pred_path = r'D:\experiment\u-net\predict'
#标签路径
lab_path = r'F:\dataset\LEVIR-CD-deal\test\label'


def tpcount(imgp,imgl):
    n = 0
    for i in range(WIDTH):
        for j in range(HIGTH):
            if imgp[i,j] == 255 and imgl[i,j] == 255:
                n = n+1
    return n

def fncount (imgp,imgl):
    n = 0
    for i in range(WIDTH):
        for j in range(HIGTH):
            if imgl[i,j] == 255 and imgp[i,j] == 0:
                n = n+1
    return n

def fpcount(imgp,imgl):
    n = 0
    for i in range(WIDTH):
        for j in range(HIGTH):
            if imgl[i,j] == 0 and imgp[i,j] == 255:
                n+=1
    return n

def tncount(imgp,imgl):
    n=0
    for i in range(WIDTH):
        for j in range(HIGTH):
            if imgl[i,j] == 0 and imgp[i,j] == 0:
                n += 1
    return n




imgs = os.listdir(pred_path)
a = len(imgs)
TP = 0
FN = 0
FP = 0
TN = 0
c = 0
for name in imgs:

    imgp = cv2.imread(pred_path + '/' + name, -1)
    imgp = np.array(imgp)

    imgl = cv2.imread(lab_path + '/' + name, -1)
    imgl = np.array(imgl)

    WIDTH = imgl.shape[0]
    HIGTH = imgl.shape[1]

    TP += tpcount(imgp, imgl)
    FN += fncount(imgp, imgl)
    FP += fpcount(imgp, imgl)
    TN += tncount(imgp, imgl)

    c += 1
    print('已经计算:'+str(c) + ',剩余数目:'+str(a-c))

print('TP:'+str(TP))
print('FN:'+str(FN))
print('FP:'+str(FP))
print('TN:'+str(TN))


#准确率
zq = (int(TN)+int(TP))/(int(WIDTH)*int(HIGTH)*int(len(imgs)))
#精确率
jq = int(TP)/(int(TP)+int(FP))
#召回率
zh = int(TP)/(int(TP)+int(FN))
#F1
f1 = int(TP)*2/(int(TP)*2+int(FN)+int(FP))

print('准确率:'+ str(zq))
print('精确率:'+ str(jq))
print('召回率:'+ str(zh))
print('F1值:'+ str(f1))

有任何疑问请直接在评论区提问!
有任何疑问请直接在评论区提问!
有任何疑问请直接在评论区提问!
重要的事说三遍!
(如非必要请勿私信,确有必要,请先点赞!)

版权专属小轩

你可能感兴趣的:(语义分割精度指标计算,深度学习)