我试图让每像素转换以使一个图像(+背景)适合结果。 背景图像+输入图像应转换为所需的结果
为了实现这一点,我使用 PyTorch gridsampler 和 autograd 来优化网格。转换后的输入将添加到未更改的背景中。
ToTensor = torchvision.transforms.ToTensor()
FromTensor = torchvision.transforms.ToPILImage()
backround= ToTensor(Image.open("backround.png"))
pic = ToTensor(Image.open("pic.png"))
goal = ToTensor(Image.open("goal.png"))
empty = empty.expand(1, 3, empty.size()[1], empty.size()[2])
pic = pic.expand(1, 3, pic.size()[1], pic.size()[2])
goal = goal.expand(1, 3, goal.size()[1], goal.size()[2])
def createIdentityGrid(w, h):
grid = torch.zeros(1, w, h, 2);
for x in range(w):
for y in range(h):
grid[0][x][y][1] = 2 / w * (0.5 + x) - 1
grid[0][x][y][0] = 2 / h * (0.5 + y) - 1
return grid
w = 256; h=256 #hardcoded imagesize
grid = createIdentityGrid(w, h)
grid.requires_grad = True
for i in range(300):
goal_pred = torch.nn.functional.grid_sample(pic, grid)[0]
goal_pred = (empty + 0.75 * goal_pred).clamp(min=0, max=1)
out = goal_pred
loss = (goal_pred - goal).pow(2).sum()
loss.backward()
with torch.no_grad():
grid -= grid.grad * (1e-2)
grid.grad.zero_()
FromTensor(out[0]).show()
结果如下:
它实际上正在使用这个简单的示例,但我观察到一些奇怪的行为。网格刚刚开始在一侧发生变化。为什么会这样,为什么整个网格不会立即改变?我缺少一些明显的部分吗?