【手撕算法系列】mIoU

import numpy as np

def compute_iou(y_true, y_pred):
    intersection = np.logical_and(y_true, y_pred)
    union = np.logical_or(y_true, y_pred)
    iou = np.sum(intersection) / np.sum(union)
    return iou

def compute_miou(y_true, y_pred, num_classes):
    iou_values = []
    for class_id in range(num_classes):
        true_class = (y_true == class_id)
        pred_class = (y_pred == class_id)
        iou = compute_iou(true_class, pred_class)
        iou_values.append(iou)
    
    mIoU = np.mean(iou_values)
    return mIoU

# Example usage:
# Assuming y_true and y_pred are numpy arrays representing ground truth and predicted segmentation masks.
# Each pixel should be assigned a class label.

# Example:
# y_true = np.array([[0, 0, 1], [1, 1, 2]])
# y_pred = np.array([[0, 0, 1], [1, 2, 2]])

# Number of classes (including background)
# Note: In this example, there are three classes (0, 1, 2)
num_classes = 3

mIoU = compute_miou(y_true, y_pred, num_classes)
print("mIoU:", mIoU)

import torch

def compute_iou(outputs, targets):
    intersection = torch.logical_and(outputs, targets)
    union = torch.logical_or(outputs, targets)
    iou = torch.sum(intersection.float()) / torch.sum(union.float())
    return iou

def compute_miou(outputs, targets, num_classes):
    iou_values = []
    for class_id in range(num_classes):
        output_class = (outputs == class_id)
        target_class = (targets == class_id)
        iou = compute_iou(output_class, target_class)
        iou_values.append(iou.item())

    mIoU = sum(iou_values) / num_classes
    return mIoU

# Example usage:
# Assuming outputs and targets are PyTorch tensors representing predicted and ground truth segmentation masks.
# Each pixel should be assigned a class label.

# Example:
# outputs = torch.tensor([[0, 0, 1], [1, 2, 2]])
# targets = torch.tensor([[0, 0, 1], [1, 1, 2]])

# Number of classes (including background)
# Note: In this example, there are three classes (0, 1, 2)
num_classes = 3

mIoU = compute_miou(outputs, targets, num_classes)
print("mIoU:", mIoU)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值