简体   繁体   English

更改Pytorch 3D张量内的值

[英]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. 我在张量(1,2,224,224)中有一个224x224二进制图像,其中0像素代表背景,而1像素代表前景。 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. 我想在张量(2,224,224)中重塑形状,例如第一个“层” gt [0]具有1个像素,而原始图像中有0个像素,反之亦然。 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). 这样,一层应该在有背景的地方显示为1,而另一层在前景上的显示为1(基本上,我需要在该张量中具有两个互补的二进制图像)。

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]. 问题是这两层都使用此代码进行了修改,我无法弄清楚如何保持两个常量之一并仅更改gt [0]。

找到了解决方案!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM