I assumed my background will be 1’s for where the class label(s) are 0’s and otherwise. Then, I summed the 1’s in the background and other the class label(s) to get their respective frequency.
torch.manual_seed(19)

labelA = torch.randint(low=0, high=2, size=(2,3, 3), dtype=torch.float64)
labelB = torch.randint(low=0, high=2, size=(2,3, 3), dtype=torch.float64)

create_background = torch.zeros((labelB.shape), dtype=torch.long)

for label in [labelA, labelB]:
    create_background |= label.long()
create_background = create_background^1
print(labelA)
print(labelB)
print(create_background)

> tensor([[[1., 0., 1.],
         [0., 0., 1.],
         [0., 0., 1.]],

        [[0., 0., 0.],
         [0., 1., 1.],
         [0., 0., 0.]]], dtype=torch.float64)
tensor([[[0., 1., 1.],
         [1., 0., 1.],
         [1., 1., 1.]],

        [[1., 0., 1.],
         [1., 1., 0.],
         [1., 1., 0.]]], dtype=torch.float64)
tensor([[[0, 0, 0],
         [0, 1, 0],
         [0, 0, 0]],

        [[0, 1, 0],
         [0, 0, 0],
         [0, 0, 1]]])

class_frequency = [int(torch.sum(i)) for i in [create_background, labelA, labelB]]
print("Class weight: ", class_frequency)
> Class frequency:  [3, 6, 13]