【手撕算法系列】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)

你可能感兴趣的:(手撕算法,算法)