SWHL commited on
Commit
1828176
·
1 Parent(s): 4e83346

First commit

Browse files
.gitignore ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ pip-wheel-metadata/
24
+ share/python-wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+ MANIFEST
29
+
30
+ # PyInstaller
31
+ # Usually these files are written by a python script from a template
32
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
33
+ *.manifest
34
+ *.spec
35
+
36
+ # Installer logs
37
+ pip-log.txt
38
+ pip-delete-this-directory.txt
39
+
40
+ # Unit test / coverage reports
41
+ htmlcov/
42
+ .tox/
43
+ .nox/
44
+ .coverage
45
+ .coverage.*
46
+ .cache
47
+ nosetests.xml
48
+ coverage.xml
49
+ *.cover
50
+ *.py,cover
51
+ .hypothesis/
52
+ .pytest_cache/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ target/
76
+
77
+ # Jupyter Notebook
78
+ .ipynb_checkpoints
79
+
80
+ # IPython
81
+ profile_default/
82
+ ipython_config.py
83
+
84
+ # pyenv
85
+ .python-version
86
+
87
+ # pipenv
88
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
90
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
91
+ # install all needed dependencies.
92
+ #Pipfile.lock
93
+
94
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95
+ __pypackages__/
96
+
97
+ # Celery stuff
98
+ celerybeat-schedule
99
+ celerybeat.pid
100
+
101
+ # SageMath parsed files
102
+ *.sage.py
103
+
104
+ # Environments
105
+ .env
106
+ .venv
107
+ env/
108
+ venv/
109
+ ENV/
110
+ env.bak/
111
+ venv.bak/
112
+
113
+ # Spyder project settings
114
+ .spyderproject
115
+ .spyproject
116
+
117
+ # Rope project settings
118
+ .ropeproject
119
+
120
+ # mkdocs documentation
121
+ /site
122
+
123
+ # mypy
124
+ .mypy_cache/
125
+ .dmypy.json
126
+ dmypy.json
127
+
128
+ # Pyre type checker
129
+ .pyre/
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2022 CVLab@StonyBrook
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md CHANGED
@@ -1,13 +0,0 @@
1
- ---
2
- title: PaperEdgeDemo
3
- emoji: 🌖
4
- colorFrom: blue
5
- colorTo: green
6
- sdk: gradio
7
- sdk_version: 3.6
8
- app_file: app.py
9
- pinned: false
10
- license: mit
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- encoding: utf-8 -*-
2
+ import copy
3
+ import os
4
+
5
+ os.system('pip install -r requirements.txt')
6
+
7
+ import time
8
+ from pathlib import Path
9
+ import cv2
10
+ import numpy as np
11
+ import torch
12
+ import torch.nn.functional as F
13
+ from networks.paperedge_cpu import GlobalWarper, LocalWarper, WarperUtil
14
+ import gradio as gr
15
+
16
+
17
+ cv2.setNumThreads(0)
18
+ cv2.ocl.setUseOpenCL(False)
19
+
20
+
21
+ class PaperEdge(object):
22
+ def __init__(self, enet_path, tnet_path, device, dst_dir) -> None:
23
+ self.device = device
24
+ self.dst_dir = dst_dir
25
+
26
+ self.netG = GlobalWarper().to(device)
27
+ netG_state = torch.load(enet_path, map_location=device)['G']
28
+ self.netG.load_state_dict(netG_state)
29
+ self.netG.eval()
30
+
31
+ self.netL = LocalWarper().to(device)
32
+ netL_state = torch.load(tnet_path, map_location=device)['L']
33
+ self.netL.load_state_dict(netL_state)
34
+ self.netL.eval()
35
+
36
+ self.warpUtil = WarperUtil(64).to(device)
37
+
38
+ @staticmethod
39
+ def load_img(img_path):
40
+ im = cv2.imread(img_path).astype(np.float32) / 255.0
41
+ im = im[:, :, (2, 1, 0)]
42
+ im = cv2.resize(im, (256, 256), interpolation=cv2.INTER_AREA)
43
+ im = torch.from_numpy(np.transpose(im, (2, 0, 1)))
44
+ return im
45
+
46
+ def __call__(self, img_path):
47
+ time_stamp = time.strftime('%Y-%m-%d-%H-%M-%S',
48
+ time.localtime(time.time()))
49
+
50
+ gs_d, ls_d = None, None
51
+ with torch.no_grad():
52
+ x = self.load_img(img_path)
53
+ x = x.unsqueeze(0).to(self.device)
54
+
55
+ d = self.netG(x)
56
+
57
+ d = self.warpUtil.global_post_warp(d, 64)
58
+
59
+ gs_d = copy.deepcopy(d)
60
+
61
+ d = F.interpolate(d, size=256, mode='bilinear', align_corners=True)
62
+ y0 = F.grid_sample(x, d.permute(0, 2, 3, 1), align_corners=True)
63
+ ls_d = self.netL(y0)
64
+
65
+ ls_d = F.interpolate(ls_d, size=256, mode='bilinear', align_corners=True)
66
+ ls_d = ls_d.clamp(-1.0, 1.0)
67
+
68
+ im = cv2.imread(img_path).astype(np.float32) / 255.0
69
+ im = torch.from_numpy(np.transpose(im, (2, 0, 1)))
70
+ im = im.to(self.device).unsqueeze(0)
71
+
72
+ gs_d = F.interpolate(gs_d, (im.size(2), im.size(3)), mode='bilinear', align_corners=True)
73
+ gs_y = F.grid_sample(im, gs_d.permute(0, 2, 3, 1), align_corners=True).detach()
74
+
75
+ ls_d = F.interpolate(ls_d, (im.size(2), im.size(3)), mode='bilinear', align_corners=True)
76
+ ls_y = F.grid_sample(gs_y, ls_d.permute(0, 2, 3, 1), align_corners=True).detach()
77
+ ls_y = ls_y.squeeze().permute(1, 2, 0).cpu().numpy()
78
+
79
+ save_path = f'{self.dst_dir}/{time_stamp}.png'
80
+ cv2.imwrite(save_path, ls_y * 255.)
81
+ return save_path
82
+
83
+
84
+ def inference(img):
85
+ img_path = img.name
86
+ save_img_path = paper_edge(img_path)
87
+ return save_img_path
88
+
89
+
90
+ enet_path = 'models/G_w_checkpoint_13820.pt'
91
+ tnet_path = 'models/L_w_checkpoint_27640.pt'
92
+ device = torch.device('cpu')
93
+
94
+ dst_dir = Path('inference/')
95
+ if not dst_dir.exists():
96
+ dst_dir.mkdir(parents=True, exist_ok=True)
97
+
98
+ paper_edge = PaperEdge(enet_path, tnet_path, device, dst_dir)
99
+
100
+ title = 'PaperEdge Demo'
101
+ description = 'This is the demo for the paper "Learning From Documents in the Wild to Improve Document Unwarping" (SIGGRAPH 2022). Github repo: https://github.com/cvlab-stonybrook/PaperEdge'
102
+ css = ".output_image, .input_image {height: 40rem !important; width: 100% !important;}"
103
+
104
+ gr.Interface(
105
+ inference,
106
+ inputs=gr.inputs.Image(type='file', label='Input'),
107
+ outputs=[
108
+ gr.outputs.Image(type='file', label='Output_image'),
109
+ ],
110
+ title=title,
111
+ description=description,
112
+ css=css,
113
+ allow_flagging='never',
114
+ ).launch(debug=True, enable_queue=True)
demo_cpu.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- encoding: utf-8 -*-
2
+ import argparse
3
+ import copy
4
+ import time
5
+ from pathlib import Path
6
+
7
+ import cv2
8
+ import numpy as np
9
+ import torch
10
+ import torch.nn.functional as F
11
+ from networks.paperedge_cpu import GlobalWarper, LocalWarper, WarperUtil
12
+
13
+ cv2.setNumThreads(0)
14
+ cv2.ocl.setUseOpenCL(False)
15
+
16
+
17
+ class PaperEdge(object):
18
+ def __init__(self, enet_path, tnet_path, device) -> None:
19
+ self.device = device
20
+
21
+ self.netG = GlobalWarper().to(device)
22
+ netG_state = torch.load(enet_path, map_location=device)['G']
23
+ self.netG.load_state_dict(netG_state)
24
+ self.netG.eval()
25
+
26
+ self.netL = LocalWarper().to(device)
27
+ netL_state = torch.load(tnet_path, map_location=device)['L']
28
+ self.netL.load_state_dict(netL_state)
29
+ self.netL.eval()
30
+
31
+ self.warpUtil = WarperUtil(64).to(device)
32
+
33
+ @staticmethod
34
+ def load_img(img_path):
35
+ im = cv2.imread(img_path).astype(np.float32) / 255.0
36
+ im = im[:, :, (2, 1, 0)]
37
+ im = cv2.resize(im, (256, 256), interpolation=cv2.INTER_AREA)
38
+ im = torch.from_numpy(np.transpose(im, (2, 0, 1)))
39
+ return im
40
+
41
+ def infer(self, img_path):
42
+ gs_d, ls_d = None, None
43
+ with torch.no_grad():
44
+ x = self.load_img(img_path)
45
+ x = x.unsqueeze(0).to(self.device)
46
+
47
+ d = self.netG(x)
48
+
49
+ d = self.warpUtil.global_post_warp(d, 64)
50
+
51
+ gs_d = copy.deepcopy(d)
52
+
53
+ d = F.interpolate(d, size=256, mode='bilinear', align_corners=True)
54
+ y0 = F.grid_sample(x, d.permute(0, 2, 3, 1), align_corners=True)
55
+ ls_d = self.netL(y0)
56
+
57
+ ls_d = F.interpolate(ls_d, size=256, mode='bilinear', align_corners=True)
58
+ ls_d = ls_d.clamp(-1.0, 1.0)
59
+
60
+ im = cv2.imread(img_path).astype(np.float32) / 255.0
61
+ im = torch.from_numpy(np.transpose(im, (2, 0, 1)))
62
+ im = im.to(self.device).unsqueeze(0)
63
+
64
+ gs_d = F.interpolate(gs_d, (im.size(2), im.size(3)), mode='bilinear', align_corners=True)
65
+ gs_y = F.grid_sample(im, gs_d.permute(0, 2, 3, 1), align_corners=True).detach()
66
+
67
+ ls_d = F.interpolate(ls_d, (im.size(2), im.size(3)), mode='bilinear', align_corners=True)
68
+ ls_y = F.grid_sample(gs_y, ls_d.permute(0, 2, 3, 1), align_corners=True).detach()
69
+ ls_y = ls_y.squeeze().permute(1, 2, 0).cpu().numpy()
70
+
71
+ save_path = f'{dst_dir}/result_ls.png'
72
+ cv2.imwrite(save_path, ls_y * 255.)
73
+ return save_path
74
+
75
+
76
+ if __name__ == '__main__':
77
+ parser = argparse.ArgumentParser()
78
+ parser.add_argument('--Enet_ckpt', type=str,
79
+ default='models/G_w_checkpoint_13820.pt')
80
+ parser.add_argument('--Tnet_ckpt', type=str,
81
+ default='models/L_w_checkpoint_27640.pt')
82
+ parser.add_argument('--img_path', type=str, default='images/3.jpg')
83
+ parser.add_argument('--out_dir', type=str, default='output')
84
+ parser.add_argument('--device', type=str, default='cpu')
85
+ args = parser.parse_args()
86
+
87
+ if args.device == 'cuda' and torch.cuda.is_available():
88
+ device = torch.device('cuda:0')
89
+ else:
90
+ device = torch.device('cpu')
91
+
92
+ dst_dir = args.out_dir
93
+ Path(dst_dir).mkdir(parents=True, exist_ok=True)
94
+
95
+ paper_edge = PaperEdge(args.Enet_ckpt, args.Tnet_ckpt, args.device)
96
+
97
+ paper_edge.inder(args.img_path)
98
+ print('ok')
models/G_w_checkpoint_13820.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:49489f5490f6786e4cc6896b47c3ff6511a92438fec1b3be7b1c53580975236f
3
+ size 146530295
models/L_w_checkpoint_27640.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eed0653d9c9fa2bd1b21f469336fc534bfaebfe20422624581141b47ddab7b6f
3
+ size 146530295
networks/__init__.py ADDED
File without changes
networks/paperedge.py ADDED
@@ -0,0 +1,553 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ # from torch.nn.utils import spectral_norm as SN
5
+ # from torchvision.models.densenet import _DenseBlock
6
+ from .tps_warp import TpsWarp, PspWarp
7
+ from functools import partial
8
+ # import plotly.graph_objects as go
9
+ import random
10
+ import numpy as np
11
+ import cv2
12
+
13
+ torch.autograd.set_detect_anomaly(True)
14
+ # torch.manual_seed(0)
15
+
16
+ def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
17
+ """3x3 convolution with padding"""
18
+ return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
19
+ padding=dilation, groups=groups, bias=False, dilation=dilation)
20
+
21
+
22
+ def conv1x1(in_planes, out_planes, stride=1):
23
+ """1x1 convolution"""
24
+ return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
25
+
26
+
27
+ class BasicBlock(nn.Module):
28
+ expansion = 1
29
+
30
+ def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
31
+ base_width=64, dilation=1, norm_layer=None):
32
+ super(BasicBlock, self).__init__()
33
+ if norm_layer is None:
34
+ norm_layer = nn.BatchNorm2d
35
+ if groups != 1 or base_width != 64:
36
+ raise ValueError('BasicBlock only supports groups=1 and base_width=64')
37
+ if dilation > 1:
38
+ raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
39
+ # Both self.conv1 and self.downsample layers downsample the input when stride != 1
40
+ self.conv1 = conv3x3(inplanes, planes, stride)
41
+ self.bn1 = norm_layer(planes)
42
+ self.actv = nn.ReLU()
43
+ self.conv2 = conv3x3(planes, planes)
44
+ self.bn2 = norm_layer(planes)
45
+ self.downsample = downsample
46
+ self.stride = stride
47
+
48
+ def forward(self, x):
49
+ identity = x
50
+
51
+ out = self.conv1(x)
52
+ out = self.bn1(out)
53
+ out = self.actv(out)
54
+
55
+ out = self.conv2(out)
56
+ out = self.bn2(out)
57
+
58
+ if self.downsample is not None:
59
+ identity = self.downsample(x)
60
+
61
+ out += identity
62
+ out = self.actv(out)
63
+
64
+ return out
65
+
66
+ def _make_layer(block, inplanes, planes, blocks, stride=1, dilate=False):
67
+ norm_layer = nn.BatchNorm2d
68
+ downsample = None
69
+
70
+ if stride != 1 or inplanes != planes * block.expansion:
71
+ downsample = nn.Sequential(
72
+ nn.Conv2d(inplanes, planes * block.expansion, 1, stride, bias=False),
73
+ norm_layer(planes * block.expansion),
74
+ )
75
+
76
+ layers = []
77
+ layers.append(block(inplanes, planes, stride, downsample, norm_layer=norm_layer))
78
+ for _ in range(1, blocks):
79
+ layers.append(block(planes, planes,
80
+ norm_layer=norm_layer))
81
+
82
+ return nn.Sequential(*layers)
83
+
84
+ class Interpolate(nn.Module):
85
+ def __init__(self, size, mode):
86
+ super(Interpolate, self).__init__()
87
+ self.interp = nn.functional.interpolate
88
+ self.size = size
89
+ self.mode = mode
90
+
91
+ def forward(self, x):
92
+ x = self.interp(x, size=self.size, mode=self.mode, align_corners=True)
93
+ return x
94
+
95
+ class GlobalWarper(nn.Module):
96
+ def __init__(self):
97
+ super(GlobalWarper, self).__init__()
98
+ modules = [
99
+ nn.Conv2d(5, 64, kernel_size=7, stride=2, padding=3, bias=False),
100
+ nn.BatchNorm2d(64),
101
+ nn.ReLU()
102
+ ]
103
+
104
+ # encoder
105
+ planes = [64, 128, 256, 256, 512, 512]
106
+ strides = [2, 2, 2, 2, 2]
107
+ blocks = [1, 1, 1, 1, 1]
108
+ for k in range(len(planes) - 1):
109
+ modules.append(_make_layer(BasicBlock, planes[k], planes[k + 1], blocks[k], strides[k]))
110
+ self.encoder = nn.Sequential(*modules)
111
+
112
+ # decoder
113
+ modules = []
114
+ planes = [512, 512, 256, 128, 64]
115
+ strides = [2, 2, 2, 2]
116
+ # tsizes = [3, 5, 9, 17, 33]
117
+ blocks = [1, 1, 1, 1]
118
+ for k in range(len(planes) - 1):
119
+ # modules += [nn.Sequential(Interpolate(size=tsizes[k], mode='bilinear'),
120
+ # _make_layer(BasicBlock, planes[k], planes[k + 1], blocks[k], 1))]
121
+ modules += [nn.Sequential(nn.Upsample(scale_factor=strides[k], mode='bilinear', align_corners=True),
122
+ _make_layer(BasicBlock, planes[k], planes[k + 1], blocks[k], 1))]
123
+ # self.decoder = nn.ModuleList(modules)
124
+ self.decoder = nn.Sequential(*modules)
125
+
126
+ self.to_warp = nn.Sequential(nn.Conv2d(64, 2, 1))
127
+ self.to_warp[0].weight.data.fill_(0.0)
128
+ self.to_warp[0].bias.data.fill_(0.0)
129
+
130
+ iy, ix = torch.meshgrid(torch.linspace(-1, 1, 256), torch.linspace(-1, 1, 256))
131
+ self.coord = torch.stack((ix, iy), dim=0).unsqueeze(0).to('cuda')
132
+ iy, ix = torch.meshgrid(torch.linspace(-1, 1, 64), torch.linspace(-1, 1, 64))
133
+ ### note we mulitply a 0.9 so the network is initialized closer to GT. This is different from localwarper net
134
+ self.basegrid = torch.stack((ix * 0.9, iy * 0.9), dim=0).unsqueeze(0).to('cuda')
135
+
136
+ # # box filter
137
+ # ksize = 7
138
+ # p = int((ksize - 1) / 2)
139
+ # self.pad_replct = partial(F.pad, pad=(p, p, p, p), mode='replicate')
140
+ # bw = torch.ones(1, 1, ksize, ksize, device='cuda') / ksize / ksize
141
+ # self.box_filter = partial(F.conv2d, weight=bw)
142
+
143
+
144
+
145
+ def forward(self, im):
146
+ # print(self.to_warp[0].weight.data)
147
+ # coordconv
148
+ B = im.size(0)
149
+ c = self.coord.expand(B, -1, -1, -1).detach()
150
+ t = torch.cat((im, c), dim=1)
151
+
152
+ t = self.encoder(t)
153
+ t = self.decoder(t)
154
+ t = self.to_warp(t)
155
+
156
+ gs = t + self.basegrid
157
+
158
+ return gs
159
+
160
+ class LocalWarper(nn.Module):
161
+ def __init__(self):
162
+ super().__init__()
163
+ modules = [
164
+ nn.Conv2d(5, 64, kernel_size=7, stride=2, padding=3, bias=False),
165
+ nn.BatchNorm2d(64),
166
+ nn.ReLU()
167
+ ]
168
+ # encoder
169
+ planes = [64, 128, 256, 256, 512, 512]
170
+ strides = [2, 2, 2, 2, 2]
171
+ blocks = [1, 1, 1, 1, 1]
172
+ for k in range(len(planes) - 1):
173
+ modules.append(_make_layer(BasicBlock, planes[k], planes[k + 1], blocks[k], strides[k]))
174
+ self.encoder = nn.Sequential(*modules)
175
+
176
+ # decoder
177
+ modules = []
178
+ planes = [512, 512, 256, 128, 64]
179
+ strides = [2, 2, 2, 2]
180
+ # tsizes = [3, 5, 9, 17, 33]
181
+ blocks = [1, 1, 1, 1]
182
+ for k in range(len(planes) - 1):
183
+ modules += [nn.Sequential(nn.Upsample(scale_factor=strides[k], mode='bilinear', align_corners=True),
184
+ _make_layer(BasicBlock, planes[k], planes[k + 1], blocks[k], 1))]
185
+ self.decoder = nn.Sequential(*modules)
186
+
187
+ self.to_warp = nn.Sequential(nn.Conv2d(64, 2, 1))
188
+ self.to_warp[0].weight.data.fill_(0.0)
189
+ self.to_warp[0].bias.data.fill_(0.0)
190
+
191
+ iy, ix = torch.meshgrid(torch.linspace(-1, 1, 256), torch.linspace(-1, 1, 256))
192
+ self.coord = torch.stack((ix, iy), dim=0).unsqueeze(0).to('cuda')
193
+ iy, ix = torch.meshgrid(torch.linspace(-1, 1, 64), torch.linspace(-1, 1, 64))
194
+ self.basegrid = torch.stack((ix, iy), dim=0).unsqueeze(0).to('cuda')
195
+
196
+ # box filter
197
+ ksize = 5
198
+ p = int((ksize - 1) / 2)
199
+ self.pad_replct = partial(F.pad, pad=(p, p, p, p), mode='replicate')
200
+ bw = torch.ones(1, 1, ksize, ksize, device='cuda') / ksize / ksize
201
+ self.box_filter = partial(F.conv2d, weight=bw)
202
+
203
+ def forward(self, im):
204
+ c = self.coord.expand(im.size(0), -1, -1, -1).detach()
205
+ t = torch.cat((im, c), dim=1)
206
+
207
+ # encoder
208
+ t = self.encoder(t)
209
+ t = self.decoder(t)
210
+ t = self.to_warp(t)
211
+
212
+ # # filter
213
+ # t = self.pad_replct(t)
214
+ # tx = self.box_filter(t[:, 0 : 1, ...])
215
+ # ty = self.box_filter(t[:, 1 : 2, ...])
216
+ # t = torch.cat((tx, ty), dim=1)
217
+
218
+ # bd condition
219
+ t[..., 1, 0, :] = 0
220
+ t[..., 1, -1, :] = 0
221
+ t[..., 0, :, 0] = 0
222
+ t[..., 0, :, -1] = 0
223
+
224
+ gs = t + self.basegrid
225
+ return gs
226
+
227
+ def gs_to_bd(gs):
228
+ # gs: B 2 H W
229
+ t = torch.cat([gs[..., 0, :], gs[..., -1, :], gs[..., 1 : -1, 0], gs[..., 1 : -1, -1]], dim=2).permute(0, 2, 1)
230
+ # t: B 2(W + H - 1) 2
231
+ return t
232
+
233
+ class MaskLoss(nn.Module):
234
+ def __init__(self, gsize):
235
+ super().__init__()
236
+ self.tpswarper = TpsWarp(gsize)
237
+ self.pspwarper = PspWarp()
238
+ # self.imsize = imsize
239
+ self.msk = torch.ones(1, 1, gsize, gsize, device='cuda')
240
+ self.cn = torch.tensor([[-1, -1], [1, -1], [1, 1], [-1, 1]], dtype=torch.float, device='cuda').unsqueeze(0)
241
+
242
+ def forward(self, gs, y, s):
243
+ # resize gs to s*s
244
+ B, _, s0, _ = gs.size()
245
+ tgs = F.interpolate(gs, s, mode='bilinear', align_corners=True)
246
+
247
+ # use only the boundary points
248
+ srcpts = gs_to_bd(tgs)
249
+ iy, ix = torch.meshgrid(torch.linspace(-1, 1, s), torch.linspace(-1, 1, s))
250
+ t = torch.stack((ix, iy), dim=0).unsqueeze(0).to('cuda').expand_as(tgs)
251
+ dstpts = gs_to_bd(t)
252
+
253
+ tgs_f = self.tpswarper(srcpts, dstpts.detach())
254
+ ym = self.msk.expand_as(y)
255
+ yh = F.grid_sample(ym, tgs_f.permute(0, 2, 3, 1), align_corners=True)
256
+ loss_f = F.l1_loss(yh, y)
257
+
258
+ # forward/backward consistency loss
259
+ tgs_b = self.tpswarper(dstpts.detach(), srcpts)
260
+ # tgs_b = F.interpolate(tgs, s0, mode='bilinear', align_corners=True)
261
+ yy = F.grid_sample(y, tgs_b.permute(0, 2, 3, 1), align_corners=True)
262
+ loss_b = F.l1_loss(yy, ym)
263
+
264
+ return loss_f + loss_b, tgs_f
265
+
266
+ def _dist(self, x):
267
+ # adjacent point distance
268
+ # B, 2, n
269
+ x = torch.cat([x[..., 0 : 1].detach(), x[..., 1 : -1], x[..., -1 : ].detach()], dim=2)
270
+ d = x[..., 1:] - x[..., :-1]
271
+ return torch.norm(d, dim=1)
272
+
273
+ # class TVLoss(nn.Module):
274
+ # def __init__(self):
275
+ # super(TVLoss, self).__init__()
276
+
277
+ # def forward(self, gs):
278
+ # loss = self._dist(gs[..., 1:], gs[..., :-1]) + self._dist(gs[..., 1:, :], gs[..., :-1, :])
279
+ # return loss
280
+
281
+ # def _dist(self, x1, x0):
282
+ # d = torch.norm(x1 - x0, dim=1, keepdim=True)
283
+ # d = torch.abs(d - torch.mean(d, dim=(2, 3), keepdim=True)).mean()
284
+ # return d
285
+
286
+ class WarperUtil(nn.Module):
287
+ def __init__(self, imsize):
288
+ super().__init__()
289
+ self.tpswarper = TpsWarp(imsize)
290
+ self.pspwarper = PspWarp()
291
+ self.s = imsize
292
+
293
+ def global_post_warp(self, gs, s):
294
+ # B, _, s0, _ = gs.size()
295
+ gs = F.interpolate(gs, s, mode='bilinear', align_corners=True)
296
+ # gs = F.interpolate(gs, s0, mode='bilinear', align_corners=True)
297
+ # extract info
298
+ m1 = gs[..., 0, :]
299
+ m2 = gs[..., -1, :]
300
+ n1 = gs[..., 0]
301
+ n2 = gs[..., -1]
302
+ # for x
303
+ m1x_interval_ratio = m1[:, 0, 1:] - m1[:, 0, :-1]
304
+ m1x_interval_ratio /= m1x_interval_ratio.sum(dim=1, keepdim=True)
305
+ m2x_interval_ratio = m2[:, 0, 1:] - m2[:, 0, :-1]
306
+ m2x_interval_ratio /= m2x_interval_ratio.sum(dim=1, keepdim=True)
307
+ # interpolate all x ratio
308
+ t = torch.stack([m1x_interval_ratio, m2x_interval_ratio], dim=1).unsqueeze(1)
309
+ mx_interval_ratio = F.interpolate(t, (s, m1x_interval_ratio.size(1)), mode='bilinear', align_corners=True)
310
+ mx_interval = (n2[..., 0 : 1, :] - n1[..., 0 : 1, :]).unsqueeze(3) * mx_interval_ratio
311
+ # cumsum to x
312
+ dx = torch.cumsum(mx_interval, dim=3) + n1[..., 0 : 1, :].unsqueeze(3)
313
+ dx = dx[..., 1 : -1, :-1]
314
+ # for y
315
+ n1y_interval_ratio = n1[:, 1, 1:] - n1[:, 1, :-1]
316
+ n1y_interval_ratio /= n1y_interval_ratio.sum(dim=1, keepdim=True)
317
+ n2y_interval_ratio = n2[:, 1, 1:] - n2[:, 1, :-1]
318
+ n2y_interval_ratio /= n2y_interval_ratio.sum(dim=1, keepdim=True)
319
+ # interpolate all x ratio
320
+ t = torch.stack([n1y_interval_ratio, n2y_interval_ratio], dim=2).unsqueeze(1)
321
+ ny_interval_ratio = F.interpolate(t, (n1y_interval_ratio.size(1), s), mode='bilinear', align_corners=True)
322
+ ny_interval = (m2[..., 1 : 2, :] - m1[..., 1 : 2, :]).unsqueeze(2) * ny_interval_ratio
323
+ # cumsum to y
324
+ dy = torch.cumsum(ny_interval, dim=2) + m1[..., 1 : 2, :].unsqueeze(2)
325
+ dy = dy[..., :-1, 1 : -1]
326
+ ds = torch.cat((dx, dy), dim=1)
327
+ gs[..., 1 : -1, 1 : -1] = ds
328
+ return gs
329
+
330
+ def perturb_warp(self, dd):
331
+ B = dd.size(0)
332
+ s = self.s
333
+ # -0.2 to 0.2
334
+ iy, ix = torch.meshgrid(torch.linspace(-1, 1, s), torch.linspace(-1, 1, s))
335
+ t = torch.stack((ix, iy), dim=0).unsqueeze(0).to('cuda').expand(B, -1, -1, -1)
336
+
337
+ tt = t.clone()
338
+
339
+ nd = random.randint(0, 4)
340
+ for ii in range(nd):
341
+ # define deformation on bd
342
+ pm = (torch.rand(B, 1) - 0.5) * 0.2
343
+ ps = (torch.rand(B, 1) - 0.5) * 1.95
344
+ pt = ps + pm
345
+ pt = pt.clamp(-0.975, 0.975)
346
+ # put it on one bd
347
+ # [1, 1] or [-1, 1] or [-1, -1] etc
348
+ a1 = (torch.rand(B, 2) > 0.5).float() * 2 -1
349
+ # select one col for every row
350
+ a2 = torch.rand(B, 1) > 0.5
351
+ a2 = torch.cat([a2, a2.bitwise_not()], dim=1)
352
+ a3 = a1.clone()
353
+ a3[a2] = ps.view(-1)
354
+ ps = a3.clone()
355
+ a3[a2] = pt.view(-1)
356
+ pt = a3.clone()
357
+ # 2 N 4
358
+ bds = torch.stack([
359
+ t[0, :, 1 : -1, 0], t[0, :, 1 : -1, -1], t[0, :, 0, 1 : -1], t[0, :, -1, 1 : -1]
360
+ ], dim=2)
361
+
362
+ pbd = a2.bitwise_not().float() * a1
363
+ # id of boundary p is on
364
+ pbd = torch.abs(0.5 * pbd[:, 0] + 2.5 * pbd[:, 1] + 0.5).long()
365
+ # ids of other boundaries
366
+ pbd = torch.stack([pbd + 1, pbd + 2, pbd + 3], dim=1) % 4
367
+ # print(pbd)
368
+ pbd = bds[..., pbd].permute(2, 0, 1, 3).reshape(B, 2, -1)
369
+
370
+ srcpts = torch.stack([
371
+ t[..., 0, 0], t[..., 0, -1], t[..., -1, 0], t[..., -1, -1],
372
+ ps.to('cuda')
373
+ ], dim=2)
374
+ srcpts = torch.cat([pbd, srcpts], dim=2).permute(0, 2, 1)
375
+ dstpts = torch.stack([
376
+ t[..., 0, 0], t[..., 0, -1], t[..., -1, 0], t[..., -1, -1],
377
+ pt.to('cuda')
378
+ ], dim=2)
379
+ dstpts = torch.cat([pbd, dstpts], dim=2).permute(0, 2, 1)
380
+ # print(srcpts)
381
+ # print(dstpts)
382
+ tgs = self.tpswarper(srcpts, dstpts)
383
+ tt = F.grid_sample(tt, tgs.permute(0, 2, 3, 1), align_corners=True)
384
+
385
+ nd = random.randint(1, 5)
386
+ for ii in range(nd):
387
+
388
+ pm = (torch.rand(B, 2) - 0.5) * 0.2
389
+ ps = (torch.rand(B, 2) - 0.5) * 1.95
390
+ pt = ps + pm
391
+ pt = pt.clamp(-0.975, 0.975)
392
+
393
+ srcpts = torch.cat([
394
+ t[..., -1, :], t[..., 0, :], t[..., 1 : -1, 0], t[..., 1 : -1, -1],
395
+ ps.unsqueeze(2).to('cuda')
396
+ ], dim=2).permute(0, 2, 1)
397
+ dstpts = torch.cat([
398
+ t[..., -1, :], t[..., 0, :], t[..., 1 : -1, 0], t[..., 1 : -1, -1],
399
+ pt.unsqueeze(2).to('cuda')
400
+ ], dim=2).permute(0, 2, 1)
401
+ tgs = self.tpswarper(srcpts, dstpts)
402
+ tt = F.grid_sample(tt, tgs.permute(0, 2, 3, 1), align_corners=True)
403
+ tgs = tt
404
+
405
+ # sample tgs to gen invtgs
406
+ num_sample = 512
407
+ # n = (H-2)*(W-2)
408
+ n = s * s
409
+ idx = torch.randperm(n)
410
+ idx = idx[:num_sample]
411
+ srcpts = tgs.reshape(-1, 2, n)[..., idx].permute(0, 2, 1)
412
+ dstpts = t.reshape(-1, 2, n)[..., idx].permute(0, 2, 1)
413
+ invtgs = self.tpswarper(srcpts, dstpts)
414
+ return tgs, invtgs
415
+
416
+ def equal_spacing_interpolate(self, gs, s):
417
+ def equal_bd(x, s):
418
+ # x is B 2 n
419
+ v0 = x[..., :-1] # B 2 n-1
420
+ v = x[..., 1:] - x[..., :-1]
421
+ vn = v.norm(dim=1, keepdim=True)
422
+ v = v / vn
423
+ c = vn.sum(dim=2, keepdim=True) #B 1 1
424
+ a = vn / c
425
+ b = torch.cumsum(a, dim=2)
426
+ b = torch.cat((torch.zeros(B, 1, 1, device='cuda'), b[..., :-1]), dim=2)
427
+
428
+ t = torch.linspace(1e-5, 1 - 1e-5, s).view(1, s, 1).to('cuda')
429
+ t = t - b # B s n-1
430
+ # print(t)
431
+
432
+ tt = torch.cat((t, -torch.ones(B, s, 1, device='cuda')), dim=2) # B s n
433
+ tt = tt[..., 1:] * tt[..., :-1] # B s n-1
434
+ tt = (tt < 0).float()
435
+ d = torch.matmul(v0, tt.permute(0, 2, 1)) + torch.matmul(v, (tt * t).permute(0, 2, 1)) # B 2 s
436
+ # print(d)
437
+ return d
438
+
439
+ gs = F.interpolate(gs, s, mode='bilinear', align_corners=True)
440
+ B = gs.size(0)
441
+ dst_cn = torch.tensor([[-1, -1], [1, -1], [1, 1], [-1, 1]], dtype=torch.float, device='cuda').expand(B, -1, -1)
442
+ src_cn = torch.stack([gs[..., 0, 0], gs[..., 0, -1], gs[..., -1, -1], gs[..., -1, 0]], dim=2).permute(0, 2, 1)
443
+ M = self.pspwarper.pspmat(src_cn, dst_cn).detach()
444
+ invM = self.pspwarper.pspmat(dst_cn, src_cn).detach()
445
+ pgs = self.pspwarper(gs.permute(0, 2, 3, 1).reshape(B, -1, 2), M).reshape(B, s, s, 2).permute(0, 3, 1, 2)
446
+ t = [pgs[..., 0, :], pgs[..., -1, :], pgs[..., :, 0], pgs[..., :, -1]]
447
+ d = []
448
+ for x in t:
449
+ d.append(equal_bd(x, s))
450
+ pgs[..., 0, :] = d[0]
451
+ pgs[..., -1, :] = d[1]
452
+ pgs[..., :, 0] = d[2]
453
+ pgs[..., :, -1] = d[3]
454
+ gs = self.pspwarper(pgs.permute(0, 2, 3, 1).reshape(B, -1, 2), invM).reshape(B, s, s, 2).permute(0, 3, 1, 2)
455
+ gs = self.global_post_warp(gs, s)
456
+ return gs
457
+
458
+
459
+
460
+ class LocalLoss(nn.Module):
461
+ def __init__(self):
462
+ super().__init__()
463
+
464
+ def identity_loss(self, gs):
465
+ s = gs.size(2)
466
+ iy, ix = torch.meshgrid(torch.linspace(-1, 1, s), torch.linspace(-1, 1, s))
467
+ t = torch.stack((ix, iy), dim=0).unsqueeze(0).to('cuda').expand_as(gs)
468
+ loss = F.l1_loss(gs, t.detach())
469
+ return loss
470
+
471
+ def direct_loss(self, gs, invtgs):
472
+ loss = F.l1_loss(gs, invtgs.detach())
473
+ return loss
474
+
475
+ def warp_diff_loss(self, xd, xpd, tgs, invtgs):
476
+ loss_f = F.l1_loss(xd, F.grid_sample(tgs, xpd.permute(0, 2, 3, 1), align_corners=True).detach())
477
+ loss_b = F.l1_loss(xpd, F.grid_sample(invtgs, xd.permute(0, 2, 3, 1), align_corners=True).detach())
478
+ loss = loss_f + loss_b
479
+ return loss
480
+
481
+
482
+ class SupervisedLoss(nn.Module):
483
+ def __init__(self):
484
+ super().__init__()
485
+ s = 64
486
+ self.tpswarper = TpsWarp(s)
487
+
488
+ def fm2bm(self, fm):
489
+ # B 3 N N
490
+ # fm in [0, 1]
491
+ B, _, s, _ = fm.size()
492
+ iy, ix = torch.meshgrid(torch.linspace(-1, 1, s), torch.linspace(-1, 1, s))
493
+ t = torch.stack((ix, iy), dim=0).unsqueeze(0).to('cuda').expand(B, -1, -1, -1)
494
+ srcpts = []
495
+ dstpts = []
496
+ for ii in range(B):
497
+ # mask
498
+ m = fm[ii, 2]
499
+ # z s
500
+ z = torch.nonzero(m, as_tuple=False)
501
+ num_sample = 512
502
+ n = z.size(0)
503
+ # print(n)
504
+ idx = torch.randperm(n)
505
+ idx = idx[:num_sample]
506
+ dstpts.append(t[ii, :, z[idx, 0], z[idx, 1]])
507
+ srcpts.append(fm[ii, : 2, z[idx, 0], z[idx, 1]] * 2 - 1)
508
+ srcpts = torch.stack(srcpts, dim=0).permute(0, 2, 1)
509
+ dstpts = torch.stack(dstpts, dim=0).permute(0, 2, 1)
510
+ # z = torch.nonzero(torch.abs(srcpts - 0) < 1e-5, as_tuple=False)
511
+ # print(z.size(0))
512
+ # print(dstpts.min())
513
+ # print(dstpts.max())
514
+ bm = self.tpswarper(srcpts, dstpts)
515
+ # bm[bm > 1] = 1
516
+ # bm[bm < -1] = -1
517
+ return bm
518
+
519
+ def gloss(self, x, y):
520
+ xbd = gs_to_bd(x)
521
+ # y = self.fm2bm(y)
522
+ y = F.interpolate(y, 64, mode='bilinear', align_corners=True)
523
+
524
+ ybd = gs_to_bd(y).detach()
525
+ loss = F.l1_loss(xbd, ybd.detach())
526
+ return loss
527
+
528
+ def lloss(self, x, y, dg):
529
+ # sample tgs to gen invtgs
530
+ B, _, s, _ = dg.size()
531
+ iy, ix = torch.meshgrid(torch.linspace(-1, 1, s), torch.linspace(-1, 1, s))
532
+ t = torch.stack((ix, iy), dim=0).unsqueeze(0).to('cuda').expand(B, -1, -1, -1)
533
+ num_sample = 512
534
+ # n = (H-2)*(W-2)
535
+ n = s * s
536
+ idx = torch.randperm(n)
537
+ idx = idx[:num_sample]
538
+ # srcpts = gs_to_bd(tgs)
539
+ # srcpts = torch.cat([srcpts, tgs[..., 1 : -1, 1 : -1].reshape(-1, 2, n)[..., idx].permute(0, 2, 1)], dim=1)
540
+ srcpts = dg.reshape(-1, 2, n)[..., idx].permute(0, 2, 1)
541
+ # dstpts = gs_to_bd(t)
542
+ # dstpts = torch.cat([dstpts, t[..., 1 : -1, 1 : -1].reshape(-1, 2, n)[..., idx].permute(0, 2, 1)], dim=1)
543
+ dstpts = t.reshape(-1, 2, n)[..., idx].permute(0, 2, 1)
544
+ invdg = self.tpswarper(srcpts, dstpts)
545
+ # compute dl = \phi(dg^-1, y)
546
+ dl = F.grid_sample(invdg, y.permute(0, 2, 3, 1), align_corners=True)
547
+ dl = F.interpolate(dl, 64, mode='bilinear', align_corners=True)
548
+ loss = F.l1_loss(x, dl.detach())
549
+
550
+ # y = F.interpolate(y, 64, mode='bilinear', align_corners=True)
551
+ # loss = F.l1_loss(F.grid_sample(dg.detach(), x.permute(0, 2, 3, 1), align_corners=True), y)
552
+
553
+ return loss, dl.detach()
networks/paperedge_cpu.py ADDED
@@ -0,0 +1,591 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ # from torch.nn.utils import spectral_norm as SN
5
+ # from torchvision.models.densenet import _DenseBlock
6
+ from .tps_warp import TpsWarp, PspWarp
7
+ from functools import partial
8
+ # import plotly.graph_objects as go
9
+ import random
10
+ import numpy as np
11
+ import cv2
12
+
13
+ torch.autograd.set_detect_anomaly(True)
14
+
15
+
16
+ def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
17
+ """3x3 convolution with padding"""
18
+ return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
19
+ padding=dilation, groups=groups, bias=False, dilation=dilation)
20
+
21
+
22
+ def conv1x1(in_planes, out_planes, stride=1):
23
+ """1x1 convolution"""
24
+ return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
25
+
26
+
27
+ class BasicBlock(nn.Module):
28
+ expansion = 1
29
+
30
+ def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
31
+ base_width=64, dilation=1, norm_layer=None):
32
+ super(BasicBlock, self).__init__()
33
+ if norm_layer is None:
34
+ norm_layer = nn.BatchNorm2d
35
+ if groups != 1 or base_width != 64:
36
+ raise ValueError(
37
+ 'BasicBlock only supports groups=1 and base_width=64')
38
+ if dilation > 1:
39
+ raise NotImplementedError(
40
+ "Dilation > 1 not supported in BasicBlock")
41
+ # Both self.conv1 and self.downsample layers downsample the input when stride != 1
42
+ self.conv1 = conv3x3(inplanes, planes, stride)
43
+ self.bn1 = norm_layer(planes)
44
+ self.actv = nn.ReLU()
45
+ self.conv2 = conv3x3(planes, planes)
46
+ self.bn2 = norm_layer(planes)
47
+ self.downsample = downsample
48
+ self.stride = stride
49
+
50
+ def forward(self, x):
51
+ identity = x
52
+
53
+ out = self.conv1(x)
54
+ out = self.bn1(out)
55
+ out = self.actv(out)
56
+
57
+ out = self.conv2(out)
58
+ out = self.bn2(out)
59
+
60
+ if self.downsample is not None:
61
+ identity = self.downsample(x)
62
+
63
+ out += identity
64
+ out = self.actv(out)
65
+
66
+ return out
67
+
68
+
69
+ def _make_layer(block, inplanes, planes, blocks, stride=1, dilate=False):
70
+ norm_layer = nn.BatchNorm2d
71
+ downsample = None
72
+
73
+ if stride != 1 or inplanes != planes * block.expansion:
74
+ downsample = nn.Sequential(
75
+ nn.Conv2d(inplanes, planes * block.expansion,
76
+ 1, stride, bias=False),
77
+ norm_layer(planes * block.expansion),
78
+ )
79
+
80
+ layers = []
81
+ layers.append(block(inplanes, planes, stride,
82
+ downsample, norm_layer=norm_layer))
83
+ for _ in range(1, blocks):
84
+ layers.append(block(planes, planes,
85
+ norm_layer=norm_layer))
86
+
87
+ return nn.Sequential(*layers)
88
+
89
+
90
+ class Interpolate(nn.Module):
91
+ def __init__(self, size, mode):
92
+ super(Interpolate, self).__init__()
93
+ self.interp = nn.functional.interpolate
94
+ self.size = size
95
+ self.mode = mode
96
+
97
+ def forward(self, x):
98
+ x = self.interp(x, size=self.size, mode=self.mode, align_corners=True)
99
+ return x
100
+
101
+
102
+ class GlobalWarper(nn.Module):
103
+ def __init__(self):
104
+ super(GlobalWarper, self).__init__()
105
+ modules = [
106
+ nn.Conv2d(5, 64, kernel_size=7, stride=2, padding=3, bias=False),
107
+ nn.BatchNorm2d(64),
108
+ nn.ReLU()
109
+ ]
110
+
111
+ # encoder
112
+ planes = [64, 128, 256, 256, 512, 512]
113
+ strides = [2, 2, 2, 2, 2]
114
+ blocks = [1, 1, 1, 1, 1]
115
+ for k in range(len(planes) - 1):
116
+ modules.append(_make_layer(
117
+ BasicBlock, planes[k], planes[k + 1], blocks[k], strides[k]))
118
+ self.encoder = nn.Sequential(*modules)
119
+
120
+ # decoder
121
+ modules = []
122
+ planes = [512, 512, 256, 128, 64]
123
+ strides = [2, 2, 2, 2]
124
+ # tsizes = [3, 5, 9, 17, 33]
125
+ blocks = [1, 1, 1, 1]
126
+ for k in range(len(planes) - 1):
127
+ modules += [nn.Sequential(nn.Upsample(scale_factor=strides[k],
128
+ mode='bilinear',
129
+ align_corners=True),
130
+ _make_layer(BasicBlock, planes[k], planes[k + 1], blocks[k], 1))]
131
+ self.decoder = nn.Sequential(*modules)
132
+
133
+ self.to_warp = nn.Sequential(nn.Conv2d(64, 2, 1))
134
+ self.to_warp[0].weight.data.fill_(0.0)
135
+ self.to_warp[0].bias.data.fill_(0.0)
136
+
137
+ iy, ix = torch.meshgrid(torch.linspace(-1, 1, 256), torch.linspace(-1, 1, 256))
138
+ self.coord = torch.stack((ix, iy), dim=0).unsqueeze(0)
139
+ iy, ix = torch.meshgrid(torch.linspace(-1, 1, 64),
140
+ torch.linspace(-1, 1, 64))
141
+
142
+ # note we mulitply a 0.9 so the network is initialized closer to GT.
143
+ # This is different from localwarper net
144
+ self.basegrid = torch.stack((ix * 0.9, iy * 0.9), dim=0).unsqueeze(0)
145
+
146
+ # # box filter
147
+ # ksize = 7
148
+ # p = int((ksize - 1) / 2)
149
+ # self.pad_replct = partial(F.pad, pad=(p, p, p, p), mode='replicate')
150
+ # bw = torch.ones(1, 1, ksize, ksize, device='cuda') / ksize / ksize
151
+ # self.box_filter = partial(F.conv2d, weight=bw)
152
+
153
+ def forward(self, im):
154
+ # print(self.to_warp[0].weight.data)
155
+ # coordconv
156
+ B = im.size(0)
157
+ c = self.coord.expand(B, -1, -1, -1).detach()
158
+ t = torch.cat((im, c), dim=1)
159
+
160
+ t = self.encoder(t)
161
+ t = self.decoder(t)
162
+ t = self.to_warp(t)
163
+
164
+ gs = t + self.basegrid
165
+
166
+ return gs
167
+
168
+
169
+ class LocalWarper(nn.Module):
170
+ def __init__(self):
171
+ super().__init__()
172
+ modules = [
173
+ nn.Conv2d(5, 64, kernel_size=7, stride=2, padding=3, bias=False),
174
+ nn.BatchNorm2d(64),
175
+ nn.ReLU()
176
+ ]
177
+ # encoder
178
+ planes = [64, 128, 256, 256, 512, 512]
179
+ strides = [2, 2, 2, 2, 2]
180
+ blocks = [1, 1, 1, 1, 1]
181
+ for k in range(len(planes) - 1):
182
+ modules.append(_make_layer(
183
+ BasicBlock, planes[k], planes[k + 1], blocks[k], strides[k]))
184
+ self.encoder = nn.Sequential(*modules)
185
+
186
+ # decoder
187
+ modules = []
188
+ planes = [512, 512, 256, 128, 64]
189
+ strides = [2, 2, 2, 2]
190
+ # tsizes = [3, 5, 9, 17, 33]
191
+ blocks = [1, 1, 1, 1]
192
+ for k in range(len(planes) - 1):
193
+ modules += [nn.Sequential(nn.Upsample(scale_factor=strides[k], mode='bilinear', align_corners=True),
194
+ _make_layer(BasicBlock, planes[k], planes[k + 1], blocks[k], 1))]
195
+ self.decoder = nn.Sequential(*modules)
196
+
197
+ self.to_warp = nn.Sequential(nn.Conv2d(64, 2, 1))
198
+ self.to_warp[0].weight.data.fill_(0.0)
199
+ self.to_warp[0].bias.data.fill_(0.0)
200
+
201
+ iy, ix = torch.meshgrid(
202
+ torch.linspace(-1, 1, 256), torch.linspace(-1, 1, 256))
203
+ self.coord = torch.stack((ix, iy), dim=0).unsqueeze(0)
204
+ iy, ix = torch.meshgrid(torch.linspace(-1, 1, 64),
205
+ torch.linspace(-1, 1, 64))
206
+ self.basegrid = torch.stack((ix, iy), dim=0).unsqueeze(0)
207
+
208
+ # box filter
209
+ ksize = 5
210
+ p = int((ksize - 1) / 2)
211
+ self.pad_replct = partial(F.pad, pad=(p, p, p, p), mode='replicate')
212
+ bw = torch.ones(1, 1, ksize, ksize) / ksize / ksize
213
+ self.box_filter = partial(F.conv2d, weight=bw)
214
+
215
+ def forward(self, im):
216
+ c = self.coord.expand(im.size(0), -1, -1, -1).detach()
217
+ t = torch.cat((im, c), dim=1)
218
+
219
+ # encoder
220
+ t = self.encoder(t)
221
+ t = self.decoder(t)
222
+ t = self.to_warp(t)
223
+
224
+ # # filter
225
+ # t = self.pad_replct(t)
226
+ # tx = self.box_filter(t[:, 0 : 1, ...])
227
+ # ty = self.box_filter(t[:, 1 : 2, ...])
228
+ # t = torch.cat((tx, ty), dim=1)
229
+
230
+ # bd condition
231
+ t[..., 1, 0, :] = 0
232
+ t[..., 1, -1, :] = 0
233
+ t[..., 0, :, 0] = 0
234
+ t[..., 0, :, -1] = 0
235
+
236
+ gs = t + self.basegrid
237
+ return gs
238
+
239
+
240
+ def gs_to_bd(gs):
241
+ # gs: B 2 H W
242
+ t = torch.cat([gs[..., 0, :], gs[..., -1, :], gs[..., 1: -1,
243
+ 0], gs[..., 1: -1, -1]], dim=2).permute(0, 2, 1)
244
+ # t: B 2(W + H - 1) 2
245
+ return t
246
+
247
+
248
+ class MaskLoss(nn.Module):
249
+ def __init__(self, gsize):
250
+ super().__init__()
251
+ self.tpswarper = TpsWarp(gsize)
252
+ self.pspwarper = PspWarp()
253
+ # self.imsize = imsize
254
+ self.msk = torch.ones(1, 1, gsize, gsize)
255
+ self.cn = torch.tensor([[-1, -1], [1, -1], [1, 1], [-1, 1]],
256
+ dtype=torch.float).unsqueeze(0)
257
+
258
+ def forward(self, gs, y, s):
259
+ # resize gs to s*s
260
+ B, _, s0, _ = gs.size()
261
+ tgs = F.interpolate(gs, s, mode='bilinear', align_corners=True)
262
+
263
+ # use only the boundary points
264
+ srcpts = gs_to_bd(tgs)
265
+ iy, ix = torch.meshgrid(torch.linspace(-1, 1, s),
266
+ torch.linspace(-1, 1, s))
267
+ t = torch.stack((ix, iy), dim=0).unsqueeze(0).expand_as(tgs)
268
+ dstpts = gs_to_bd(t)
269
+
270
+ tgs_f = self.tpswarper(srcpts, dstpts.detach())
271
+ ym = self.msk.expand_as(y)
272
+ yh = F.grid_sample(ym, tgs_f.permute(0, 2, 3, 1), align_corners=True)
273
+ loss_f = F.l1_loss(yh, y)
274
+
275
+ # forward/backward consistency loss
276
+ tgs_b = self.tpswarper(dstpts.detach(), srcpts)
277
+ # tgs_b = F.interpolate(tgs, s0, mode='bilinear', align_corners=True)
278
+ yy = F.grid_sample(y, tgs_b.permute(0, 2, 3, 1), align_corners=True)
279
+ loss_b = F.l1_loss(yy, ym)
280
+
281
+ return loss_f + loss_b, tgs_f
282
+
283
+ def _dist(self, x):
284
+ # adjacent point distance
285
+ # B, 2, n
286
+ x = torch.cat([x[..., 0: 1].detach(), x[..., 1: -1],
287
+ x[..., -1:].detach()], dim=2)
288
+ d = x[..., 1:] - x[..., :-1]
289
+ return torch.norm(d, dim=1)
290
+
291
+ # class TVLoss(nn.Module):
292
+ # def __init__(self):
293
+ # super(TVLoss, self).__init__()
294
+
295
+ # def forward(self, gs):
296
+ # loss = self._dist(gs[..., 1:], gs[..., :-1]) + self._dist(gs[..., 1:, :], gs[..., :-1, :])
297
+ # return loss
298
+
299
+ # def _dist(self, x1, x0):
300
+ # d = torch.norm(x1 - x0, dim=1, keepdim=True)
301
+ # d = torch.abs(d - torch.mean(d, dim=(2, 3), keepdim=True)).mean()
302
+ # return d
303
+
304
+
305
+ class WarperUtil(nn.Module):
306
+ def __init__(self, imsize):
307
+ super().__init__()
308
+ self.tpswarper = TpsWarp(imsize)
309
+ self.pspwarper = PspWarp()
310
+ self.s = imsize
311
+
312
+ def global_post_warp(self, gs, s):
313
+ # B, _, s0, _ = gs.size()
314
+ gs = F.interpolate(gs, s, mode='bilinear', align_corners=True)
315
+ # gs = F.interpolate(gs, s0, mode='bilinear', align_corners=True)
316
+ # extract info
317
+ m1 = gs[..., 0, :]
318
+ m2 = gs[..., -1, :]
319
+ n1 = gs[..., 0]
320
+ n2 = gs[..., -1]
321
+ # for x
322
+ m1x_interval_ratio = m1[:, 0, 1:] - m1[:, 0, :-1]
323
+ m1x_interval_ratio /= m1x_interval_ratio.sum(dim=1, keepdim=True)
324
+ m2x_interval_ratio = m2[:, 0, 1:] - m2[:, 0, :-1]
325
+ m2x_interval_ratio /= m2x_interval_ratio.sum(dim=1, keepdim=True)
326
+ # interpolate all x ratio
327
+ t = torch.stack(
328
+ [m1x_interval_ratio, m2x_interval_ratio], dim=1).unsqueeze(1)
329
+ mx_interval_ratio = F.interpolate(
330
+ t, (s, m1x_interval_ratio.size(1)), mode='bilinear', align_corners=True)
331
+ mx_interval = (n2[..., 0: 1, :] - n1[..., 0: 1, :]
332
+ ).unsqueeze(3) * mx_interval_ratio
333
+ # cumsum to x
334
+ dx = torch.cumsum(mx_interval, dim=3) + n1[..., 0: 1, :].unsqueeze(3)
335
+ dx = dx[..., 1: -1, :-1]
336
+ # for y
337
+ n1y_interval_ratio = n1[:, 1, 1:] - n1[:, 1, :-1]
338
+ n1y_interval_ratio /= n1y_interval_ratio.sum(dim=1, keepdim=True)
339
+ n2y_interval_ratio = n2[:, 1, 1:] - n2[:, 1, :-1]
340
+ n2y_interval_ratio /= n2y_interval_ratio.sum(dim=1, keepdim=True)
341
+ # interpolate all x ratio
342
+ t = torch.stack(
343
+ [n1y_interval_ratio, n2y_interval_ratio], dim=2).unsqueeze(1)
344
+ ny_interval_ratio = F.interpolate(
345
+ t, (n1y_interval_ratio.size(1), s), mode='bilinear', align_corners=True)
346
+ ny_interval = (m2[..., 1: 2, :] - m1[..., 1: 2, :]
347
+ ).unsqueeze(2) * ny_interval_ratio
348
+ # cumsum to y
349
+ dy = torch.cumsum(ny_interval, dim=2) + m1[..., 1: 2, :].unsqueeze(2)
350
+ dy = dy[..., :-1, 1: -1]
351
+ ds = torch.cat((dx, dy), dim=1)
352
+ gs[..., 1: -1, 1: -1] = ds
353
+ return gs
354
+
355
+ def perturb_warp(self, dd):
356
+ B = dd.size(0)
357
+ s = self.s
358
+ # -0.2 to 0.2
359
+ iy, ix = torch.meshgrid(torch.linspace(-1, 1, s),
360
+ torch.linspace(-1, 1, s))
361
+ t = torch.stack((ix, iy), dim=0).unsqueeze(
362
+ 0).expand(B, -1, -1, -1)
363
+
364
+ tt = t.clone()
365
+
366
+ nd = random.randint(0, 4)
367
+ for ii in range(nd):
368
+ # define deformation on bd
369
+ pm = (torch.rand(B, 1) - 0.5) * 0.2
370
+ ps = (torch.rand(B, 1) - 0.5) * 1.95
371
+ pt = ps + pm
372
+ pt = pt.clamp(-0.975, 0.975)
373
+ # put it on one bd
374
+ # [1, 1] or [-1, 1] or [-1, -1] etc
375
+ a1 = (torch.rand(B, 2) > 0.5).float() * 2 - 1
376
+ # select one col for every row
377
+ a2 = torch.rand(B, 1) > 0.5
378
+ a2 = torch.cat([a2, a2.bitwise_not()], dim=1)
379
+ a3 = a1.clone()
380
+ a3[a2] = ps.view(-1)
381
+ ps = a3.clone()
382
+ a3[a2] = pt.view(-1)
383
+ pt = a3.clone()
384
+ # 2 N 4
385
+ bds = torch.stack([
386
+ t[0, :, 1: -1, 0], t[0, :, 1: -1, -1], t[0,
387
+ :, 0, 1: -1], t[0, :, -1, 1: -1]
388
+ ], dim=2)
389
+
390
+ pbd = a2.bitwise_not().float() * a1
391
+ # id of boundary p is on
392
+ pbd = torch.abs(0.5 * pbd[:, 0] + 2.5 * pbd[:, 1] + 0.5).long()
393
+ # ids of other boundaries
394
+ pbd = torch.stack([pbd + 1, pbd + 2, pbd + 3], dim=1) % 4
395
+ # print(pbd)
396
+ pbd = bds[..., pbd].permute(2, 0, 1, 3).reshape(B, 2, -1)
397
+
398
+ srcpts = torch.stack([
399
+ t[..., 0, 0], t[..., 0, -1], t[..., -1, 0], t[..., -1, -1],
400
+ ps
401
+ ], dim=2)
402
+ srcpts = torch.cat([pbd, srcpts], dim=2).permute(0, 2, 1)
403
+ dstpts = torch.stack([
404
+ t[..., 0, 0], t[..., 0, -1], t[..., -1, 0], t[..., -1, -1],
405
+ pt
406
+ ], dim=2)
407
+ dstpts = torch.cat([pbd, dstpts], dim=2).permute(0, 2, 1)
408
+ # print(srcpts)
409
+ # print(dstpts)
410
+ tgs = self.tpswarper(srcpts, dstpts)
411
+ tt = F.grid_sample(tt, tgs.permute(0, 2, 3, 1), align_corners=True)
412
+
413
+ nd = random.randint(1, 5)
414
+ for ii in range(nd):
415
+
416
+ pm = (torch.rand(B, 2) - 0.5) * 0.2
417
+ ps = (torch.rand(B, 2) - 0.5) * 1.95
418
+ pt = ps + pm
419
+ pt = pt.clamp(-0.975, 0.975)
420
+
421
+ srcpts = torch.cat([
422
+ t[..., -1, :], t[..., 0, :], t[..., 1: -1, 0], t[..., 1: -1, -1],
423
+ ps.unsqueeze(2)
424
+ ], dim=2).permute(0, 2, 1)
425
+ dstpts = torch.cat([
426
+ t[..., -1, :], t[..., 0, :], t[..., 1: -1, 0], t[..., 1: -1, -1],
427
+ pt.unsqueeze(2)
428
+ ], dim=2).permute(0, 2, 1)
429
+ tgs = self.tpswarper(srcpts, dstpts)
430
+ tt = F.grid_sample(tt, tgs.permute(0, 2, 3, 1), align_corners=True)
431
+ tgs = tt
432
+
433
+ # sample tgs to gen invtgs
434
+ num_sample = 512
435
+ # n = (H-2)*(W-2)
436
+ n = s * s
437
+ idx = torch.randperm(n)
438
+ idx = idx[:num_sample]
439
+ srcpts = tgs.reshape(-1, 2, n)[..., idx].permute(0, 2, 1)
440
+ dstpts = t.reshape(-1, 2, n)[..., idx].permute(0, 2, 1)
441
+ invtgs = self.tpswarper(srcpts, dstpts)
442
+ return tgs, invtgs
443
+
444
+ def equal_spacing_interpolate(self, gs, s):
445
+ def equal_bd(x, s):
446
+ # x is B 2 n
447
+ v0 = x[..., :-1] # B 2 n-1
448
+ v = x[..., 1:] - x[..., :-1]
449
+ vn = v.norm(dim=1, keepdim=True)
450
+ v = v / vn
451
+ c = vn.sum(dim=2, keepdim=True) # B 1 1
452
+ a = vn / c
453
+ b = torch.cumsum(a, dim=2)
454
+ b = torch.cat((torch.zeros(B, 1, 1), b[..., :-1]), dim=2)
455
+
456
+ t = torch.linspace(1e-5, 1 - 1e-5, s).view(1, s, 1)
457
+ t = t - b # B s n-1
458
+ # print(t)
459
+
460
+ tt = torch.cat((t, -torch.ones(B, s, 1)), dim=2) # B s n
461
+ tt = tt[..., 1:] * tt[..., :-1] # B s n-1
462
+ tt = (tt < 0).float()
463
+ d = torch.matmul(v0, tt.permute(0, 2, 1)) + \
464
+ torch.matmul(v, (tt * t).permute(0, 2, 1)) # B 2 s
465
+ return d
466
+
467
+ gs = F.interpolate(gs, s, mode='bilinear', align_corners=True)
468
+ B = gs.size(0)
469
+ dst_cn = torch.tensor([[-1, -1], [1, -1], [1, 1], [-1, 1]],
470
+ dtype=torch.float).expand(B, -1, -1)
471
+ src_cn = torch.stack([gs[..., 0, 0], gs[..., 0, -1],
472
+ gs[..., -1, -1], gs[..., -1, 0]], dim=2).permute(0, 2, 1)
473
+ M = self.pspwarper.pspmat(src_cn, dst_cn).detach()
474
+ invM = self.pspwarper.pspmat(dst_cn, src_cn).detach()
475
+ pgs = self.pspwarper(gs.permute(0, 2, 3, 1).reshape(
476
+ B, -1, 2), M).reshape(B, s, s, 2).permute(0, 3, 1, 2)
477
+ t = [pgs[..., 0, :], pgs[..., -1, :], pgs[..., :, 0], pgs[..., :, -1]]
478
+ d = []
479
+ for x in t:
480
+ d.append(equal_bd(x, s))
481
+ pgs[..., 0, :] = d[0]
482
+ pgs[..., -1, :] = d[1]
483
+ pgs[..., :, 0] = d[2]
484
+ pgs[..., :, -1] = d[3]
485
+ gs = self.pspwarper(pgs.permute(0, 2, 3, 1).reshape(
486
+ B, -1, 2), invM).reshape(B, s, s, 2).permute(0, 3, 1, 2)
487
+ gs = self.global_post_warp(gs, s)
488
+ return gs
489
+
490
+
491
+ class LocalLoss(nn.Module):
492
+ def __init__(self):
493
+ super().__init__()
494
+
495
+ def identity_loss(self, gs):
496
+ s = gs.size(2)
497
+ iy, ix = torch.meshgrid(torch.linspace(-1, 1, s),
498
+ torch.linspace(-1, 1, s))
499
+ t = torch.stack((ix, iy), dim=0).unsqueeze(0).expand_as(gs)
500
+ loss = F.l1_loss(gs, t.detach())
501
+ return loss
502
+
503
+ def direct_loss(self, gs, invtgs):
504
+ loss = F.l1_loss(gs, invtgs.detach())
505
+ return loss
506
+
507
+ def warp_diff_loss(self, xd, xpd, tgs, invtgs):
508
+ loss_f = F.l1_loss(xd, F.grid_sample(
509
+ tgs, xpd.permute(0, 2, 3, 1), align_corners=True).detach())
510
+ loss_b = F.l1_loss(xpd, F.grid_sample(
511
+ invtgs, xd.permute(0, 2, 3, 1), align_corners=True).detach())
512
+ loss = loss_f + loss_b
513
+ return loss
514
+
515
+
516
+ class SupervisedLoss(nn.Module):
517
+ def __init__(self):
518
+ super().__init__()
519
+ s = 64
520
+ self.tpswarper = TpsWarp(s)
521
+
522
+ def fm2bm(self, fm):
523
+ # B 3 N N
524
+ # fm in [0, 1]
525
+ B, _, s, _ = fm.size()
526
+ iy, ix = torch.meshgrid(torch.linspace(-1, 1, s),
527
+ torch.linspace(-1, 1, s))
528
+ t = torch.stack((ix, iy), dim=0).unsqueeze(
529
+ 0).expand(B, -1, -1, -1)
530
+ srcpts = []
531
+ dstpts = []
532
+ for ii in range(B):
533
+ # mask
534
+ m = fm[ii, 2]
535
+ # z s
536
+ z = torch.nonzero(m, as_tuple=False)
537
+ num_sample = 512
538
+ n = z.size(0)
539
+ # print(n)
540
+ idx = torch.randperm(n)
541
+ idx = idx[:num_sample]
542
+ dstpts.append(t[ii, :, z[idx, 0], z[idx, 1]])
543
+ srcpts.append(fm[ii, : 2, z[idx, 0], z[idx, 1]] * 2 - 1)
544
+ srcpts = torch.stack(srcpts, dim=0).permute(0, 2, 1)
545
+ dstpts = torch.stack(dstpts, dim=0).permute(0, 2, 1)
546
+ # z = torch.nonzero(torch.abs(srcpts - 0) < 1e-5, as_tuple=False)
547
+ # print(z.size(0))
548
+ # print(dstpts.min())
549
+ # print(dstpts.max())
550
+ bm = self.tpswarper(srcpts, dstpts)
551
+ # bm[bm > 1] = 1
552
+ # bm[bm < -1] = -1
553
+ return bm
554
+
555
+ def gloss(self, x, y):
556
+ xbd = gs_to_bd(x)
557
+ # y = self.fm2bm(y)
558
+ y = F.interpolate(y, 64, mode='bilinear', align_corners=True)
559
+
560
+ ybd = gs_to_bd(y).detach()
561
+ loss = F.l1_loss(xbd, ybd.detach())
562
+ return loss
563
+
564
+ def lloss(self, x, y, dg):
565
+ # sample tgs to gen invtgs
566
+ B, _, s, _ = dg.size()
567
+ iy, ix = torch.meshgrid(torch.linspace(-1, 1, s),
568
+ torch.linspace(-1, 1, s))
569
+ t = torch.stack((ix, iy), dim=0).unsqueeze(
570
+ 0).expand(B, -1, -1, -1)
571
+ num_sample = 512
572
+ # n = (H-2)*(W-2)
573
+ n = s * s
574
+ idx = torch.randperm(n)
575
+ idx = idx[:num_sample]
576
+ # srcpts = gs_to_bd(tgs)
577
+ # srcpts = torch.cat([srcpts, tgs[..., 1 : -1, 1 : -1].reshape(-1, 2, n)[..., idx].permute(0, 2, 1)], dim=1)
578
+ srcpts = dg.reshape(-1, 2, n)[..., idx].permute(0, 2, 1)
579
+ # dstpts = gs_to_bd(t)
580
+ # dstpts = torch.cat([dstpts, t[..., 1 : -1, 1 : -1].reshape(-1, 2, n)[..., idx].permute(0, 2, 1)], dim=1)
581
+ dstpts = t.reshape(-1, 2, n)[..., idx].permute(0, 2, 1)
582
+ invdg = self.tpswarper(srcpts, dstpts)
583
+ # compute dl = \phi(dg^-1, y)
584
+ dl = F.grid_sample(invdg, y.permute(0, 2, 3, 1), align_corners=True)
585
+ dl = F.interpolate(dl, 64, mode='bilinear', align_corners=True)
586
+ loss = F.l1_loss(x, dl.detach())
587
+
588
+ # y = F.interpolate(y, 64, mode='bilinear', align_corners=True)
589
+ # loss = F.l1_loss(F.grid_sample(dg.detach(), x.permute(0, 2, 3, 1), align_corners=True), y)
590
+
591
+ return loss, dl.detach()
networks/tps_warp.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+
6
+ class TpsWarp(nn.Module):
7
+ def __init__(self, s):
8
+ super(TpsWarp, self).__init__()
9
+ iy, ix = torch.meshgrid(torch.linspace(-1, 1, s),
10
+ torch.linspace(-1, 1, s))
11
+ self.gs = torch.stack((ix, iy), dim=2).reshape((1, -1, 2))
12
+ self.sz = s
13
+
14
+ def forward(self, src, dst):
15
+ # src and dst are B.n.2
16
+ B, n, _ = src.size()
17
+ # B.n.1.2
18
+ delta = src.unsqueeze(2)
19
+ delta = delta - delta.permute(0, 2, 1, 3)
20
+ # B.n.n
21
+ K = delta.norm(dim=3)
22
+ # Rsq = torch.sum(delta**2, dim=3)
23
+ # Rsq += torch.eye(n)
24
+ # Rsq[Rsq == 0] = 1.
25
+ # K = 0.5 * Rsq * torch.log(Rsq)
26
+ # c = -150
27
+ # K = torch.exp(c * Rsq)
28
+ # K = torch.abs(Rsq - 0.5) - 0.5
29
+ # WARNING: TORCH.SQRT HAS NAN GRAD AT 0
30
+ # K = torch.sqrt(Rsq)
31
+ # print(K)
32
+ # K[torch.isnan(K)] = 0.
33
+ P = torch.cat((torch.ones((B, n, 1)), src), 2)
34
+ L = torch.cat((K, P), 2)
35
+ t = torch.cat(
36
+ (P.permute(0, 2, 1), torch.zeros((B, 3, 3))), 2)
37
+ L = torch.cat((L, t), 1)
38
+ # LInv = L.inverse()
39
+ # # wv is B.n+3.2
40
+ # wv = torch.matmul(LInv, torch.cat((dst, torch.zeros((B, 3, 2))), 1))
41
+ # the above implementation has stability problem near the boundaries
42
+ wv = torch.solve(
43
+ torch.cat((dst, torch.zeros((B, 3, 2))), 1), L)[0]
44
+
45
+ # get the grid sampler
46
+ s = self.gs.size(1)
47
+ gs = self.gs
48
+ delta = gs.unsqueeze(2)
49
+ delta = delta - src.unsqueeze(1)
50
+ K = delta.norm(dim=3)
51
+ # Rsq = torch.sum(delta**2, dim=3)
52
+ # K = torch.exp(c * Rsq)
53
+ # Rsq[Rsq == 0] = 1.
54
+ # K = 0.5 * Rsq * torch.log(Rsq)
55
+ # K = torch.abs(Rsq - 0.5) - 0.5
56
+ # K = torch.sqrt(Rsq)
57
+ # K[torch.isnan(K)] = 0.
58
+ gs = gs.expand(B, -1, -1)
59
+ P = torch.cat((torch.ones((B, s, 1)), gs), 2)
60
+ L = torch.cat((K, P), 2)
61
+ gs = torch.matmul(L, wv)
62
+ return gs.reshape(B, self.sz, self.sz, 2).permute(0, 3, 1, 2)
63
+
64
+
65
+ class PspWarp(nn.Module):
66
+ def __init__(self):
67
+ super().__init__()
68
+
69
+ def pspmat(self, src, dst):
70
+ # B, 4, 2
71
+ B, _, _ = src.size()
72
+ s = torch.cat([
73
+ torch.cat([src,
74
+ torch.ones((B, 4, 1)),
75
+ torch.zeros((B, 4, 3)),
76
+ -dst[..., 0: 1] * src[..., 0: 1], -dst[..., 0: 1] * src[..., 1: 2]], dim=2),
77
+ torch.cat([torch.zeros((B, 4, 3)), src, torch.ones((B, 4, 1)),
78
+ -dst[..., 1: 2] * src[..., 0: 1], -dst[..., 1: 2] * src[..., 1: 2]], dim=2)
79
+ ], dim=1)
80
+ t = torch.cat([dst[..., 0: 1], dst[..., 1: 2]], dim=1)
81
+ # M = s.inverse() @ t
82
+ M = torch.solve(t, s)[0]
83
+ # M is B 8 1
84
+ return M
85
+
86
+ def forward(self, xy, M):
87
+ # permute M to B 1 8
88
+ M = M.permute(0, 2, 1)
89
+ t = M[..., 6] * xy[..., 0] + M[..., 7] * xy[..., 1] + 1
90
+ u = (M[..., 0] * xy[..., 0] + M[..., 1] * xy[..., 1] + M[..., 2]) / t
91
+ v = (M[..., 3] * xy[..., 0] + M[..., 4] * xy[..., 1] + M[..., 5]) / t
92
+ return torch.stack((u, v), dim=2)
93
+ # for ii in range(4):
94
+ # xy = src[:, ii : ii + 1, :]
95
+ # uv = dst[:, ii : ii + 1, :]
96
+ # t0 = [xy, torch.ones((B, 1, 1)), torch.zeros((B, 1, 3)), -uv[..., 0] * xy[..., 0], -uv[..., 0] * xy[..., 1]]
97
+ # t0 = torch.cat(t0, dim=2)
98
+ # t1 = [torch.zeros((B, 1, 3)), xy, torch.ones((B, 1, 1)), -uv[..., 1] * xy[..., 0], -uv[..., 1] * xy[..., 1]]
99
+ # t1 = torch.cat(t1, dim=2)
100
+
101
+
102
+ class IdwWarp(nn.Module):
103
+ # inverse distance weighting
104
+ def __init__(self, s):
105
+ super().__init__()
106
+ iy, ix = torch.meshgrid(torch.linspace(-1, 1, s),
107
+ torch.linspace(-1, 1, s))
108
+ self.gs = torch.stack((ix, iy), dim=2).reshape((1, -1, 2)).to('cuda')
109
+ self.s = s
110
+
111
+ def forward(self, src, dst):
112
+ # B n 2
113
+ B, n, _ = src.size()
114
+ # B.n.1.2
115
+ delta = src.unsqueeze(2)
116
+ delta = delta - self.gs.unsqueeze(0)
117
+ # B.n.K
118
+ p = 1
119
+ Rsq = torch.sum(delta**2, dim=3)**p
120
+ w = 1 / Rsq
121
+ # turn inf to [0...1...0]
122
+ t = torch.isinf(w)
123
+ idx = t.any(dim=1).nonzero()
124
+ w[idx[:, 0], :, idx[:, 1]] = t[idx[:, 0], :, idx[:, 1]].float()
125
+ wwx = w * dst[..., 0: 1]
126
+ wwx = wwx.sum(dim=1) / w.sum(dim=1)
127
+ wwy = w * dst[..., 1: 2]
128
+ wwy = wwy.sum(dim=1) / w.sum(dim=1)
129
+ # print(wwy.size())
130
+ gs = torch.stack((wwx, wwy), dim=2).reshape(
131
+ B, self.s, self.s, 2).permute(0, 3, 1, 2)
132
+ return gs
133
+
134
+
135
+ if __name__ == "__main__":
136
+ import cv2
137
+ import numpy as np
138
+ from hdf5storage import loadmat
139
+ from visdom import Visdom
140
+ vis = Visdom(port=10086)
141
+
142
+ # bm_path = '/nfs/bigdisk/sagnik/swat3d/bm/7/2_471_7-ec_Page_375-5LI0001.mat'
143
+ # img_path = '/nfs/bigdisk/sagnik/swat3d/img/7/2_471_7-ec_Page_375-5LI0001.png'
144
+
145
+ # bm = loadmat(bm_path)['bm']
146
+ # bm = (bm - 224) / 224.
147
+ # bm = cv2.resize(bm, (64, 64), cv2.INTER_LINEAR).astype(np.float32)
148
+
149
+ # im = cv2.imread(img_path) / 255.
150
+ # im = im[..., ::-1].copy()
151
+ # im = cv2.resize(im, (256, 256), cv2.INTER_AREA).astype(np.float32)
152
+ # im = torch.from_numpy(im.transpose(2, 0, 1)).unsqueeze(0).to('cuda')
153
+
154
+ # x = np.random.choice(np.arange(64), 50, False)
155
+ # y = np.random.choice(np.arange(64), 50, False)
156
+
157
+ # src = torch.tensor([[x, y]], dtype=torch.float32).permute(0, 2, 1)
158
+ # src = (src - 32) / 32.
159
+ # dst = torch.from_numpy(bm[y, x, :]).unsqueeze(0).to('cuda')
160
+
161
+ # # print(src.size())
162
+ # # print(dst.size())
163
+
164
+ # tpswarp = TpsWarp(64)
165
+ # import time
166
+ # t = time.time()
167
+ # for _ in range(100):
168
+ # gs = tpswarp(src, dst)
169
+ # print(f'time:{time.time() - t}')
170
+ # gs = gs.view(-1, 64, 64, 2)
171
+
172
+ # print(gs.size())
173
+ # bm2x2 = F.interpolate(gs.permute(0, 3, 1, 2), size=256, mode='bilinear', align_corners=True).permute(0, 2, 3, 1)
174
+
175
+ # rim = F.grid_sample(im, bm2x2, align_corners=True)
176
+ # vis.images(rim, win='sk3')
177
+ tpswarp = TpsWarp(16)
178
+ import matplotlib.pyplot as plt
179
+ cn = torch.tensor([[-1, -1], [1, -1], [1, 1], [-1, 1], [-0.5, -1],
180
+ [0, -1], [0.5, -1]], dtype=torch.float).unsqueeze(0)
181
+ pn = torch.tensor([[-1, -0.5], [1, -1], [1, 1], [-1, 0.5],
182
+ [-0.5, -1], [0, -0.5], [0.5, -1]]).unsqueeze(0)
183
+ pspwarp = PspWarp()
184
+ # # print(cn.dtype)
185
+ M = pspwarp.pspmat(cn[..., 0: 4, :], pn[..., 0: 4, :])
186
+ invM = pspwarp.pspmat(pn[..., 0: 4, :], cn[..., 0: 4, :])
187
+ # iy, ix = torch.meshgrid(torch.linspace(-1, 1, 8), torch.linspace(-1, 1, 8))
188
+ # gs = torch.stack((ix, iy), dim=2).reshape((1, -1, 2)).to('cuda')
189
+ # t = pspwarp(gs, M).reshape(8, 8, 2).detach().cpu().numpy()
190
+ # print(M)
191
+
192
+ t = tpswarp(cn, pn)
193
+ from tsdeform import WarperUtil
194
+ wu = WarperUtil(16)
195
+ tgs = wu.global_post_warp(t, 16, invM, M)
196
+
197
+ t = tgs.permute(0, 2, 3, 1)[0].detach().cpu().numpy()
198
+
199
+ plt.clf()
200
+ plt.pcolormesh(t[..., 0], t[..., 1],
201
+ np.zeros_like(t[..., 0]), edgecolors='r')
202
+ plt.gca().invert_yaxis()
203
+ plt.gca().axis('equal')
204
+ vis.matplot(plt, env='grid', win='mpl')
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ opencv_python
2
+ scipy
3
+ torch
4
+ numpy>=1.20.3
5
+ hdf5storage>=0.1.18
utils/__init__.py ADDED
File without changes
utils/handlers.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import visdom
2
+ import numpy as np
3
+ import csv
4
+ import torch
5
+ from datetime import datetime
6
+ import os
7
+ import cv2
8
+ import random
9
+ import matplotlib.pyplot as plt
10
+
11
+
12
+ class VisPlot(object):
13
+ def __init__(self, port=10086, env='main'):
14
+ self.vis = visdom.Visdom(port=port)
15
+ self.env = env
16
+ self.vis.close('loss', env=env)
17
+
18
+ def plot_loss(self, engine, monitor_metrics, win='loss'):
19
+ self.vis.line(X=np.array([engine.state.iteration]),
20
+ # NOTE because we use RunningAverage to log the loss, we can retrieve these numbers from state.metrics
21
+ Y=np.array([[engine.state.metrics[x]
22
+ for x in monitor_metrics]]),
23
+ env=self.env, win=win, update='append')
24
+
25
+ def plot_imgs(self, imgs, win='img', imhistory=False):
26
+ imgs = np.clip(imgs, 1e-5, 1 - 1e-5)
27
+ self.vis.images(imgs, env=self.env, win=win, opts={
28
+ 'caption': win, 'store_history': imhistory})
29
+
30
+ def plot_meshes(self, ms, win='ms'):
31
+ plt.close()
32
+ n = ms.shape[0]
33
+ nr = (n - 1) // 8 + 1
34
+ fig, axs = plt.subplots(1, 2)
35
+ axs = axs.ravel()
36
+ # fig.clf()
37
+
38
+ c = np.arange(256) / 255.0
39
+ c = c.reshape((16, 16))
40
+ for ii in range(2):
41
+ t = ms[ii]
42
+ axs[ii].pcolormesh(t[..., 0], t[..., 1], c,
43
+ cmap='YlGnBu', edgecolors='black')
44
+ axs[ii].set_xlim(-1, 1)
45
+ axs[ii].set_ylim(-1, 1)
46
+ axs[ii].invert_yaxis()
47
+ # axs[ii].axis('equal', 'box')
48
+ axs[ii].set_aspect('equal', 'box')
49
+ # fig, axs = plt.subplots(1, 2)
50
+ # axs = axs.ravel()
51
+ # t = ms[0]
52
+ # axs[0].pcolormesh(t[..., 0], t[..., 1], np.zeros_like(t[..., 0]), edgecolors='r')
53
+ # axs[0].invert_yaxis()
54
+ # axs[0].axis('equal', 'box')
55
+ fig.tight_layout()
56
+ self.vis.matplot(fig, env=self.env, win=win)
57
+
58
+
59
+ class CSVLogger(object):
60
+ def __init__(self, filename):
61
+ self.filename = filename
62
+
63
+ def __call__(self, engine, monitor_metrics):
64
+ with open(self.filename, 'a') as csvfile:
65
+ writer = csv.writer(csvfile, delimiter=',')
66
+ date_time = datetime.now().strftime('%m/%d/%Y-%H:%M:%S')
67
+ writer.writerow([date_time, engine.state.iteration] +
68
+ [engine.state.metrics[x] for x in monitor_metrics])
69
+
70
+ # class SaveRes(object):
71
+ # def __init__(self, resdir='./'):
72
+ # self.yp = []
73
+ # self.resdir = resdir
74
+
75
+ # def update(self, engine):
76
+ # self.yp.append(engine.state.output[0][1].cpu().numpy())
77
+
78
+ # def save(self, epoch_id):
79
+ # self.yp = np.concatenate(self.yp)
80
+ # savemat(os.path.join(self.resdir, 't{}.mat'.format(epoch_id)), \
81
+ # {'yp': self.yp})
82
+ # self.yp = []
83
+ # # self.yp = []
84
+ # # self.yg = []