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)
二分类语义分割评价指标代码(准确率、精确率、召回率、F1值)
于 2024-09-09 20:33:38 首次发布