Files

29 lines
1.2 KiB
Python
Raw Permalink Normal View History

2021-06-17 11:26:17 +08:00
import torch
import torch.nn as nn
if torch.cuda.is_available():
device = torch.device("cuda")
elif torch.backends.mps.is_available():
device = torch.device("mps")
else:
device = torch.device("cpu")
2021-06-17 11:26:17 +08:00
backwarp_tenGrid = {}
def warp(tenInput, tenFlow):
flow_device = tenFlow.device
k = (str(flow_device), str(tenFlow.size()))
2021-06-17 11:26:17 +08:00
if k not in backwarp_tenGrid:
tenHorizontal = torch.linspace(-1.0, 1.0, tenFlow.shape[3], device=flow_device).view(
2021-06-17 11:26:17 +08:00
1, 1, 1, tenFlow.shape[3]).expand(tenFlow.shape[0], -1, tenFlow.shape[2], -1)
tenVertical = torch.linspace(-1.0, 1.0, tenFlow.shape[2], device=flow_device).view(
2021-06-17 11:26:17 +08:00
1, 1, tenFlow.shape[2], 1).expand(tenFlow.shape[0], -1, -1, tenFlow.shape[3])
backwarp_tenGrid[k] = torch.cat(
[tenHorizontal, tenVertical], 1).to(flow_device)
2021-06-17 11:26:17 +08:00
tenFlow = torch.cat([tenFlow[:, 0:1, :, :] / ((tenInput.shape[3] - 1.0) / 2.0),
tenFlow[:, 1:2, :, :] / ((tenInput.shape[2] - 1.0) / 2.0)], 1)
g = (backwarp_tenGrid[k] + tenFlow).permute(0, 2, 3, 1)
return torch.nn.functional.grid_sample(input=tenInput, grid=g, mode='bilinear', padding_mode='border', align_corners=True)