import torch


def calculate_binary_iou_batch(prediction, label):
    """
    Calculates an iou core for binary tensors, maintaining the batch dimension.
    Defaults to a value of 0 if the union is 0
    :param prediction: binary tensor of shape (batch, 1, x, y)
    :param label: binary tensor of shape (batch, 1, x, y)
    :return: tensor of shape (batch)
    """
    assert prediction.shape[1] == 1
    assert label.shape[1] == 1
    intersection = torch.sum(torch.logical_and(prediction, label), dim=[1, 2, 3])
    union = torch.sum(torch.logical_or(prediction, label), dim=[1, 2, 3])
    iou = torch.div(intersection, union)
    iou[torch.logical_or(torch.isinf(iou), torch.isnan(iou))] = 0
    return iou