Change values inside a Pytorch 3D tensor
I have a 224x224 binary image in a tensor (1, 224, 224), with 0-pixels representing background a 1-pixels representing foreground.
I want to reshape it in a tensor (2, 224, 224), such as the first "layer" gt[0] has 1-pixels where there were 0-pixels in the original image and viceversa. This way one layer should show 1s where there is background and the other one will have 1s on the foreground (basically I need to have two complementary binary images in this tensor).

This is my code:

# gt is a tensor (1, 224, 224)
gt = gt.expand((2, 224, 224))  
backgr = gt[0]
foregr = gt[1]

backgr[backgr == 0] = 2 # swap all 0s in 1s and viceversa
backgr[backgr == 1] = 0
backgr[backgr == 2] = 1

gt[0] = backgr

print(gt[0])
print(gt[1])


The problem is both layers are modified with this code and I can't figure out how to keep one of the two constant and change only gt[0].

Found a solution!

gt = gt.repeat(2, 1, 1)

