二分类语义分割评价指标代码(准确率、精确率、召回率、F1值)

import cv2
import numpy as np
import os

pred_path = r'Pred'
lab_path = r'GT'


def confusion_matrix_counts(imgp, imgl):
    # 确保图像具有相同的尺寸
    if imgp.shape != imgl.shape:
        raise ValueError("Image sizes do not match.")

        # 使用numpy的向量化操作来比较
    tp = np.sum((imgp != 0) & (imgl != 0))
    fn = np.sum((imgl != 0) & (imgp == 0))
    fp = np.sum((imgl == 0) & (imgp != 0))
    tn = np.prod(imgp.shape) - tp - fn - fp  # 总像素数减去其他三项
    return tp, fn, fp, tn


imgs = os.listdir(pred_path)
TP, FN, FP, TN = 0, 0, 0, 0

for name in imgs:
    imgp = cv2.imread(os.path.join(pred_path, name), -1)
    if imgp is None:
        continue  # 跳过无法读取的图像

    imgl = cv2.imread(os.path.join(lab_path, name), -1)
    if imgl is None or imgp.shape != imgl.shape:
        continue  # 跳过标签图像或尺寸不匹配的图像

    tp, fn, fp, tn = confusion_matrix_counts(imgp, imgl)
    TP += tp
    FN += fn
    FP += fp
    TN += tn

    print(f'Processed {name}, TP: {TP}, FN: {FN}, FP: {FP}, TN: {TN}')

# 计算性能指标
Accuracy = (TP + TN) / (TP + TN + FP + FN)
Precision = TP / (TP + FP) if (TP + FP) != 0 else 0
Recall = TP / (TP + FN) if (TP + FN) != 0 else 0
f1 = 2 * (Precision * Recall) / (Precision + Recall) if (Precision + Recall) != 0 else 0


print('准确率:', Accuracy)
print('精确率:', Precision)
print('召回率:', Recall)
print('F1值:', f1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

有梦想的炸豆皮

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

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

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

打赏作者

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

抵扣说明:

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

余额充值