torch.unique() method identifies uniques elements in a tensor. You can use (tensor).numel() method to find number of elements in a tensor.
Hence you can combine both and calculate total loss as:
loss = torch.unique(img_tensor).numel()