import torch
from typing import Optional


def count_classes(tensor: torch.Tensor, ignore_index: Optional[int] = None) -> int:
    """Infer the number of classes by getting the maximum class index, excluding the ignored one.

    :param tensor: generic tensor containing class indices
    :type tensor: torch.Tensor
    :param ignore_index: index to be ignored, defaults to None
    :type ignore_index: Optional[int], optional
    :return: maximum class index + 1 to account for 0-indexing
    :rtype: int
    """
    classes = tensor.unique()
    if ignore_index is not None:
        classes = classes[classes != ignore_index]
    return int(classes.max().item()) + 1