【手撕算法系列】mIoU
2023-12-17 15:42:49
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)
文章来源:https://blog.csdn.net/weixin_41845840/article/details/135044867
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!