├── README.md
└── softcode
├── __init__.py
├── example_img
├── test10.jpg
├── test4.jpg
└── test7.jpg
├── gridnet
├── __init__.py
├── modules.py
├── net_module.py
├── single_net.py
└── train.py
├── loss_f.py
├── main_net.py
├── other_modules.py
├── pair_img
├── im1.png
├── im2.png
└── im3.png
├── pwc
├── LICENSE
├── __init__.py
├── comparison
│ ├── comparison.gif
│ ├── comparison.py
│ ├── official - caffe.png
│ └── this - pytorch.png
├── correlation
│ ├── README.md
│ ├── __pycache__
│ │ └── correlation.cpython-36.pyc
│ └── correlation.py
├── dataset.py
├── images
│ ├── README.md
│ ├── first.png
│ └── second.png
├── log
│ ├── 1flowpic.png
│ ├── events.out.tfevents.1611136582.DESKTOP-A6T4CD8.18592.5.v2
│ └── pic.png
├── logger.py
├── out.flo
├── pwc_network.py
├── requirements.txt
├── train.py
└── utils
│ ├── __pycache__
│ ├── constv.cpython-36.pyc
│ ├── flow_utils.cpython-36.pyc
│ └── losses.cpython-36.pyc
│ ├── constv.py
│ ├── flow_utils.py
│ ├── losses.py
│ └── test.py
├── readme.md
├── run_a_pair.py
├── softsplatting
├── README.md
├── __init__.py
├── benchmark.py
├── requirements.txt
├── run.py
└── softsplat.py
├── tmptest.py
├── train_and_test.py
└── vimo_dataset.py
/README.md:
--------------------------------------------------------------------------------
1 | # pytorch-soft-splatting
2 | personal reimplementation of softsplatting
3 |
4 |
5 | # pytorch-soft-splatting
6 | First apologize for my poor English
7 |
8 | This is a personal reimplementation of softsplatting [1] using PyTorch. The code is complete comparing with official code. That's to say it is trainable and I will provide a pretrained model later.
9 |
10 | Please NOTE that I am a beginner in deep learning especially in frame interpolation. ***And the most important thing is that I only have a 1060 GPU (so poor right?)*** The model is trained on REDS including about 240 scenes(100 images per scene and very large motion). I am unable to train the whole dataset currently, so more test and criteria is not available now. And I am not so sure of some training details.
11 | But this model **does deal with very large motions**
12 | NOTE: you may get very blur result when using my pretrained weight. That's because The amount of training data set is too small I highly recommend you train this model on whole Vimeo.
13 | If you have trained a better model, please contact me.
14 |
15 | But there are still some good news. I think it is easy for you to train and run your own model. Also, the code is purely python your can feel free of issues of cuda version,gcc version and platform(windows and linux both run well). Despite of shortage of test, my reimplementation looks at least plausible.
16 | # examples
17 | left is interpolation result and right is ground truth.
some very good res.
18 |
19 |

20 | 
21 |
22 |
23 |
24 | ## environment
25 | I run in python36 cupy 10.1 in fact I think it can also run well in any version
26 | for python>=3.6.2
27 |
28 | ## usage
29 | ### to simply test my code you should
30 | 1 download my pretrained model from
31 | [baiduyun](https://pan.baidu.com/s/1rMzwHrhiZofZTkt1VrHqpQ)
32 | password:l4gz
33 | [google drive](https://drive.google.com/file/d/1sX8vZ90XANk_WOdmspWcZiz6T4pmrjo_/view?usp=sharing)
34 |
35 |
36 | ```
37 | python run_a_pair.py
38 | ```
39 | ### to train my code you should
40 | 1 download Vimeo
41 | 2 download pretrained model of pwc and move it to 'pwc\weights\network-default.pytorch'
42 | [baiduyun](https://pan.baidu.com/s/1Y-xtYy0tu4R2odvwmawpHw
43 | )
password: kuh5
44 |
if you want to train from scratch you can choose not to download this and comment the **torch.load** but you may get very bad result.
45 | 3 change the variable **vimo_data_dir** in train_and_test.py to 'path_to_your_dataset/vimeo_triplet'
46 |
47 | 4 I didn't write args parser for your convenience to revise my code. Change the settings as what you like in train_or_test.It 's very easy to revise. or just run as:
48 |
49 | ```
50 | python train_and_test.py
51 | ```
52 | IF YOU HAVE BETTER DEVICE AND YOU CAN TRAIN WHOLE DATASET PLEASE TELL ME THANK YOU VERY MUCH!!!
53 |
54 |
55 | ## structure of code
56 | The code mainly include 3 parts
57 | 1 gridnet[3]: it's a U-net like structure network which is used to compile the img1,img2 and their warped results. for more info please see the code or the papar.Note you can train this part without any other parts. it may serve as a baseline
58 | 2 pwc[2]: It's a network that utilizes to extract flow from images. for more info please see the code or the papar. This is also trainable because I wrote the train code.But for my device limitation, I cannot fine-tune the pretrained model pwc\weights\network-default.pytorch. If you can fine-tune this on flythings or flychairs I think you can get better result(this is advice from author)
59 | 3 softsplatting[1]: the 'soft operation'.
60 | 4 main_net: put all things metioned above together.
61 |
62 |
63 |
64 |
65 | ## references
66 | ```
67 | [1] @inproceedings{Niklaus_CVPR_2020,
68 | author = {Simon Niklaus and Feng Liu},
69 | title = {Softmax Splatting for Video Frame Interpolation},
70 | booktitle = {IEEE Conference on Computer Vision and Pattern Recognition},
71 | year = {2020}
72 | }
73 | ```
74 | [2] [pytorch-pwc](https://github.com/sniklaus/pytorch-pwc)
75 | [3] [grid-net](https://github.com/daigo0927/GridNet)
76 |
77 | Many codes are from Niklaus.
78 | Many Many Many thanks for him.
79 |
80 |
81 |
--------------------------------------------------------------------------------
/softcode/__init__.py:
--------------------------------------------------------------------------------
1 | # @Time : 2021/1/23 10:37
2 |
3 | # @Author : xx
4 |
5 | # @File : __init__.py.py
6 |
7 | # @Software: PyCharm
8 |
9 | # @description=''
--------------------------------------------------------------------------------
/softcode/example_img/test10.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gangsterless/pytorch-softmax-splatting/6a7ff3b876050ded9957c4e68528b04d49621ad0/softcode/example_img/test10.jpg
--------------------------------------------------------------------------------
/softcode/example_img/test4.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gangsterless/pytorch-softmax-splatting/6a7ff3b876050ded9957c4e68528b04d49621ad0/softcode/example_img/test4.jpg
--------------------------------------------------------------------------------
/softcode/example_img/test7.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gangsterless/pytorch-softmax-splatting/6a7ff3b876050ded9957c4e68528b04d49621ad0/softcode/example_img/test7.jpg
--------------------------------------------------------------------------------
/softcode/gridnet/__init__.py:
--------------------------------------------------------------------------------
1 | # @Time : 2021/1/23 20:19
2 |
3 | # @Author : xx
4 |
5 | # @File : __init__.py.py
6 |
7 | # @Software: PyCharm
8 |
9 | # @description=''
--------------------------------------------------------------------------------
/softcode/gridnet/modules.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 | import numpy as np
4 | import cv2
5 | from sklearn.decomposition import PCA
6 | from PIL import Image
7 | class Basic_layer1(nn.Module):
8 | def __init__(self,block_index):
9 | super(Basic_layer1, self).__init__()
10 | # 第一层
11 | self.layer = nn.Sequential(
12 | nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, stride=1, padding=1),
13 | nn.RReLU(inplace=False),
14 | nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1),
15 | nn.RReLU(inplace=False)
16 | )
17 | def forward(self,x):
18 | return self.layer(x)
19 |
20 | class Basic_layer2(nn.Module):
21 | def __init__(self,block_index):
22 | super(Basic_layer2, self).__init__()
23 | # 第二层
24 | self.layer = nn.Sequential(
25 | nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=2, padding=1),
26 | nn.RReLU(inplace=False),
27 | nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1),
28 | nn.RReLU(inplace=False)
29 | )
30 | def forward(self,x):
31 | return self.layer(x)
32 | class Basic_layer3(nn.Module):
33 | def __init__(self,block_index):
34 | super(Basic_layer3, self).__init__()
35 | # 第三层
36 | self.layer = nn.Sequential(
37 | nn.Conv2d(in_channels=64, out_channels=96, kernel_size=3, stride=2, padding=1),
38 | nn.RReLU(inplace=False),
39 | nn.Conv2d(in_channels=96, out_channels=96, kernel_size=3, stride=1, padding=1),
40 | nn.RReLU(inplace=False)
41 | )
42 | def forward(self,x):
43 | return self.layer(x)
44 |
45 | class Feature_extractor(nn.Module):
46 | def __init__(self,use_pretrained = True):
47 | super(Feature_extractor, self).__init__()
48 | self.use_pretrained = use_pretrained
49 | self.replace = False
50 | if use_pretrained:
51 |
52 | model = models.resnet18(pretrained=False)
53 | # model.load_state_dict(torch.load('weights/resnet18-5c106cde.pth'))
54 | # 只保留第一层 conv
55 | self.resnet_layer = nn.Sequential(*list(model.children())[:1])
56 | if self.replace:
57 | self.resnet_layer[0] = nn.Conv2d(in_channels=3,out_channels=64,kernel_size=7,stride=1,padding=3)
58 | self.resnet_layer[4] = self.resnet_layer[4][0]
59 | for each in self.resnet_layer:
60 | print(each)
61 | # print(self.resnet_layer)
62 | # for k,v in self.resnet_layer.named_parameters():
63 | # print(k)
64 | # print(self.resnet_layer.conv1.weight)
65 | # self.resnet_layer.conv1 = nn.Conv2d(in_channels=3,out_channels=64,kernel_size=7,stride=1,padding=3)
66 | # for k,v in self.resnet_layer.named_parameters():
67 | # # if k=='conv1.weight':
68 | # # print(v)
69 | #
70 | # print(k,v.requires_grad)
71 | else:
72 | self.layer1 = Basic_layer1()
73 | self.layer2 = Basic_layer2()
74 | self.layer3 = Basic_layer3()
75 | def forward(self,x):
76 | if self.use_pretrained:
77 | return torch.mean( self.resnet_layer(x),axis=1)
78 | else:
79 | self.feature_map1 = self.layer1(x)
80 | self.feature_map2 = self.layer2(self.feature_map1)
81 | self.feature_map3 = self.layer3(self.feature_map2)
82 | #把金字塔返回出来
83 | return [x,self.feature_map1,self.feature_map2,self.feature_map3]
84 |
85 |
86 | class LateralBlock(nn.Module):
87 |
88 | def __init__(self, ch_in, ch_out):
89 | super().__init__()
90 | self.f = nn.Sequential(
91 | nn.PReLU(),
92 | nn.Conv2d(ch_in, ch_out, kernel_size=3, padding=1),
93 | nn.PReLU(),
94 | nn.Conv2d(ch_out, ch_out, kernel_size=3, padding=1)
95 | )
96 | if ch_in != ch_out:
97 | self.conv = nn.Conv2d(ch_in, ch_out, kernel_size=3, padding=1)
98 |
99 | def forward(self, x):
100 | fx = self.f(x)
101 | if fx.shape[1] != x.shape[1]:
102 | x = self.conv(x)
103 |
104 | return fx + x
105 |
106 | class DownSamplingBlock(nn.Module):
107 |
108 | def __init__(self, ch_in, ch_out):
109 | super().__init__()
110 | self.f = nn.Sequential(
111 | nn.PReLU(),
112 | nn.Conv2d(ch_in, ch_out, kernel_size = 3, stride = 2, padding = 1),
113 | nn.PReLU(),
114 | nn.Conv2d(ch_out, ch_out, kernel_size = 3, padding = 1)
115 | )
116 |
117 | def forward(self, x):
118 | return self.f(x)
119 |
120 | class UpSamplingBlock(nn.Module):
121 |
122 | def __init__(self, ch_in, ch_out):
123 | super().__init__()
124 | self.f = nn.Sequential(
125 | nn.Upsample(scale_factor = 2, mode = 'bilinear', align_corners = False),
126 | # nn.UpsamplingNearest2d(scale_factor = 2),
127 | nn.PReLU(),
128 | nn.Conv2d(ch_in, ch_out, kernel_size = 3, padding = 1),
129 | nn.PReLU(),
130 | nn.Conv2d(ch_out, ch_out, kernel_size = 3, padding = 1)
131 | )
132 |
133 | def forward(self, x):
134 | return self.f(x)
135 | if __name__=='__main__':
136 | Fe = Feature_extractor()
137 | img_dir = '/media/zyt/新加卷/data/big4/code/softsplat-impl/test_data'
138 | img = img_dir+ '/' + 'first.png'
139 | # img = 'leaf.png'
140 | img = Image.open(img)
141 | # img = torch.FloatTensor(np.ascontiguousarray(
142 | # cv2.imread(filename=img, flags=-1).reshape(-1,3,320,320)))
143 |
144 |
145 | transform = transforms.Compose([transforms.Resize((224, 224)),
146 | transforms.ToTensor()])
147 |
148 | img = transform(img)
149 | img = img.unsqueeze(0)
150 | res = Fe(img)
151 | res = res.detach().numpy().reshape(112,112,1)*255
152 | res = np.stack([res,res,res],axis=2).squeeze()*255
153 | print(res.shape)
154 | # res = res.detach().numpy().reshape(160*160,64)
155 | # print(res.shape)
156 | # pca = PCA(n_components=3)
157 | # fit_res = pca.fit_transform(res).reshape(160,160,3)*255
158 | # cv2.imshow('fit_res.jpg',fit_res)
159 | cv2.imwrite('fitres.png',res)
160 | # cv2.waitKey(0)
161 | # print(fit_res.shape)
162 |
163 |
--------------------------------------------------------------------------------
/softcode/gridnet/net_module.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 |
4 | from gridnet.modules import LateralBlock, DownSamplingBlock, UpSamplingBlock
5 | class GridNet(nn.Module):
6 | def __init__(self, out_chs=3, grid_chs=[32, 64, 96]):
7 | # n_row = 3, n_col = 6, n_chs = [32, 64, 96]):
8 | super().__init__()
9 |
10 | self.n_row = 3
11 | self.n_col = 6
12 | self.n_chs = grid_chs
13 | assert len(grid_chs) == self.n_row, 'should give num channels for each row (scale stream)'
14 |
15 | self.lateral_init = LateralBlock(70, self.n_chs[0])
16 |
17 | for r, n_ch in enumerate(self.n_chs):
18 | for c in range(self.n_col - 1):
19 |
20 | setattr(self, f'lateral_{r}_{c}', LateralBlock(n_ch, n_ch))
21 |
22 | for r, (in_ch, out_ch) in enumerate(zip(self.n_chs[:-1], self.n_chs[1:])):
23 | for c in range(int(self.n_col / 2)):
24 | # 00 10 要特殊设置
25 | if r==0 and c==0:
26 | setattr(self, f'down_{r}_{c}', LateralBlock(128, out_ch))
27 | elif r==1 and c==0:
28 | setattr(self, f'down_{r}_{c}', LateralBlock(192, out_ch))
29 | else:
30 | setattr(self, f'down_{r}_{c}', DownSamplingBlock(in_ch, out_ch))
31 |
32 | for r, (in_ch, out_ch) in enumerate(zip(self.n_chs[1:], self.n_chs[:-1])):
33 | for c in range(int(self.n_col / 2)):
34 | setattr(self, f'up_{r}_{c}', UpSamplingBlock(in_ch, out_ch))
35 |
36 | self.lateral_final = LateralBlock(self.n_chs[0], out_chs)
37 |
38 | def forward(self, x_l1,x_l2,x_l3):
39 | # torch.Size([2, 32, 328, 448])
40 | state_00 = self.lateral_init(x_l1)
41 | #torch.Size([2, 64, 164, 224])
42 | state_10 = self.down_0_0(x_l2)
43 | #torch.Size([2, 96, 82, 112])
44 | state_20 = self.down_1_0(x_l3)
45 | #01的输入换成 warp的结果
46 | # torch.Size([2, 32, 164, 224])
47 | state_01 = self.lateral_0_0(state_00)
48 | state_11 = self.down_0_1(state_01) + self.lateral_1_0(state_10)
49 | state_21 = self.down_1_1(state_11) + self.lateral_2_0(state_20)
50 |
51 | state_02 = self.lateral_0_1(state_01)
52 | state_12 = self.down_0_2(state_02) + self.lateral_1_1(state_11)
53 | state_22 = self.down_1_2(state_12) + self.lateral_2_1(state_21)
54 |
55 | state_23 = self.lateral_2_2(state_22)
56 | state_13 = self.up_1_0(state_23) + self.lateral_1_2(state_12)
57 | state_03 = self.up_0_0(state_13) + self.lateral_0_2(state_02)
58 |
59 | state_24 = self.lateral_2_3(state_23)
60 | state_14 = self.up_1_1(state_24) + self.lateral_1_3(state_13)
61 | state_04 = self.up_0_1(state_14) + self.lateral_0_3(state_03)
62 |
63 | state_25 = self.lateral_2_4(state_24)
64 | state_15 = self.up_1_2(state_25) + self.lateral_1_4(state_14)
65 | state_05 = self.up_0_2(state_15) + self.lateral_0_4(state_04)
66 | return self.lateral_final(state_05)
67 | if __name__=='__main__':
68 | W = 448
69 | H = 328
70 | N = 2
71 | x_l1 = torch.rand(size=(N, 70, H, W)).cuda()
72 | x_l2 = torch.rand(size=(N, 128, H//2, W//2)).cuda()
73 | x_l3 = torch.rand(size=(N, 192, H//4, W//4)).cuda()
74 | model = GridNet(out_chs=3).cuda()
75 | res = model(x_l1,x_l2,x_l3)
76 | print(res.shape)
--------------------------------------------------------------------------------
/softcode/gridnet/single_net.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 |
4 | from gridnet.modules import LateralBlock, DownSamplingBlock, UpSamplingBlock
5 |
6 |
7 | class GridNet(nn.Module):
8 | def __init__(self, in_chs = 6, out_chs = 3, grid_chs=[32, 64, 96]):
9 | # n_row = 3, n_col = 6, n_chs = [32, 64, 96]):
10 | super().__init__()
11 |
12 | self.n_row = 3
13 | self.n_col = 6
14 | self.n_chs = grid_chs
15 | assert len(grid_chs) == self.n_row, 'should give num channels for each row (scale stream)'
16 |
17 | self.lateral_init = LateralBlock(in_chs, self.n_chs[0])
18 |
19 | for r, n_ch in enumerate(self.n_chs):
20 | for c in range(self.n_col - 1):
21 | setattr(self, f'lateral_{r}_{c}', LateralBlock(n_ch, n_ch))
22 |
23 | for r, (in_ch, out_ch) in enumerate(zip(self.n_chs[:-1], self.n_chs[1:])):
24 | for c in range(int(self.n_col / 2)):
25 | setattr(self, f'down_{r}_{c}', DownSamplingBlock(in_ch, out_ch))
26 |
27 | for r, (in_ch, out_ch) in enumerate(zip(self.n_chs[1:], self.n_chs[:-1])):
28 | for c in range(int(self.n_col / 2)):
29 | setattr(self, f'up_{r}_{c}', UpSamplingBlock(in_ch, out_ch))
30 |
31 | self.lateral_final = LateralBlock(self.n_chs[0], out_chs)
32 |
33 | def forward(self, x1,x2):
34 | x = torch.cat([x1,x2],dim=1)
35 | state_00 = self.lateral_init(x)
36 | state_10 = self.down_0_0(state_00)
37 | state_20 = self.down_1_0(state_10)
38 |
39 | state_01 = self.lateral_0_0(state_00)
40 | state_11 = self.down_0_1(state_01) + self.lateral_1_0(state_10)
41 | state_21 = self.down_1_1(state_11) + self.lateral_2_0(state_20)
42 |
43 | state_02 = self.lateral_0_1(state_01)
44 | state_12 = self.down_0_2(state_02) + self.lateral_1_1(state_11)
45 | state_22 = self.down_1_2(state_12) + self.lateral_2_1(state_21)
46 |
47 | state_23 = self.lateral_2_2(state_22)
48 | state_13 = self.up_1_0(state_23) + self.lateral_1_2(state_12)
49 | state_03 = self.up_0_0(state_13) + self.lateral_0_2(state_02)
50 |
51 | state_24 = self.lateral_2_3(state_23)
52 | state_14 = self.up_1_1(state_24) + self.lateral_1_3(state_13)
53 | state_04 = self.up_0_1(state_14) + self.lateral_0_3(state_03)
54 |
55 | state_25 = self.lateral_2_4(state_24)
56 | state_15 = self.up_1_2(state_25) + self.lateral_1_4(state_14)
57 | state_05 = self.up_0_2(state_15) + self.lateral_0_4(state_04)
58 |
59 | return self.lateral_final(state_05)
--------------------------------------------------------------------------------
/softcode/gridnet/train.py:
--------------------------------------------------------------------------------
1 | #我们要试试 只用两张图片合成,总应该有一个baseline
2 | from gridnet.single_net import GridNet
3 | import torch
4 | from vimo_dataset import Vimeo
5 | from torch.utils.data import DataLoader
6 | from loss_f import LapLoss
7 | vimo_data_dir = 'D:/dataset/vimeo_triplet'
8 | def EPE(input_flow, target_flow):
9 | return torch.norm(target_flow-input_flow,p=2,dim=1).mean()
10 | def train():
11 | batch_size = 1
12 | total_step = 100
13 | num_workers = 0
14 | W = 448
15 | H = 256
16 | lr = 1e-4
17 | criteration = LapLoss()
18 | vimo_dataset = Vimeo(base_dir=vimo_data_dir)
19 | train_loader = DataLoader(vimo_dataset,
20 | batch_size=batch_size,
21 | shuffle=True,
22 | num_workers=num_workers,
23 | pin_memory=True)
24 |
25 | model = GridNet().cuda().train()
26 | optimizer = torch.optim.Adam(params=model.parameters(), lr=lr, weight_decay=4e-4)
27 |
28 | print('这是 测试 gridnet')
29 | for step in range(total_step):
30 | total_loss = 0
31 | total_epe = 0
32 | for ix, data in enumerate(train_loader):
33 | img1, img2, tar = data
34 | img1 = img1.cuda()
35 | img2 = img2.cuda()
36 | tar = tar.cuda()
37 | img_out = model(img1, img2)
38 | # loss = torch.nn.functional.l1_loss(img_out,tar)
39 | loss = criteration(img_out, tar)
40 |
41 | optimizer.zero_grad()
42 |
43 | loss.backward()
44 | optimizer.step()
45 | print()
46 | print('data idx:' + ' lr :' + str(lr) + ' epoch: ' + str(ix) + ' / ' + str(len(train_loader)))
47 | print('loss value :', loss.item())
48 | epe = EPE(img_out,tar)
49 | print('EPE :',epe.item())
50 | total_loss += loss
51 | total_epe+=epe
52 | # f.write('epoch: ' + str(step) + ' avg loss :' + str(total_loss.item() / len(train_loader)))
53 | # f.write('\n')
54 | print('epoch: ' + str(step) + ' avg loss :' + str(total_loss.item() / len(train_loader)))
55 | print('epoch: ' + str(step) + ' avg epe :' + str(total_epe.item() / len(train_loader)))
56 | if __name__=='__main__':
57 | train()
--------------------------------------------------------------------------------
/softcode/loss_f.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import torch
3 | from torch.autograd import Variable
4 | import torch.nn as nn
5 | def build_gauss_kernel(size=5, sigma=1.0, n_channels=1, cuda=False):
6 | if size % 2 != 1:
7 | raise ValueError("kernel size must be uneven")
8 | grid = np.float32(np.mgrid[0:size, 0:size].T)
9 | gaussian = lambda x: np.exp((x - size // 2) ** 2 / (-2 * sigma ** 2)) ** 2
10 | kernel = np.sum(gaussian(grid), axis=2)
11 | kernel /= np.sum(kernel)
12 | # repeat same kernel across depth dimension
13 | kernel = np.tile(kernel, (n_channels, 1, 1))
14 | # conv weight should be (out_channels, groups/in_channels, h, w),
15 | # and since we have depth-separable convolution we want the groups dimension to be 1
16 | kernel = torch.FloatTensor(kernel[:, None, :, :])
17 | if cuda:
18 | kernel = kernel.cuda()
19 | return Variable(kernel, requires_grad=False)
20 |
21 |
22 | def conv_gauss(img, kernel):
23 | """ convolve img with a gaussian kernel that has been built with build_gauss_kernel """
24 | n_channels, _, kw, kh = kernel.shape
25 | img = torch.nn.functional.pad(img, (kw // 2, kh // 2, kw // 2, kh // 2), mode='replicate')
26 | return torch.nn.functional.conv2d(img, kernel, groups=n_channels)
27 |
28 |
29 | def laplacian_pyramid(img, kernel, max_levels=5):
30 | current = img
31 | pyr = []
32 |
33 | for level in range(max_levels):
34 | filtered = conv_gauss(current, kernel)
35 | diff = current - filtered
36 | pyr.append(diff)
37 | current = torch.nn.functional.avg_pool2d(filtered, 2)
38 |
39 | pyr.append(current)
40 | return pyr
41 |
42 |
43 | class LapLoss(nn.Module):
44 | def __init__(self, max_levels=5, k_size=5, sigma=2.0):
45 | super(LapLoss, self).__init__()
46 | self.max_levels = max_levels
47 | self.k_size = k_size
48 | self.sigma = sigma
49 | self._gauss_kernel = None
50 |
51 | def forward(self, input, target):
52 | if self._gauss_kernel is None or self._gauss_kernel.shape[1] != input.shape[1]:
53 | self._gauss_kernel = build_gauss_kernel(
54 | size=self.k_size, sigma=self.sigma,
55 | n_channels=input.shape[1], cuda=input.is_cuda
56 | )
57 | pyr_input = laplacian_pyramid(input, self._gauss_kernel, self.max_levels)
58 | pyr_target = laplacian_pyramid(target, self._gauss_kernel, self.max_levels)
59 |
60 | weights = [1, 2, 4, 8, 16, 32]
61 |
62 | return sum(weights[i]*torch.nn.functional.l1_loss(a, b) for i, (a, b) in enumerate(zip(pyr_input, pyr_target))).mean()
--------------------------------------------------------------------------------
/softcode/main_net.py:
--------------------------------------------------------------------------------
1 | # @Time : 2021/1/22 17:53
2 |
3 | # @Author : xx
4 |
5 | # @File : main_net.py
6 |
7 | # @Software: PyCharm
8 |
9 | # @description=''
10 | import torch.nn as nn
11 | from pwc.pwc_network import Network as flow_net
12 | from softsplatting import softsplat
13 | from softsplatting.run import backwarp
14 | import torch
15 | from other_modules import context_extractor_layer , Matric_UNet
16 | from gridnet.net_module import GridNet
17 | from pwc.utils.flow_utils import show_compare
18 | import cv2
19 |
20 |
21 | class Main_net(nn.Module):
22 | def __init__(self,shape):
23 | super(Main_net, self).__init__()
24 |
25 | self.shape = shape
26 |
27 | self.feature_extractor = context_extractor_layer()
28 |
29 |
30 | self.flow_extractor = flow_net()
31 |
32 |
33 | self.alpha = nn.Parameter(-torch.ones(1))
34 |
35 | self.Matric_UNet = Matric_UNet()
36 | self.grid_net = GridNet()
37 |
38 | def scale_flow(self,flow):
39 |
40 | intHeight,intWidth = self.shape[2:]
41 |
42 | # https://github.com/sniklaus/softmax-splatting/issues/12
43 | flow_scale_half =(20.0/2.0) * nn.functional.interpolate(input=flow,
44 | size=(int(intHeight/2), int(intWidth /2)),
45 | mode='bilinear', align_corners=False)
46 | flow_scale_raw =(20.0)* nn.functional.interpolate(input=flow,size=(int(intHeight), int(intWidth)),
47 | mode='bilinear', align_corners=False)
48 | return [flow_scale_raw,flow_scale_half,flow*(20/4.0)]
49 |
50 | def scale_tenMetric(self, tenMetric):
51 | intHeight, intWidth = self.shape[2:]
52 | tenMetric_scale_half = nn.functional.interpolate(input=tenMetric,size=(int(intHeight / 2), int(intWidth / 2)), mode='bilinear', align_corners=False)
53 | tenMetric_scale_quarter = nn.functional.interpolate(input=tenMetric, size=(int(intHeight/4), int(intWidth/4)),
54 | mode='bilinear', align_corners=False)
55 | return [tenMetric,tenMetric_scale_half,tenMetric_scale_quarter ]
56 | def forward(self,img1,img2):
57 | feature_pyrr1 = self.feature_extractor(img1)
58 | feature_pyrr2 = self.feature_extractor(img2)
59 |
60 | flow_1to2 = self.flow_extractor(img1,img2)
61 |
62 | flow_1to2_pyri = self.scale_flow(flow_1to2)
63 |
64 | # show_compare(flow_1to2_pyri[0].squeeze().cpu().detach().numpy().transpose(1,2,0), flow_1to2_pyri[0].squeeze().cpu().detach().numpy().transpose(1,2,0))
65 | flow_2to1 = self.flow_extractor(img2, img1)
66 | flow_2to1_pyri = self.scale_flow(flow_2to1)
67 |
68 |
69 | tenMetric_1to2 = nn.functional.l1_loss(input=img1, target=backwarp(tenInput=img2, tenFlow=flow_1to2_pyri[0]),
70 | reduction='none').mean(1, True)
71 |
72 | tenMetric_1to2 = self.Matric_UNet(tenMetric_1to2,img1)
73 | tenMetric_ls_1to2 = self.scale_tenMetric(tenMetric_1to2)
74 |
75 | warped_img1 = softsplat.FunctionSoftsplat(tenInput=img1, tenFlow=flow_1to2_pyri[0] * 0.5,
76 | tenMetric=self.alpha* tenMetric_ls_1to2[0],
77 | strType='softmax') # -20.0 is a hyperparameter, called 'beta' in the paper, that could be learned using a torch.Parameter
78 | # print('beta 1',self.alpha)
79 | # print('beta 2', self.beta2)
80 | # warped_img1_out = warped_img1.squeeze().cpu().detach().numpy().transpose(1,2,0)
81 | # cv2.imshow(warped_img1_out)
82 | # cv2.waitKey(0)
83 | warped_pyri1_1 = softsplat.FunctionSoftsplat(tenInput=feature_pyrr1[0], tenFlow=flow_1to2_pyri[0] * 0.5,
84 | tenMetric=self.alpha* tenMetric_ls_1to2[0],
85 | strType='softmax')
86 | warped_pyri1_2 = softsplat.FunctionSoftsplat(tenInput=feature_pyrr1[1], tenFlow=flow_1to2_pyri[1] * 0.5,
87 | tenMetric=self.alpha * tenMetric_ls_1to2[1],
88 | strType='softmax')
89 | warped_pyri1_3 = softsplat.FunctionSoftsplat(tenInput=feature_pyrr1[2], tenFlow=flow_1to2_pyri[2] * 0.5,
90 | tenMetric=self.alpha * tenMetric_ls_1to2[2],
91 | strType='softmax')
92 |
93 | tenMetric_2to1 = nn.functional.l1_loss(input=img2, target=backwarp(tenInput=img1, tenFlow=flow_2to1_pyri[0]),
94 | reduction='none').mean(1, True)
95 | tenMetric_2to1 = self.Matric_UNet(tenMetric_2to1, img2)
96 | tenMetric_ls_2to1 = self.scale_tenMetric(tenMetric_2to1)
97 |
98 | warped_img2 = softsplat.FunctionSoftsplat(tenInput=img2, tenFlow=flow_2to1_pyri[0] * 0.5,
99 | tenMetric=self.alpha * tenMetric_ls_2to1[0],
100 | strType='softmax') # -20.0 is a hyperparameter, called 'beta' in the paper, that could be learned using a torch.Parameter
101 |
102 | warped_pyri2_1= softsplat.FunctionSoftsplat(tenInput=feature_pyrr2[0], tenFlow=flow_2to1_pyri[0] * 0.5,
103 | tenMetric=self.alpha * tenMetric_ls_2to1[0],
104 | strType='softmax')
105 | warped_pyri2_2 = softsplat.FunctionSoftsplat(tenInput=feature_pyrr2[1], tenFlow=flow_2to1_pyri[1] * 0.5,
106 | tenMetric=self.alpha * tenMetric_ls_2to1[1],
107 | strType='softmax')
108 | warped_pyri2_3 = softsplat.FunctionSoftsplat(tenInput=feature_pyrr2[2], tenFlow=flow_2to1_pyri[2] * 0.5,
109 | tenMetric=self.alpha * tenMetric_ls_2to1[2],
110 | strType='softmax')
111 | grid_input_l1 = torch.cat([warped_img1, warped_pyri1_1,warped_img2,warped_pyri2_1], dim=1)
112 |
113 | grid_input_l2 = torch.cat([ warped_pyri1_2,warped_pyri2_2], dim=1)
114 |
115 | grid_input_l3 = torch.cat([ warped_pyri1_3,warped_pyri2_3], dim=1)
116 |
117 | out = self.grid_net(grid_input_l1,grid_input_l2,grid_input_l3)
118 |
119 | return out
120 | if __name__=='__main__':
121 | W = 448
122 | H = 256
123 | N = 1
124 | tenFirst = torch.rand(size=(N, 3, H, W)).cuda()
125 | tenSecond = torch.rand(size=(N, 3, H, W)).cuda()
126 |
127 | model = Main_net(tenFirst.shape).cuda()
128 |
129 | res = model(tenFirst,tenSecond)
130 | print(res.shape)
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
--------------------------------------------------------------------------------
/softcode/other_modules.py:
--------------------------------------------------------------------------------
1 | import torch.nn as nn
2 | import torch
3 | class context_extractor_layer(nn.Module):
4 | def __init__(self):
5 | super(context_extractor_layer, self).__init__()
6 | # 第一层
7 | self.layer1 = nn.Sequential(
8 | nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, stride=1, padding=1),
9 | nn.ReLU(inplace=False),
10 | nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1),
11 | nn.ReLU(inplace=False)
12 | )
13 |
14 | self.layer2 = nn.Sequential(
15 | nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=2, padding=1),
16 | nn.ReLU(inplace=False),
17 | nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1),
18 | nn.ReLU(inplace=False)
19 | )
20 |
21 | self.layer3 = nn.Sequential(
22 | nn.Conv2d(in_channels=64, out_channels=96, kernel_size=3, stride=2, padding=1),
23 | nn.ReLU(inplace=False),
24 | nn.Conv2d(in_channels=96, out_channels=96, kernel_size=3, stride=1, padding=1),
25 | nn.ReLU(inplace=False)
26 | )
27 |
28 | def forward(self, x):
29 | layer1 = self.layer1(x)
30 | layer2 = self.layer2(layer1)
31 | out = self.layer3(layer2)
32 | return [layer1, layer2, out]
33 |
34 |
35 | # 作者说可以不用Unet来估计那个 important metric 但是我先试试再说
36 | # class Metric(torch.nn.Module):
37 | # def __init__(self):
38 | # super(Metric, self).__init__()
39 | #
40 | # self.paramScale = torch.nn.Parameter(-torch.ones(1, 1, 1, 1))
41 | #
42 | #
43 | # def forward(self, tenFirst, tenSecond, tenFlow):
44 | # return self.paramScale * torch.nn.functional.l1_loss(input=tenFirst, target=backwarp(tenSecond, tenFlow)).mean(1, True)
45 | #
46 | #
47 | class Matric_UNet(nn.Module):
48 | def __init__(self):
49 | super(Matric_UNet, self).__init__()
50 |
51 | class Decoder(nn.Module):
52 | def __init__(self,l_num):
53 | super(Decoder, self).__init__()
54 |
55 | self.conv_relu = nn.Sequential(
56 | nn.ReLU(inplace=False),
57 | nn.Conv2d(in_channels=l_num*32*2, out_channels=l_num*32, kernel_size=3, stride=1, padding=1),
58 | nn.ReLU(inplace=False),
59 | nn.Conv2d(in_channels=l_num*32, out_channels=l_num*32, kernel_size=3, stride=1, padding=1),
60 |
61 | )
62 |
63 | def forward(self, x1, x2):
64 |
65 | x1 = torch.cat((x1, x2), dim=1)
66 | x1 = self.conv_relu(x1)
67 | return x1
68 |
69 | # 这个是把第一张图片从3通道变成12通道负责color consistency
70 | self.conv_img = nn.Conv2d(in_channels=3, out_channels=12, kernel_size=3, stride=1, padding=1)
71 | # 这个是把两张图片的loss从1通道变成4通道 负责计算背景的重要程度
72 | self.conv_metric = nn.Conv2d(in_channels=1, out_channels=4, kernel_size=3, stride=1, padding=1)
73 | self.down_l1 = nn.Sequential(
74 | nn.ReLU(inplace=False),
75 | nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3, stride=2, padding=1),
76 | nn.ReLU(inplace=False),
77 | nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1),
78 | )
79 | self.down_l2 = nn.Sequential(
80 | nn.ReLU(inplace=False),
81 | nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=2, padding=1),
82 | nn.ReLU(inplace=False),
83 | nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1),
84 | )
85 | self.down_l3 = nn.Sequential(
86 | nn.ReLU(inplace=False),
87 | nn.Conv2d(in_channels=64, out_channels=96, kernel_size=3, stride=2, padding=1),
88 | nn.ReLU(inplace=False),
89 | nn.Conv2d(in_channels=96, out_channels=96, kernel_size=3, stride=1, padding=1),
90 | )
91 | self.middle = nn.Sequential(
92 | nn.Conv2d(in_channels=96, out_channels=96, kernel_size=3, stride=1, padding=1),
93 | nn.ReLU(inplace=False),
94 | nn.Conv2d(in_channels=96, out_channels=96, kernel_size=3, stride=1, padding=1),
95 | nn.ReLU(inplace=False)
96 | )
97 | self.up_l3 = nn.Sequential(
98 | nn.UpsamplingBilinear2d(scale_factor=2),
99 | nn.ReLU(inplace=False),
100 | nn.Conv2d(in_channels=96, out_channels=64, kernel_size=3, stride=1, padding=1),
101 | nn.ReLU(inplace=False),
102 | nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1),
103 | nn.ReLU(inplace=False)
104 | )
105 | self.up_l2 = nn.Sequential(
106 | nn.UpsamplingBilinear2d(scale_factor=2),
107 | nn.ReLU(inplace=False),
108 | nn.Conv2d(in_channels=64, out_channels=32, kernel_size=3, stride=1, padding=1),
109 | nn.ReLU(inplace=False),
110 | nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1),
111 | nn.ReLU(inplace=False)
112 | )
113 | self.up_l1 = nn.Sequential(
114 | nn.UpsamplingBilinear2d(scale_factor=2),
115 | nn.ReLU(inplace=False),
116 | nn.Conv2d(in_channels=32, out_channels=16, kernel_size=3, stride=1, padding=1),
117 | nn.ReLU(inplace=False),
118 | nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3, stride=1, padding=1),
119 | )
120 | self.out_seq = nn.Sequential(
121 | nn.ReLU(inplace=False),
122 | nn.Conv2d(in_channels=16, out_channels=1, kernel_size=3, stride=1, padding=1),
123 | #最后这个到底有没有有点慌
124 | # nn.ReLU(inplace=False),
125 | )
126 | self.Decoder3 = Decoder(3)
127 | self.Decoder2 = Decoder(2)
128 | self.Decoder1 =Decoder(1)
129 |
130 | def forward(self, tenMetric, img1):
131 | conv_img = self.conv_img(img1)
132 | conv_metric = self.conv_metric(tenMetric)
133 | ten_input_l0 = torch.cat([conv_metric, conv_img], dim=1)
134 | ten_d_l1 = self.down_l1(ten_input_l0)
135 | ten_d_l2 = self.down_l2(ten_d_l1)
136 | ten_d_l3 = self.down_l3(ten_d_l2)
137 | ten_middle = self.middle(ten_d_l3)
138 |
139 | ten_u_l3 = self.Decoder3(ten_d_l3, ten_middle)
140 | ten_u_l2 = self.up_l3(ten_u_l3)
141 |
142 | ten_u_l2 = self.Decoder2(ten_d_l2, ten_u_l2)
143 | ten_u_l1 = self.up_l2(ten_u_l2)
144 |
145 | ten_u_l1 = self.Decoder1(ten_d_l1, ten_u_l1)
146 | ten_out = self.up_l1(ten_u_l1)
147 |
148 | return self.out_seq(ten_out)
149 |
150 | if __name__=='__main__':
151 | W = 448
152 | H = 328
153 | test_tenmatric = torch.rand(size=(2,1,H,W))
154 | test_img = torch.rand(size=(2, 3, H, W))
155 | model = Matric_UNet()
156 | res = model(test_tenmatric,test_img)
157 | print(model)
158 | print(res.shape)
159 |
160 |
161 |
--------------------------------------------------------------------------------
/softcode/pair_img/im1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gangsterless/pytorch-softmax-splatting/6a7ff3b876050ded9957c4e68528b04d49621ad0/softcode/pair_img/im1.png
--------------------------------------------------------------------------------
/softcode/pair_img/im2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gangsterless/pytorch-softmax-splatting/6a7ff3b876050ded9957c4e68528b04d49621ad0/softcode/pair_img/im2.png
--------------------------------------------------------------------------------
/softcode/pair_img/im3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gangsterless/pytorch-softmax-splatting/6a7ff3b876050ded9957c4e68528b04d49621ad0/softcode/pair_img/im3.png
--------------------------------------------------------------------------------
/softcode/pwc/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
--------------------------------------------------------------------------------
/softcode/pwc/__init__.py:
--------------------------------------------------------------------------------
1 | # @Time : 2021/1/23 21:19
2 |
3 | # @Author : xx
4 |
5 | # @File : __init__.py
6 |
7 | # @Software: PyCharm
8 |
9 | # @description=''
--------------------------------------------------------------------------------
/softcode/pwc/comparison/comparison.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gangsterless/pytorch-softmax-splatting/6a7ff3b876050ded9957c4e68528b04d49621ad0/softcode/pwc/comparison/comparison.gif
--------------------------------------------------------------------------------
/softcode/pwc/comparison/comparison.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import math
4 | import moviepy
5 | import moviepy.editor
6 | import numpy
7 | import PIL
8 | import PIL.Image
9 | import PIL.ImageFont
10 | import PIL.ImageDraw
11 |
12 | intX = 32
13 | intY = 436 - 64
14 |
15 | objImages = [ {
16 | 'strFile': 'official - caffe.png',
17 | 'strText': 'official - Caffe'
18 | }, {
19 | 'strFile': 'this - pytorch.png',
20 | 'strText': 'this - PyTorch'
21 | } ]
22 |
23 | npyImages = []
24 |
25 | for objImage in objImages:
26 | objOutput = PIL.Image.open(objImage['strFile']).convert('RGB')
27 |
28 | for intU in [ intShift - 10 for intShift in range(20) ]:
29 | for intV in [ intShift - 10 for intShift in range(20) ]:
30 | if math.sqrt(math.pow(intU, 2.0) + math.pow(intV, 2.0)) <= 5.0:
31 | PIL.ImageDraw.Draw(objOutput).text((intX + intU, intY + intV), objImage['strText'], (255, 255, 255), PIL.ImageFont.truetype('freefont/FreeSerifBold.ttf', 32))
32 | # end
33 | # end
34 | # end
35 |
36 | PIL.ImageDraw.Draw(objOutput).text((intX, intY), objImage['strText'], (0, 0, 0), PIL.ImageFont.truetype('freefont/FreeSerifBold.ttf', 32))
37 |
38 | npyImages.append(numpy.array(objOutput))
39 | # end
40 |
41 | moviepy.editor.ImageSequenceClip(sequence=npyImages, fps=1).write_gif(filename='comparison.gif', program='ImageMagick', opt='optimizeplus')
--------------------------------------------------------------------------------
/softcode/pwc/comparison/official - caffe.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gangsterless/pytorch-softmax-splatting/6a7ff3b876050ded9957c4e68528b04d49621ad0/softcode/pwc/comparison/official - caffe.png
--------------------------------------------------------------------------------
/softcode/pwc/comparison/this - pytorch.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gangsterless/pytorch-softmax-splatting/6a7ff3b876050ded9957c4e68528b04d49621ad0/softcode/pwc/comparison/this - pytorch.png
--------------------------------------------------------------------------------
/softcode/pwc/correlation/README.md:
--------------------------------------------------------------------------------
1 | This is an adaptation of the FlowNet2 implementation in order to compute cost volumes. Should you be making use of this work, please make sure to adhere to the licensing terms of the original authors. Should you be making use or modify this particular implementation, please acknowledge it appropriately.
--------------------------------------------------------------------------------
/softcode/pwc/correlation/__pycache__/correlation.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gangsterless/pytorch-softmax-splatting/6a7ff3b876050ded9957c4e68528b04d49621ad0/softcode/pwc/correlation/__pycache__/correlation.cpython-36.pyc
--------------------------------------------------------------------------------
/softcode/pwc/correlation/correlation.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import torch
4 |
5 | import cupy
6 | import re
7 |
8 | kernel_Correlation_rearrange = '''
9 | extern "C" __global__ void kernel_Correlation_rearrange(
10 | const int n,
11 | const float* input,
12 | float* output
13 | ) {
14 | int intIndex = (blockIdx.x * blockDim.x) + threadIdx.x;
15 |
16 | if (intIndex >= n) {
17 | return;
18 | }
19 |
20 | int intSample = blockIdx.z;
21 | int intChannel = blockIdx.y;
22 |
23 | float fltValue = input[(((intSample * SIZE_1(input)) + intChannel) * SIZE_2(input) * SIZE_3(input)) + intIndex];
24 |
25 | __syncthreads();
26 |
27 | int intPaddedY = (intIndex / SIZE_3(input)) + 4;
28 | int intPaddedX = (intIndex % SIZE_3(input)) + 4;
29 | int intRearrange = ((SIZE_3(input) + 8) * intPaddedY) + intPaddedX;
30 |
31 | output[(((intSample * SIZE_1(output) * SIZE_2(output)) + intRearrange) * SIZE_1(input)) + intChannel] = fltValue;
32 | }
33 | '''
34 |
35 | kernel_Correlation_updateOutput = '''
36 | extern "C" __global__ void kernel_Correlation_updateOutput(
37 | const int n,
38 | const float* rbot0,
39 | const float* rbot1,
40 | float* top
41 | ) {
42 | extern __shared__ char patch_data_char[];
43 |
44 | float *patch_data = (float *)patch_data_char;
45 |
46 | // First (upper left) position of kernel upper-left corner in current center position of neighborhood in image 1
47 | int x1 = blockIdx.x + 4;
48 | int y1 = blockIdx.y + 4;
49 | int item = blockIdx.z;
50 | int ch_off = threadIdx.x;
51 |
52 | // Load 3D patch into shared shared memory
53 | for (int j = 0; j < 1; j++) { // HEIGHT
54 | for (int i = 0; i < 1; i++) { // WIDTH
55 | int ji_off = (j + i) * SIZE_3(rbot0);
56 | for (int ch = ch_off; ch < SIZE_3(rbot0); ch += 32) { // CHANNELS
57 | int idx1 = ((item * SIZE_1(rbot0) + y1+j) * SIZE_2(rbot0) + x1+i) * SIZE_3(rbot0) + ch;
58 | int idxPatchData = ji_off + ch;
59 | patch_data[idxPatchData] = rbot0[idx1];
60 | }
61 | }
62 | }
63 |
64 | __syncthreads();
65 |
66 | __shared__ float sum[32];
67 |
68 | // Compute correlation
69 | for (int top_channel = 0; top_channel < SIZE_1(top); top_channel++) {
70 | sum[ch_off] = 0;
71 |
72 | int s2o = top_channel % 9 - 4;
73 | int s2p = top_channel / 9 - 4;
74 |
75 | for (int j = 0; j < 1; j++) { // HEIGHT
76 | for (int i = 0; i < 1; i++) { // WIDTH
77 | int ji_off = (j + i) * SIZE_3(rbot0);
78 | for (int ch = ch_off; ch < SIZE_3(rbot0); ch += 32) { // CHANNELS
79 | int x2 = x1 + s2o;
80 | int y2 = y1 + s2p;
81 |
82 | int idxPatchData = ji_off + ch;
83 | int idx2 = ((item * SIZE_1(rbot0) + y2+j) * SIZE_2(rbot0) + x2+i) * SIZE_3(rbot0) + ch;
84 |
85 | sum[ch_off] += patch_data[idxPatchData] * rbot1[idx2];
86 | }
87 | }
88 | }
89 |
90 | __syncthreads();
91 |
92 | if (ch_off == 0) {
93 | float total_sum = 0;
94 | for (int idx = 0; idx < 32; idx++) {
95 | total_sum += sum[idx];
96 | }
97 | const int sumelems = SIZE_3(rbot0);
98 | const int index = ((top_channel*SIZE_2(top) + blockIdx.y)*SIZE_3(top))+blockIdx.x;
99 | top[index + item*SIZE_1(top)*SIZE_2(top)*SIZE_3(top)] = total_sum / (float)sumelems;
100 | }
101 | }
102 | }
103 | '''
104 |
105 | kernel_Correlation_updateGradFirst = '''
106 | #define ROUND_OFF 50000
107 |
108 | extern "C" __global__ void kernel_Correlation_updateGradFirst(
109 | const int n,
110 | const int intSample,
111 | const float* rbot0,
112 | const float* rbot1,
113 | const float* gradOutput,
114 | float* gradFirst,
115 | float* gradSecond
116 | ) { for (int intIndex = (blockIdx.x * blockDim.x) + threadIdx.x; intIndex < n; intIndex += blockDim.x * gridDim.x) {
117 | int n = intIndex % SIZE_1(gradFirst); // channels
118 | int l = (intIndex / SIZE_1(gradFirst)) % SIZE_3(gradFirst) + 4; // w-pos
119 | int m = (intIndex / SIZE_1(gradFirst) / SIZE_3(gradFirst)) % SIZE_2(gradFirst) + 4; // h-pos
120 |
121 | // round_off is a trick to enable integer division with ceil, even for negative numbers
122 | // We use a large offset, for the inner part not to become negative.
123 | const int round_off = ROUND_OFF;
124 | const int round_off_s1 = round_off;
125 |
126 | // We add round_off before_s1 the int division and subtract round_off after it, to ensure the formula matches ceil behavior:
127 | int xmin = (l - 4 + round_off_s1 - 1) + 1 - round_off; // ceil (l - 4)
128 | int ymin = (m - 4 + round_off_s1 - 1) + 1 - round_off; // ceil (l - 4)
129 |
130 | // Same here:
131 | int xmax = (l - 4 + round_off_s1) - round_off; // floor (l - 4)
132 | int ymax = (m - 4 + round_off_s1) - round_off; // floor (m - 4)
133 |
134 | float sum = 0;
135 | if (xmax>=0 && ymax>=0 && (xmin<=SIZE_3(gradOutput)-1) && (ymin<=SIZE_2(gradOutput)-1)) {
136 | xmin = max(0,xmin);
137 | xmax = min(SIZE_3(gradOutput)-1,xmax);
138 |
139 | ymin = max(0,ymin);
140 | ymax = min(SIZE_2(gradOutput)-1,ymax);
141 |
142 | for (int p = -4; p <= 4; p++) {
143 | for (int o = -4; o <= 4; o++) {
144 | // Get rbot1 data:
145 | int s2o = o;
146 | int s2p = p;
147 | int idxbot1 = ((intSample * SIZE_1(rbot0) + (m+s2p)) * SIZE_2(rbot0) + (l+s2o)) * SIZE_3(rbot0) + n;
148 | float bot1tmp = rbot1[idxbot1]; // rbot1[l+s2o,m+s2p,n]
149 |
150 | // Index offset for gradOutput in following loops:
151 | int op = (p+4) * 9 + (o+4); // index[o,p]
152 | int idxopoffset = (intSample * SIZE_1(gradOutput) + op);
153 |
154 | for (int y = ymin; y <= ymax; y++) {
155 | for (int x = xmin; x <= xmax; x++) {
156 | int idxgradOutput = (idxopoffset * SIZE_2(gradOutput) + y) * SIZE_3(gradOutput) + x; // gradOutput[x,y,o,p]
157 | sum += gradOutput[idxgradOutput] * bot1tmp;
158 | }
159 | }
160 | }
161 | }
162 | }
163 | const int sumelems = SIZE_1(gradFirst);
164 | const int bot0index = ((n * SIZE_2(gradFirst)) + (m-4)) * SIZE_3(gradFirst) + (l-4);
165 | gradFirst[bot0index + intSample*SIZE_1(gradFirst)*SIZE_2(gradFirst)*SIZE_3(gradFirst)] = sum / (float)sumelems;
166 | } }
167 | '''
168 |
169 | kernel_Correlation_updateGradSecond = '''
170 | #define ROUND_OFF 50000
171 |
172 | extern "C" __global__ void kernel_Correlation_updateGradSecond(
173 | const int n,
174 | const int intSample,
175 | const float* rbot0,
176 | const float* rbot1,
177 | const float* gradOutput,
178 | float* gradFirst,
179 | float* gradSecond
180 | ) { for (int intIndex = (blockIdx.x * blockDim.x) + threadIdx.x; intIndex < n; intIndex += blockDim.x * gridDim.x) {
181 | int n = intIndex % SIZE_1(gradSecond); // channels
182 | int l = (intIndex / SIZE_1(gradSecond)) % SIZE_3(gradSecond) + 4; // w-pos
183 | int m = (intIndex / SIZE_1(gradSecond) / SIZE_3(gradSecond)) % SIZE_2(gradSecond) + 4; // h-pos
184 |
185 | // round_off is a trick to enable integer division with ceil, even for negative numbers
186 | // We use a large offset, for the inner part not to become negative.
187 | const int round_off = ROUND_OFF;
188 | const int round_off_s1 = round_off;
189 |
190 | float sum = 0;
191 | for (int p = -4; p <= 4; p++) {
192 | for (int o = -4; o <= 4; o++) {
193 | int s2o = o;
194 | int s2p = p;
195 |
196 | //Get X,Y ranges and clamp
197 | // We add round_off before_s1 the int division and subtract round_off after it, to ensure the formula matches ceil behavior:
198 | int xmin = (l - 4 - s2o + round_off_s1 - 1) + 1 - round_off; // ceil (l - 4 - s2o)
199 | int ymin = (m - 4 - s2p + round_off_s1 - 1) + 1 - round_off; // ceil (l - 4 - s2o)
200 |
201 | // Same here:
202 | int xmax = (l - 4 - s2o + round_off_s1) - round_off; // floor (l - 4 - s2o)
203 | int ymax = (m - 4 - s2p + round_off_s1) - round_off; // floor (m - 4 - s2p)
204 |
205 | if (xmax>=0 && ymax>=0 && (xmin<=SIZE_3(gradOutput)-1) && (ymin<=SIZE_2(gradOutput)-1)) {
206 | xmin = max(0,xmin);
207 | xmax = min(SIZE_3(gradOutput)-1,xmax);
208 |
209 | ymin = max(0,ymin);
210 | ymax = min(SIZE_2(gradOutput)-1,ymax);
211 |
212 | // Get rbot0 data:
213 | int idxbot0 = ((intSample * SIZE_1(rbot0) + (m-s2p)) * SIZE_2(rbot0) + (l-s2o)) * SIZE_3(rbot0) + n;
214 | float bot0tmp = rbot0[idxbot0]; // rbot1[l+s2o,m+s2p,n]
215 |
216 | // Index offset for gradOutput in following loops:
217 | int op = (p+4) * 9 + (o+4); // index[o,p]
218 | int idxopoffset = (intSample * SIZE_1(gradOutput) + op);
219 |
220 | for (int y = ymin; y <= ymax; y++) {
221 | for (int x = xmin; x <= xmax; x++) {
222 | int idxgradOutput = (idxopoffset * SIZE_2(gradOutput) + y) * SIZE_3(gradOutput) + x; // gradOutput[x,y,o,p]
223 | sum += gradOutput[idxgradOutput] * bot0tmp;
224 | }
225 | }
226 | }
227 | }
228 | }
229 | const int sumelems = SIZE_1(gradSecond);
230 | const int bot1index = ((n * SIZE_2(gradSecond)) + (m-4)) * SIZE_3(gradSecond) + (l-4);
231 | gradSecond[bot1index + intSample*SIZE_1(gradSecond)*SIZE_2(gradSecond)*SIZE_3(gradSecond)] = sum / (float)sumelems;
232 | } }
233 | '''
234 |
235 | def cupy_kernel(strFunction, objVariables):
236 | strKernel = globals()[strFunction]
237 |
238 | while True:
239 | objMatch = re.search('(SIZE_)([0-4])(\()([^\)]*)(\))', strKernel)
240 |
241 | if objMatch is None:
242 | break
243 | # end
244 |
245 | intArg = int(objMatch.group(2))
246 |
247 | strTensor = objMatch.group(4)
248 | intSizes = objVariables[strTensor].size()
249 |
250 | strKernel = strKernel.replace(objMatch.group(), str(intSizes[intArg]))
251 | # end
252 |
253 | while True:
254 | objMatch = re.search('(VALUE_)([0-4])(\()([^\)]+)(\))', strKernel)
255 |
256 | if objMatch is None:
257 | break
258 | # end
259 |
260 | intArgs = int(objMatch.group(2))
261 | strArgs = objMatch.group(4).split(',')
262 |
263 | strTensor = strArgs[0]
264 | intStrides = objVariables[strTensor].stride()
265 | strIndex = [ '((' + strArgs[intArg + 1].replace('{', '(').replace('}', ')').strip() + ')*' + str(intStrides[intArg]) + ')' for intArg in range(intArgs) ]
266 |
267 | strKernel = strKernel.replace(objMatch.group(0), strTensor + '[' + str.join('+', strIndex) + ']')
268 | # end
269 |
270 | return strKernel
271 | # end
272 |
273 | @cupy.memoize(for_each_device=True)
274 | def cupy_launch(strFunction, strKernel):
275 | return cupy.cuda.compile_with_cache(strKernel).get_function(strFunction)
276 | # end
277 |
278 | class _FunctionCorrelation(torch.autograd.Function):
279 | @staticmethod
280 | def forward(self, first, second):
281 | rbot0 = first.new_zeros([ first.shape[0], first.shape[2] + 8, first.shape[3] + 8, first.shape[1] ])
282 | rbot1 = first.new_zeros([ first.shape[0], first.shape[2] + 8, first.shape[3] + 8, first.shape[1] ])
283 |
284 | self.save_for_backward(first, second, rbot0, rbot1)
285 |
286 | assert(first.is_contiguous() == True)
287 | assert(second.is_contiguous() == True)
288 |
289 | output = first.new_zeros([ first.shape[0], 81, first.shape[2], first.shape[3] ])
290 |
291 | if first.is_cuda == True:
292 | n = first.shape[2] * first.shape[3]
293 | cupy_launch('kernel_Correlation_rearrange', cupy_kernel('kernel_Correlation_rearrange', {
294 | 'input': first,
295 | 'output': rbot0
296 | }))(
297 | grid=tuple([ int((n + 16 - 1) / 16), first.shape[1], first.shape[0] ]),
298 | block=tuple([ 16, 1, 1 ]),
299 | args=[ n, first.data_ptr(), rbot0.data_ptr() ]
300 | )
301 |
302 | n = second.shape[2] * second.shape[3]
303 | cupy_launch('kernel_Correlation_rearrange', cupy_kernel('kernel_Correlation_rearrange', {
304 | 'input': second,
305 | 'output': rbot1
306 | }))(
307 | grid=tuple([ int((n + 16 - 1) / 16), second.shape[1], second.shape[0] ]),
308 | block=tuple([ 16, 1, 1 ]),
309 | args=[ n, second.data_ptr(), rbot1.data_ptr() ]
310 | )
311 |
312 | n = output.shape[1] * output.shape[2] * output.shape[3]
313 | cupy_launch('kernel_Correlation_updateOutput', cupy_kernel('kernel_Correlation_updateOutput', {
314 | 'rbot0': rbot0,
315 | 'rbot1': rbot1,
316 | 'top': output
317 | }))(
318 | grid=tuple([ output.shape[3], output.shape[2], output.shape[0] ]),
319 | block=tuple([ 32, 1, 1 ]),
320 | shared_mem=first.shape[1] * 4,
321 | args=[ n, rbot0.data_ptr(), rbot1.data_ptr(), output.data_ptr() ]
322 | )
323 |
324 | elif first.is_cuda == False:
325 | raise NotImplementedError()
326 |
327 | # end
328 |
329 | return output
330 | # end
331 |
332 | @staticmethod
333 | def backward(self, gradOutput):
334 | first, second, rbot0, rbot1 = self.saved_tensors
335 |
336 | assert(gradOutput.is_contiguous() == True)
337 |
338 | gradFirst = first.new_zeros([ first.shape[0], first.shape[1], first.shape[2], first.shape[3] ]) if self.needs_input_grad[0] == True else None
339 | gradSecond = first.new_zeros([ first.shape[0], first.shape[1], first.shape[2], first.shape[3] ]) if self.needs_input_grad[1] == True else None
340 |
341 | if first.is_cuda == True:
342 | if gradFirst is not None:
343 | for intSample in range(first.shape[0]):
344 | n = first.shape[1] * first.shape[2] * first.shape[3]
345 | cupy_launch('kernel_Correlation_updateGradFirst', cupy_kernel('kernel_Correlation_updateGradFirst', {
346 | 'rbot0': rbot0,
347 | 'rbot1': rbot1,
348 | 'gradOutput': gradOutput,
349 | 'gradFirst': gradFirst,
350 | 'gradSecond': None
351 | }))(
352 | grid=tuple([ int((n + 512 - 1) / 512), 1, 1 ]),
353 | block=tuple([ 512, 1, 1 ]),
354 | args=[ n, intSample, rbot0.data_ptr(), rbot1.data_ptr(), gradOutput.data_ptr(), gradFirst.data_ptr(), None ]
355 | )
356 | # end
357 | # end
358 |
359 | if gradSecond is not None:
360 | for intSample in range(first.shape[0]):
361 | n = first.shape[1] * first.shape[2] * first.shape[3]
362 | cupy_launch('kernel_Correlation_updateGradSecond', cupy_kernel('kernel_Correlation_updateGradSecond', {
363 | 'rbot0': rbot0,
364 | 'rbot1': rbot1,
365 | 'gradOutput': gradOutput,
366 | 'gradFirst': None,
367 | 'gradSecond': gradSecond
368 | }))(
369 | grid=tuple([ int((n + 512 - 1) / 512), 1, 1 ]),
370 | block=tuple([ 512, 1, 1 ]),
371 | args=[ n, intSample, rbot0.data_ptr(), rbot1.data_ptr(), gradOutput.data_ptr(), None, gradSecond.data_ptr() ]
372 | )
373 | # end
374 | # end
375 |
376 | elif first.is_cuda == False:
377 | raise NotImplementedError()
378 |
379 | # end
380 |
381 | return gradFirst, gradSecond
382 | # end
383 | # end
384 |
385 | def FunctionCorrelation(tenFirst, tenSecond):
386 | return _FunctionCorrelation.apply(tenFirst, tenSecond)
387 | # end
388 |
389 | class ModuleCorrelation(torch.nn.Module):
390 | def __init__(self):
391 | super(ModuleCorrelation, self).__init__()
392 | # end
393 |
394 | def forward(self, tenFirst, tenSecond):
395 | return _FunctionCorrelation.apply(tenFirst, tenSecond)
396 | # end
397 | # end
--------------------------------------------------------------------------------
/softcode/pwc/dataset.py:
--------------------------------------------------------------------------------
1 | from abc import abstractmethod
2 | from torch.utils.data import Dataset
3 | import imageio
4 | import cv2
5 | import numpy as np
6 | import random
7 | from pathlib import Path
8 | from itertools import islice
9 | import torch
10 | from utils.flow_utils import load_flow
11 | from utils.constv import ConstV
12 |
13 | class StaticRandomCrop(object):
14 | def __init__(self, image_size, crop_size):
15 | self.th, self.tw = crop_size
16 | h, w = image_size
17 | self.h1 = random.randint(0, h - self.th)
18 | self.w1 = random.randint(0, w - self.tw)
19 |
20 | def __call__(self, img):
21 | return img[self.h1:(self.h1 + self.th), self.w1:(self.w1 + self.tw), :]
22 |
23 |
24 | class StaticCenterCrop(object):
25 | def __init__(self, image_size, crop_size):
26 | self.th, self.tw = crop_size
27 | self.h, self.w = image_size
28 |
29 | def __call__(self, img):
30 | return img[(self.h - self.th) // 2:(self.h + self.th) // 2, (self.w - self.tw) // 2:(self.w + self.tw) // 2, :]
31 |
32 |
33 | def window(seq, n=2):
34 | "Returns a sliding window (of width n) over data from the iterable"
35 | " s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... "
36 | it = iter(seq)
37 | result = tuple(islice(it, n))
38 | if len(result) == n:
39 | yield result
40 | for elem in it:
41 | result = result[1:] + (elem,)
42 | yield result
43 |
44 |
45 | class BaseDataset(Dataset):
46 | @abstractmethod
47 | def __init__(self):
48 | pass
49 |
50 | def __len__(self):
51 | return len(self.samples)
52 |
53 | def __getitem__(self, idx):
54 |
55 | img1_path, img2_path, flow_path = self.samples[idx]
56 | img1, img2 = map(imageio.imread, (img1_path, img2_path))
57 |
58 | flow = load_flow(flow_path)
59 |
60 | if self.color == 'gray':
61 | img1 = cv2.cvtColor(img1, cv2.COLOR_RGB2GRAY)[:, :, np.newaxis]
62 | img2 = cv2.cvtColor(img2, cv2.COLOR_RGB2GRAY)[:, :, np.newaxis]
63 |
64 | if self.crop_shape is not None:
65 | # cropper = StaticRandomCrop(img1.shape[:2], self.crop_shape) if self.cropper == 'random' else StaticCenterCrop(img1.shape[:2], self.crop_shape)
66 | # print(cropper)
67 | cropper = StaticRandomCrop(img1.shape[:2], self.crop_shape)
68 | img1 = cropper(img1)
69 | img2 = cropper(img2)
70 | flow = cropper(flow)
71 | if self.resize_shape is not None:
72 | resizer = partial(cv2.resize, dsize=(0, 0), dst=self.resize_shape)
73 | images = list(map(resizer, images))
74 | flow = resizer(flow)
75 | elif self.resize_scale is not None:
76 | resizer = partial(cv2.resize, dsize=(0, 0), fx=self.resize_scale, fy=self.resize_scale)
77 | images = list(map(resizer, images))
78 | flow = resizer(flow)
79 |
80 | # if self.train_or_test == 'test':
81 | # H, W = img1.shape[:2]
82 | # img1, img2 = images
83 | # img1 = np.pad(img1, ((0, (64 - H % 64) if H % 64 else 0), (0, (64 - W % 64) if H % 64 else 0), (0, 0)),
84 | # mode='constant')
85 | # img1 = img1.transpose(2, 0, 1).astype(np.float32) * (1.0 / 255.0)
86 | # img2 = np.pad(img2, ((0, (64 - H % 64) if H % 64 else 0), (0, (64 - W % 64) if H % 64 else 0), (0, 0)),
87 | # mode='constant')
88 | # img2 = img2.transpose(2, 0, 1).astype(np.float32) * (1.0 / 255.0)
89 | # images = [img1, img2]
90 | # 在这里标准化一下
91 | # img_pair = [img1,img2]
92 | # rgb_mean = x.contiguous().view(x.size()[:2] + (-1,)).mean(dim=-1).view(x.size()[:2] + (1, 1, 1,))
93 | # x = (x - rgb_mean) / args.rgb_max
94 | # img1,img2 = self.pair_norm(np.array([img1,img2]))
95 | if ConstV.train_or_test=='train':
96 | img1 = np.ascontiguousarray(img1.transpose(2, 0, 1).astype(np.float32))*(1.0/255.0)
97 | img2 = np.ascontiguousarray(img2.transpose(2, 0, 1).astype(np.float32))*(1.0/255.0)
98 | else:
99 |
100 | img1 = np.ascontiguousarray(img1.transpose(2, 0, 1).astype(np.float32))*(1.0/255.0)
101 | img2 = np.ascontiguousarray(img2.transpose(2, 0, 1).astype(np.float32))*(1.0/255.0)
102 |
103 | # images = np.array(images).transpose(3,0,1,2)
104 | flow = flow.transpose(2, 0, 1)
105 | flow.astype('float32')
106 | img1 = torch.from_numpy(img1.astype(np.float32))
107 | img2 = torch.from_numpy(img2.astype(np.float32))
108 | flow = torch.from_numpy(flow.astype(np.float32))
109 | # images = torch.from_numpy(images.astype(np.float32))
110 | # flow = torch.from_numpy(flow.astype(np.float32))
111 |
112 | return img1, img2, flow
113 | def pair_norm(self,imgls):
114 | R_mean = np.mean(imgls[:,:,:,0])
115 | R_std = np.std(imgls[:,:,:,0])
116 | G_mean = np.mean(imgls[:,:,:,1])
117 | G_std = np.std(imgls[:,:,:,1])
118 | B_mean = np.mean(imgls[:,:,:,2])
119 | B_std = np.std(imgls[:, :, :, 2])
120 | return (imgls[0]-(R_mean,G_mean,B_mean))/(R_std,G_std,B_std),(imgls[1]-(R_mean,G_mean,B_mean))/(R_std,G_std,B_std)
121 | def has_txt(self):
122 |
123 | p = Path(self.dataset_dir) / (self.train_or_test + '.txt')
124 | print('self.dataset_dir :', p)
125 | self.samples = []
126 | with open(p, 'r') as f:
127 | for i in f.readlines():
128 | img1, img2, flow = i.split(',')
129 | flow = flow.strip()
130 | self.samples.append((img1, img2, flow))
131 |
132 | def split(self, samples):
133 | p = Path(self.dataset_dir)
134 | if ConstV.train_or_test=='train':
135 | test_ratio = 0.0
136 | else:
137 | test_ratio = 1.0
138 | random.shuffle(samples)
139 | idx = int(len(samples) * (1 - test_ratio))
140 | train_samples = samples[:idx]
141 | test_samples = samples[idx:]
142 |
143 | with open(p / 'train.txt', 'w') as f: f.writelines((','.join(i) + '\n' for i in train_samples))
144 | with open(p / 'test.txt', 'w') as f: f.writelines((','.join(i) + '\n' for i in test_samples))
145 |
146 | self.samples = train_samples if self.train_or_test == 'train' else test_samples
147 |
148 |
149 | class Sintel(BaseDataset):
150 |
151 | def __init__(self, dataset_dir, train_or_test, mode='final', color='rgb', cropper='random', rgb_mean=True,
152 | crop_shape=None, resize_shape=None, resize_scale=None):
153 | super(Sintel, self).__init__()
154 | self.mode = mode
155 | self.color = color
156 | self.cropper = cropper
157 | self.crop_shape = crop_shape
158 | self.resize_shape = resize_shape
159 | self.resize_scale = resize_scale
160 |
161 | self.dataset_dir = dataset_dir
162 | self.train_or_test = train_or_test
163 | p = Path(dataset_dir) / (train_or_test + '.txt')
164 | # if p.exists():
165 | # print('exist')
166 | # self.has_txt()
167 | # else:
168 | # print('not exist')
169 | self.has_no_txt()
170 |
171 | def has_no_txt(self):
172 | p = Path(self.dataset_dir)
173 | p_img = p / 'training' / self.mode
174 | p_flow = p / 'training/flow'
175 | samples = []
176 |
177 | collections_of_scenes = sorted(map(str, p_img.glob('**/*.png')))
178 | from itertools import groupby
179 | collections = [list(g) for k, g in groupby(collections_of_scenes, lambda x: x.split('\\')[-2])]
180 |
181 | samples = [(*i, i[0].replace(self.mode, 'flow').replace('.png', '.flo')) for collection in collections for i in
182 | window(collection, 2)]
183 |
184 | self.split(samples)
185 |
186 |
187 | if __name__ == '__main__':
188 |
189 | dataset_dir = '/home/zhangyuantong/dataset/Sintel'
190 | train_or_test = 'train'
191 |
192 | sintel_dataset = Sintel(dataset_dir=dataset_dir, train_or_test=train_or_test)
193 | print('len', len(sintel_dataset))
194 | for idx, data in enumerate(sintel_dataset):
195 | # print(len(imgls))
196 | img1, img2, flowls = data
197 | print(img1.shape)
198 | print(flowls.shape)
--------------------------------------------------------------------------------
/softcode/pwc/images/README.md:
--------------------------------------------------------------------------------
1 | The used example originates from the MPI Sintel dataset: http://sintel.is.tue.mpg.de/
--------------------------------------------------------------------------------
/softcode/pwc/images/first.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gangsterless/pytorch-softmax-splatting/6a7ff3b876050ded9957c4e68528b04d49621ad0/softcode/pwc/images/first.png
--------------------------------------------------------------------------------
/softcode/pwc/images/second.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gangsterless/pytorch-softmax-splatting/6a7ff3b876050ded9957c4e68528b04d49621ad0/softcode/pwc/images/second.png
--------------------------------------------------------------------------------
/softcode/pwc/log/1flowpic.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gangsterless/pytorch-softmax-splatting/6a7ff3b876050ded9957c4e68528b04d49621ad0/softcode/pwc/log/1flowpic.png
--------------------------------------------------------------------------------
/softcode/pwc/log/events.out.tfevents.1611136582.DESKTOP-A6T4CD8.18592.5.v2:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gangsterless/pytorch-softmax-splatting/6a7ff3b876050ded9957c4e68528b04d49621ad0/softcode/pwc/log/events.out.tfevents.1611136582.DESKTOP-A6T4CD8.18592.5.v2
--------------------------------------------------------------------------------
/softcode/pwc/log/pic.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gangsterless/pytorch-softmax-splatting/6a7ff3b876050ded9957c4e68528b04d49621ad0/softcode/pwc/log/pic.png
--------------------------------------------------------------------------------
/softcode/pwc/logger.py:
--------------------------------------------------------------------------------
1 | import tensorflow as tf
2 | import numpy as np
3 | import scipy.misc
4 | from io import BytesIO
5 |
6 |
7 | class Logger(object):
8 |
9 | def __init__(self, log_dir):
10 | """Create a summary writer logging to log_dir."""
11 |
12 | self.writer = tf.summary.create_file_writer(log_dir)
13 |
14 | def scalar_summary(self, tag, value, step):
15 | """Log a scalar variable."""
16 | summary = tf.Summary(value=[tf.Summary.Value(tag=tag, simple_value=value)])
17 | self.writer.add_summary(summary, step)
18 |
19 | def image_summary(self, tag, images, step):
20 | """Log a list of images."""
21 |
22 | img_summaries = []
23 | for i, img in enumerate(images):
24 | # Write the image to a string
25 | try:
26 | s = StringIO()
27 | except:
28 | s = BytesIO()
29 | scipy.misc.toimage(img).save('./log/'+str(step)+tag+'pic.png', format="png")
30 |
31 | # Create an Image object
32 | # img_sum = tf.Summary.Image(encoded_image_string=s.getvalue(),
33 | # height=img.shape[0],
34 | # width=img.shape[1])
35 | # # # Create a Summary value
36 | # img_summaries.append(tf.Summary.Value(tag='%s/%d' % (tag, i), image=img_sum))
37 | #
38 | # # Create and write Summary
39 | # summary = tf.Summary(value=img_summaries)
40 | # self.writer.add_summary(summary, step)
41 |
42 | def histo_summary(self, tag, values, step, bins=1000):
43 | """Log a histogram of the tensor of values."""
44 |
45 | # Create a histogram using numpy
46 | counts, bin_edges = np.histogram(values, bins=bins)
47 |
48 | # Fill the fields of the histogram proto
49 | hist = tf.HistogramProto()
50 | hist.min = float(np.min(values))
51 | hist.max = float(np.max(values))
52 | hist.num = int(np.prod(values.shape))
53 | hist.sum = float(np.sum(values))
54 | hist.sum_squares = float(np.sum(values ** 2))
55 |
56 | # Drop the start of the first bin
57 | bin_edges = bin_edges[1:]
58 |
59 | # Add bin edges and counts
60 | for edge in bin_edges:
61 | hist.bucket_limit.append(edge)
62 | for c in counts:
63 | hist.bucket.append(c)
64 |
65 | # Create and write Summary
66 | summary = tf.Summary(value=[tf.Summary.Value(tag=tag, histo=hist)])
67 | self.writer.add_summary(summary, step)
68 | self.writer.flush()
--------------------------------------------------------------------------------
/softcode/pwc/out.flo:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gangsterless/pytorch-softmax-splatting/6a7ff3b876050ded9957c4e68528b04d49621ad0/softcode/pwc/out.flo
--------------------------------------------------------------------------------
/softcode/pwc/pwc_network.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import torch
4 |
5 | import getopt
6 | import math
7 | import numpy
8 | import os
9 | import PIL
10 | import PIL.Image
11 | import sys
12 | import torch.nn.functional as F
13 | from pwc.utils.constv import ConstV
14 | import torch.nn as nn
15 | try:
16 | from .correlation import correlation # the custom cost volume layer
17 | except:
18 | sys.path.insert(0, './correlation'); import correlation # you should consider upgrading python
19 | # end
20 |
21 | ##########################################################
22 |
23 | assert(int(str('').join(torch.__version__.split('.')[0:2])) >= 13) # requires at least pytorch version 1.3.0
24 |
25 | # torch.set_grad_enabled(False) # make sure to not compute gradients for computational performance
26 |
27 | torch.backends.cudnn.enabled = True # make sure to use cudnn for computational performance
28 |
29 | ##########################################################
30 |
31 | arguments_strModel = 'default'
32 | arguments_strFirst = './images/first.png'
33 | arguments_strSecond = './images/second.png'
34 | arguments_strOut = './out.flo'
35 |
36 | for strOption, strArgument in getopt.getopt(sys.argv[1:], '', [ strParameter[2:] + '=' for strParameter in sys.argv[1::2] ])[0]:
37 | if strOption == '--model' and strArgument != '': arguments_strModel = strArgument # which model to use
38 | if strOption == '--first' and strArgument != '': arguments_strFirst = strArgument # path to the first frame
39 | if strOption == '--second' and strArgument != '': arguments_strSecond = strArgument # path to the second frame
40 | if strOption == '--out' and strArgument != '': arguments_strOut = strArgument # path to where the output should be stored
41 | # end
42 |
43 | ##########################################################
44 |
45 | backwarp_tenGrid = {}
46 | backwarp_tenPartial = {}
47 |
48 | def backwarp(tenInput, tenFlow):
49 | if str(tenFlow.shape) not in backwarp_tenGrid:
50 | tenHor = torch.linspace(-1.0 + (1.0 / tenFlow.shape[3]), 1.0 - (1.0 / tenFlow.shape[3]), tenFlow.shape[3]).view(1, 1, 1, -1).expand(-1, -1, tenFlow.shape[2], -1)
51 | tenVer = torch.linspace(-1.0 + (1.0 / tenFlow.shape[2]), 1.0 - (1.0 / tenFlow.shape[2]), tenFlow.shape[2]).view(1, 1, -1, 1).expand(-1, -1, -1, tenFlow.shape[3])
52 |
53 | backwarp_tenGrid[str(tenFlow.shape)] = torch.cat([ tenHor, tenVer ], 1).cuda()
54 | # end
55 |
56 | if str(tenFlow.shape) not in backwarp_tenPartial:
57 | backwarp_tenPartial[str(tenFlow.shape)] = tenFlow.new_ones([ tenFlow.shape[0], 1, tenFlow.shape[2], tenFlow.shape[3] ])
58 | # end
59 |
60 | tenFlow = torch.cat([ tenFlow[:, 0:1, :, :] / ((tenInput.shape[3] - 1.0) / 2.0), tenFlow[:, 1:2, :, :] / ((tenInput.shape[2] - 1.0) / 2.0) ], 1)
61 | tenInput = torch.cat([ tenInput, backwarp_tenPartial[str(tenFlow.shape)] ], 1)
62 |
63 | tenOutput = torch.nn.functional.grid_sample(input=tenInput, grid=(backwarp_tenGrid[str(tenFlow.shape)] + tenFlow).permute(0, 2, 3, 1), mode='bilinear', padding_mode='zeros', align_corners=False)
64 |
65 | tenMask = tenOutput[:, -1:, :, :]; tenMask[tenMask > 0.999] = 1.0; tenMask[tenMask < 1.0] = 0.0
66 |
67 | return tenOutput[:, :-1, :, :] * tenMask
68 | # end
69 |
70 | ##########################################################
71 |
72 | class Network(torch.nn.Module):
73 | def __init__(self):
74 | super(Network, self).__init__()
75 | #
76 |
77 | class Extractor(torch.nn.Module):
78 | def __init__(self):
79 | super(Extractor, self).__init__()
80 |
81 | self.netOne = torch.nn.Sequential(
82 | torch.nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3, stride=2, padding=1),
83 | torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
84 | torch.nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3, stride=1, padding=1),
85 | torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
86 | torch.nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3, stride=1, padding=1),
87 | torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
88 | )
89 |
90 | self.netTwo = torch.nn.Sequential(
91 | torch.nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3, stride=2, padding=1),
92 | torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
93 | torch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1),
94 | torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
95 | torch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1),
96 | torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
97 | )
98 |
99 | self.netThr = torch.nn.Sequential(
100 | torch.nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=2, padding=1),
101 | torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
102 | torch.nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1),
103 | torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
104 | torch.nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1),
105 | torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
106 | )
107 |
108 | self.netFou = torch.nn.Sequential(
109 | torch.nn.Conv2d(in_channels=64, out_channels=96, kernel_size=3, stride=2, padding=1),
110 | torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
111 | torch.nn.Conv2d(in_channels=96, out_channels=96, kernel_size=3, stride=1, padding=1),
112 | torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
113 | torch.nn.Conv2d(in_channels=96, out_channels=96, kernel_size=3, stride=1, padding=1),
114 | torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
115 | )
116 |
117 | self.netFiv = torch.nn.Sequential(
118 | torch.nn.Conv2d(in_channels=96, out_channels=128, kernel_size=3, stride=2, padding=1),
119 | torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
120 | torch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1),
121 | torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
122 | torch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1),
123 | torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
124 | )
125 |
126 | self.netSix = torch.nn.Sequential(
127 | torch.nn.Conv2d(in_channels=128, out_channels=196, kernel_size=3, stride=2, padding=1),
128 | torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
129 | torch.nn.Conv2d(in_channels=196, out_channels=196, kernel_size=3, stride=1, padding=1),
130 | torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
131 | torch.nn.Conv2d(in_channels=196, out_channels=196, kernel_size=3, stride=1, padding=1),
132 | torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
133 | )
134 | # end
135 |
136 | def forward(self, tenInput):
137 | tenOne = self.netOne(tenInput)
138 | tenTwo = self.netTwo(tenOne)
139 | tenThr = self.netThr(tenTwo)
140 | tenFou = self.netFou(tenThr)
141 | tenFiv = self.netFiv(tenFou)
142 | tenSix = self.netSix(tenFiv)
143 |
144 | return [ tenOne, tenTwo, tenThr, tenFou, tenFiv, tenSix ]
145 | # end
146 | # end
147 |
148 | class Decoder(torch.nn.Module):
149 | def __init__(self, intLevel):
150 | super(Decoder, self).__init__()
151 | self.intLevel = intLevel
152 | intPrevious = [ None, None, 81 + 32 + 2 + 2, 81 + 64 + 2 + 2, 81 + 96 + 2 + 2, 81 + 128 + 2 + 2, 81, None ][intLevel + 1]
153 | intCurrent = [ None, None, 81 + 32 + 2 + 2, 81 + 64 + 2 + 2, 81 + 96 + 2 + 2, 81 + 128 + 2 + 2, 81, None ][intLevel + 0]
154 |
155 | if intLevel < 6: self.netUpflow = torch.nn.ConvTranspose2d(in_channels=2, out_channels=2, kernel_size=4, stride=2, padding=1)
156 | if intLevel < 6: self.netUpfeat = torch.nn.ConvTranspose2d(in_channels=intPrevious + 128 + 128 + 96 + 64 + 32, out_channels=2, kernel_size=4, stride=2, padding=1)
157 | if intLevel < 6: self.fltBackwarp = [ None, None, None, 5.0, 2.5, 1.25, 0.625, None ][intLevel + 1]
158 |
159 | self.netOne = torch.nn.Sequential(
160 | torch.nn.Conv2d(in_channels=intCurrent, out_channels=128, kernel_size=3, stride=1, padding=1),
161 | torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
162 | )
163 |
164 | self.netTwo = torch.nn.Sequential(
165 | torch.nn.Conv2d(in_channels=intCurrent + 128, out_channels=128, kernel_size=3, stride=1, padding=1),
166 | torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
167 | )
168 |
169 | self.netThr = torch.nn.Sequential(
170 | torch.nn.Conv2d(in_channels=intCurrent + 128 + 128, out_channels=96, kernel_size=3, stride=1, padding=1),
171 | torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
172 | )
173 |
174 | self.netFou = torch.nn.Sequential(
175 | torch.nn.Conv2d(in_channels=intCurrent + 128 + 128 + 96, out_channels=64, kernel_size=3, stride=1, padding=1),
176 | torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
177 | )
178 |
179 | self.netFiv = torch.nn.Sequential(
180 | torch.nn.Conv2d(in_channels=intCurrent + 128 + 128 + 96 + 64, out_channels=32, kernel_size=3, stride=1, padding=1),
181 | torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
182 | )
183 |
184 | self.netSix = torch.nn.Sequential(
185 | torch.nn.Conv2d(in_channels=intCurrent + 128 + 128 + 96 + 64 + 32, out_channels=2, kernel_size=3, stride=1, padding=1)
186 | )
187 | # end
188 |
189 | def forward(self, tenFirst, tenSecond, objPrevious):
190 | tenFlow = None
191 | tenFeat = None
192 |
193 | if objPrevious is None:
194 | tenFlow = None
195 | tenFeat = None
196 |
197 | tenVolume = torch.nn.functional.leaky_relu(input=correlation.FunctionCorrelation(tenFirst=tenFirst, tenSecond=tenSecond), negative_slope=0.1, inplace=False)
198 |
199 | tenFeat = torch.cat([ tenVolume ], 1)
200 |
201 |
202 | elif objPrevious is not None:
203 | tenFlow = self.netUpflow(objPrevious['tenFlow'])
204 | tenFeat = self.netUpfeat(objPrevious['tenFeat'])
205 |
206 | tenVolume = torch.nn.functional.leaky_relu(input=correlation.FunctionCorrelation(tenFirst=tenFirst, tenSecond=backwarp(tenInput=tenSecond, tenFlow=tenFlow * self.fltBackwarp)), negative_slope=0.1, inplace=False)
207 | #corr 对应 tenVolume tenFirst对应x1 flow 对应tenflow
208 | tenFeat = torch.cat([ tenVolume, tenFirst, tenFlow, tenFeat ], 1)
209 |
210 |
211 | # end
212 | # #如果是最后一层
213 | # if self.intLevel==6:
214 |
215 |
216 | tenFeat = torch.cat([ self.netOne(tenFeat), tenFeat ], 1)
217 | tenFeat = torch.cat([ self.netTwo(tenFeat), tenFeat ], 1)
218 | tenFeat = torch.cat([ self.netThr(tenFeat), tenFeat ], 1)
219 | tenFeat = torch.cat([ self.netFou(tenFeat), tenFeat ], 1)
220 | tenFeat = torch.cat([ self.netFiv(tenFeat), tenFeat ], 1)
221 |
222 | tenFlow = self.netSix(tenFeat)
223 |
224 | return {
225 | 'tenFlow': tenFlow,
226 | 'tenFeat': tenFeat
227 | }
228 | # end
229 | # end
230 |
231 | class Refiner(torch.nn.Module):
232 | def __init__(self,in_ch):
233 | super(Refiner, self).__init__()
234 |
235 | self.netMain = torch.nn.Sequential(
236 | torch.nn.Conv2d(in_channels=in_ch, out_channels=128, kernel_size=3, stride=1, padding=1, dilation=1),
237 | # nn.BatchNorm2d(128),
238 | torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
239 | torch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=2, dilation=2),
240 | torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
241 | torch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=4, dilation=4),
242 | torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
243 | torch.nn.Conv2d(in_channels=128, out_channels=96, kernel_size=3, stride=1, padding=8, dilation=8),
244 | torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
245 | torch.nn.Conv2d(in_channels=96, out_channels=64, kernel_size=3, stride=1, padding=16, dilation=16),
246 | torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
247 | torch.nn.Conv2d(in_channels=64, out_channels=32, kernel_size=3, stride=1, padding=1, dilation=1),
248 | torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
249 | torch.nn.Conv2d(in_channels=32, out_channels=2, kernel_size=3, stride=1, padding=1, dilation=1)
250 | )
251 | # end
252 |
253 | def forward(self, tenInput):
254 | return self.netMain(tenInput)
255 | # end
256 | # end
257 |
258 | # 初始化 context refiner
259 | # self.context_refiners = []
260 | # for l, ch in enumerate(ConstV.lv_chs):
261 | # layer = Refiner(ch).to(ConstV.my_device)
262 | # # self.add_module(f'ContextNetwork(Lv{l})', layer)
263 | # self.context_refiners.append(layer)
264 | self.netExtractor = Extractor()
265 |
266 | self.netTwo = Decoder(2)
267 | self.netThr = Decoder(3)
268 | self.netFou = Decoder(4)
269 | self.netFiv = Decoder(5)
270 | self.netSix = Decoder(6)
271 |
272 | self.netRefiner = Refiner(565)
273 |
274 |
275 | #一定用高斯初始化
276 | for m in self.modules():
277 | if isinstance(m, nn.Conv2d):
278 | if m.bias is not None: nn.init.uniform_(m.bias)
279 | nn.init.xavier_uniform_(m.weight)
280 |
281 | if isinstance(m, nn.ConvTranspose2d):
282 | if m.bias is not None: nn.init.uniform_(m.bias)
283 | nn.init.xavier_uniform_(m.weight)
284 | # print('http://content.sniklaus.com/github/pytorch-pwc/network-' + arguments_strModel + '.pytorch')
285 | #不清楚为啥 不能load 似乎只会起反作用,应该是估计的光流没有起到很好的效果???
286 | #看来输入的光流必须除以255否则不顶用 这根预训练模型绝对有关系
287 | self.load_state_dict({ strKey.replace('module', 'net'): tenWeight for strKey, tenWeight in torch.load('pwc/weights/network-default.pytorch').items()})
288 | # end
289 |
290 | def forward(self, tenFirst, tenSecond):
291 | tenFirst = self.netExtractor(tenFirst)
292 | tenSecond = self.netExtractor(tenSecond)
293 | if ConstV.mutil_l:
294 | objEstimate = self.netSix(tenFirst[-1], tenSecond[-1], None)
295 | # objEstimate['tneFlow'] = [2,2,6,7]
296 |
297 | flow_l1 = objEstimate['tenFlow']
298 |
299 | objEstimate = self.netFiv(tenFirst[-2], tenSecond[-2], objEstimate)
300 | # objEstimate['tneFlow'] = [2,2,12,14] [2,529,6,7]
301 |
302 | flow_l2 = objEstimate['tenFlow']
303 | # flow_l2 = objEstimate['tenFlow'] + self.context_refiners[1](objEstimate['tenFeat'])
304 | objEstimate = self.netFou(tenFirst[-3], tenSecond[-3], objEstimate)
305 |
306 | # objEstimate['tneFlow'] = [2,2,24,28] [2, 661, 12, 14]
307 | flow_l3 = objEstimate['tenFlow']
308 | # flow_l3 = objEstimate['tenFlow'] + self.context_refiners[2](objEstimate['tenFeat'])
309 | objEstimate = self.netThr(tenFirst[-4], tenSecond[-4], objEstimate)
310 |
311 | # objEstimate['tneFlow'] = [2,2,48,56]
312 | flow_l4 = objEstimate['tenFlow']
313 | # flow_l4 = objEstimate['tenFlow'] + self.context_refiners[3](objEstimate['tenFeat'])
314 | objEstimate = self.netTwo(tenFirst[-5], tenSecond[-5], objEstimate)
315 | # shapels.append(objEstimate['tenFeat'].shape[1])
316 | # print(shapels)
317 | flow_l5 = objEstimate['tenFlow'] + self.netRefiner(objEstimate['tenFeat'])
318 | # objEstimate['tneFlow'] = [2,2,96,112]
319 | # 貌似是把最后一层的尺寸强行拉到 原始输入尺寸 即扩大四倍 然后数值也乘4
320 | # if l == args.output_level:
321 | # flow = F.upsample(flow, scale_factor = 2 ** (args.num_levels - args.output_level - 1), mode = 'bilinear') * 2 ** (args.num_levels - args.output_level - 1)
322 | # flows.append(flow)
323 |
324 | # flow_l5 = F.upsample(flow_l5, scale_factor=2 ** (2), mode='bilinear')
325 | if ConstV.integrated:
326 | return flow_l5
327 | if ConstV.train_or_test == 'train':
328 | #后面会× 20的,不用再乘了
329 | flow_l5 = F.upsample(flow_l5, scale_factor=2 ** (2), mode='bilinear')
330 | return [flow_l1, flow_l2, flow_l3, flow_l4, flow_l5]
331 | else:
332 | return flow_l5
333 | else:
334 | # shapels = []
335 | objEstimate = self.netSix(tenFirst[-1], tenSecond[-1], None)
336 | # objEstimate['tneFlow'] = [2,2,6,7]
337 |
338 | objEstimate = self.netFiv(tenFirst[-2], tenSecond[-2], objEstimate)
339 | # objEstimate['tneFlow'] = [2,2,12,14] [2,529,6,7]
340 |
341 | objEstimate = self.netFou(tenFirst[-3], tenSecond[-3], objEstimate)
342 | # shapels.append(objEstimate['tenFeat'].shape[1])
343 |
344 | objEstimate = self.netThr(tenFirst[-4], tenSecond[-4], objEstimate)
345 |
346 | # flow_l4 = objEstimate['tenFlow'] + self.context_refiners[3](objEstimate['tenFeat'])
347 | objEstimate = self.netTwo(tenFirst[-5], tenSecond[-5], objEstimate)
348 |
349 |
350 | # flow_coarse + flow_fine
351 | return objEstimate['tenFlow'] + self.netRefiner(objEstimate['tenFeat'])
352 | # end
353 | # end
354 |
355 | # netNetwork = None
356 | #
357 | # ##########################################################
358 | #
359 | # def estimate(tenFirst, tenSecond):
360 | # global netNetwork
361 | #
362 | # if netNetwork is None:
363 | # netNetwork = Network().cuda().eval()
364 | # # end
365 | #
366 | # assert(tenFirst.shape[1] == tenSecond.shape[1])
367 | # assert(tenFirst.shape[2] == tenSecond.shape[2])
368 | #
369 | # intWidth = tenFirst.shape[2]
370 | # intHeight = tenFirst.shape[1]
371 | #
372 | # assert(intWidth == 1024) # remember that there is no guarantee for correctness, comment this line out if you acknowledge this and want to continue
373 | # assert(intHeight == 436) # remember that there is no guarantee for correctness, comment this line out if you acknowledge this and want to continue
374 | #
375 | # tenPreprocessedFirst = tenFirst.cuda().view(1, 3, intHeight, intWidth)
376 | # tenPreprocessedSecond = tenSecond.cuda().view(1, 3, intHeight, intWidth)
377 | #
378 | # intPreprocessedWidth = int(math.floor(math.ceil(intWidth / 64.0) * 64.0))
379 | # intPreprocessedHeight = int(math.floor(math.ceil(intHeight / 64.0) * 64.0))
380 | #
381 | # tenPreprocessedFirst = torch.nn.functional.interpolate(input=tenPreprocessedFirst, size=(intPreprocessedHeight, intPreprocessedWidth), mode='bilinear', align_corners=False)
382 | # tenPreprocessedSecond = torch.nn.functional.interpolate(input=tenPreprocessedSecond, size=(intPreprocessedHeight, intPreprocessedWidth), mode='bilinear', align_corners=False)
383 | #
384 | # tenFlow = 20.0 * torch.nn.functional.interpolate(input=netNetwork(tenPreprocessedFirst, tenPreprocessedSecond), size=(intHeight, intWidth), mode='bilinear', align_corners=False)
385 | #
386 | # tenFlow[:, 0, :, :] *= float(intWidth) / float(intPreprocessedWidth)
387 | # tenFlow[:, 1, :, :] *= float(intHeight) / float(intPreprocessedHeight)
388 | #
389 | # return tenFlow[0, :, :, :].cpu()
390 | # # end
391 | #
392 | # ##########################################################
393 | #
394 | # if __name__ == '__main__':
395 | # tenFirst = torch.FloatTensor(numpy.ascontiguousarray(numpy.array(PIL.Image.open(arguments_strFirst))[:, :, ::-1].transpose(2, 0, 1).astype(numpy.float32) * (1.0 / 255.0)))
396 | # tenSecond = torch.FloatTensor(numpy.ascontiguousarray(numpy.array(PIL.Image.open(arguments_strSecond))[:, :, ::-1].transpose(2, 0, 1).astype(numpy.float32) * (1.0 / 255.0)))
397 | # #(3, 436, 1024)
398 | # tenOutput = estimate(tenFirst, tenSecond)
399 | #
400 | # objOutput = open(arguments_strOut, 'wb')
401 | #
402 | # numpy.array([ 80, 73, 69, 72 ], numpy.uint8).tofile(objOutput)
403 | # numpy.array([ tenOutput.shape[2], tenOutput.shape[1] ], numpy.int32).tofile(objOutput)
404 | # numpy.array(tenOutput.detach().numpy().transpose(1, 2, 0), numpy.float32).tofile(objOutput)
405 | #
406 | # objOutput.close()
407 | # # end
--------------------------------------------------------------------------------
/softcode/pwc/requirements.txt:
--------------------------------------------------------------------------------
1 | cupy>=5.0.0
2 | numpy>=1.15.0
3 | Pillow>=5.0.0
4 | torch>=1.6.0
--------------------------------------------------------------------------------
/softcode/pwc/train.py:
--------------------------------------------------------------------------------
1 | from run import Network
2 | from torch.autograd import Variable
3 | from torch.utils.data import DataLoader
4 | from dataset import Sintel
5 | import torch
6 | import time
7 | import math
8 | from torchvision import transforms
9 | from utils.constv import ConstV
10 | from utils.losses import MultiScale, robust_training_loss, L1Loss
11 | import numpy as np
12 | import torch.nn.functional as F
13 | from utils.flow_utils import (vis_flow, save_flow)
14 | from logger import Logger
15 | import matplotlib.pyplot as plt
16 | from utils.losses import EPE
17 | from pwc.utils.flow_utils import show_compare
18 | model = None
19 | #
20 | # 以下都是muti_scale
21 | # 1. img 不除以255 从头开始:::
22 | # loss -> 0.1279, 0.1260, 0.1271 降不下去了!!! epe 16.3左右
23 | #这个loss跟epe降不下来也属于正常 一方面我得训练代码估计不太对 另一方面主要是因为 没有在flychair上面训练
24 |
25 | #2 img除以255 从头开始 0.1499->0.1337->0.1313->0.1291->0.1276->0.1246->1270 不降了
26 | # 作者说必须要用set_device 指定设备
27 |
28 | #3 用了random crop 1,2都是center crop 0.1333->0.1302->0.1292->1273->1277
29 | # You are correct, it should be set_device instead of just device. Thank you for letting me know! No need to issue a pull request,
30 | # I just updated it and removed that line altogether. It is usually better to set CUDA_VISIBLE_DEVICES
31 | # and I only had this line to avoid issues with multi-GPU systems.
32 | # 4 使用预训练模型 loss 0.0812->0.0740->0.0722->0.0741 6.3左右的epe 1
33 |
34 |
35 | #以下是 一个scale
36 | # 使用预训练模型 loss 8.8289 epe 13.27 明显不行
37 | #不使用预训练模型 0.1470 0.1343 。。。。。 最好的 1296 epe 16.6 看来还是muti比较牛逼
38 |
39 | def train():
40 | def estimate(tenFirst, tenSecond):
41 |
42 | # if model is None:
43 | # model = Network().cuda().train()
44 | intWidth = tenFirst.shape[3]
45 | intHeight = tenFirst.shape[2]
46 | tenPreprocessedFirst = tenFirst.cuda().view(-1, 3, intHeight, intWidth)
47 | tenPreprocessedSecond = tenSecond.cuda().view(-1, 3, intHeight, intWidth)
48 | intPreprocessedWidth = int(math.floor(math.ceil(intWidth / 64.0) * 64.0))
49 | intPreprocessedHeight = int(math.floor(math.ceil(intHeight / 64.0) * 64.0))
50 |
51 | tenPreprocessedFirst = torch.nn.functional.interpolate(input=tenPreprocessedFirst,
52 | size=(intPreprocessedHeight, intPreprocessedWidth),
53 | mode='bilinear', align_corners=False)
54 | tenPreprocessedSecond = torch.nn.functional.interpolate(input=tenPreprocessedSecond,
55 | size=(intPreprocessedHeight, intPreprocessedWidth),
56 | mode='bilinear', align_corners=False)
57 | flow_out_ls = model(tenPreprocessedFirst, tenPreprocessedSecond)
58 | if ConstV.mutil_l:
59 | return flow_out_ls
60 |
61 | else:
62 | tenFlow = 20.0 * torch.nn.functional.interpolate(input=flow_out_ls, size=(intHeight, intWidth),
63 | mode='bilinear',
64 | align_corners=False)
65 | #
66 | tenFlow[:, 0, :, :] *= float(intWidth) / float(intPreprocessedWidth)
67 | tenFlow[:, 1, :, :] *= float(intHeight) / float(intPreprocessedHeight)
68 | return tenFlow
69 | # global model
70 | crop_shape = [384, 448]
71 | sintel_dataset = Sintel(dataset_dir=ConstV.dataset_dir, train_or_test=ConstV.train_or_test, crop_shape=crop_shape)
72 | model = Network().cuda().train()
73 | train_loader = DataLoader(sintel_dataset,
74 | batch_size=ConstV.batch_size,
75 | shuffle=True,
76 | num_workers=ConstV.num_workers,
77 | pin_memory=True)
78 | forward_time = 0
79 | backward_time = 0
80 | optimizer = torch.optim.Adam(params=model.parameters(), lr=ConstV.lr, weight_decay=ConstV.weight_decay)
81 |
82 | total_loss_levels = [0] * ConstV.num_levels
83 | total_epe_levels = [0] * ConstV.num_levels
84 | # 金字塔L1 loss
85 | # loss = robust_training_loss(args, flows, flow_gt_pyramid)
86 | if ConstV.mutil_l:
87 | criteration = MultiScale()
88 | else:
89 | criteration = L1Loss()
90 |
91 | # logger = Logger('log')
92 | for step in range(1, ConstV.total_step + 1):
93 | total_loss = 0
94 | total_epe = 0
95 | for ix, data in enumerate(train_loader):
96 | data = [each.to(ConstV.my_device) for each in data]
97 | img1, img2, flow_gt = data
98 |
99 | t_forward = time.time()
100 | out_flow = estimate(img1, img2)
101 | if ConstV.mutil_l:
102 | forward_time += time.time() - t_forward
103 | # print(forward_time)
104 | # loss, epe, loss_levels, epe_levels = criteration(out_flow, flow_gt)
105 | loss, epe, loss_levels, epe_levels = criteration(out_flow, flow_gt)
106 | total_loss += loss
107 | total_epe+=epe
108 | for l, (loss_, epe_) in enumerate(zip(loss_levels, epe_levels)):
109 | total_loss_levels[l] += loss_.item()
110 | total_epe_levels[l] += epe_.item()
111 | t_backward = time.time()
112 | optimizer.zero_grad()
113 |
114 | loss.backward()
115 | optimizer.step()
116 | backward_time += time.time() - t_backward
117 | print('step,,' + str(step) + ' data: ' + str(ix) + '\\' + str(len(train_loader)) + ' loss :' + str(
118 | loss.item()))
119 | print('epe,,' + str(epe.item()))
120 | else:
121 |
122 | # print(img1.shape)
123 | # print(out_flow.shape)
124 | forward_time += time.time() - t_forward
125 | # print(forward_time)
126 | # loss, epe, loss_levels, epe_levels = criteration(out_flow, flow_gt)
127 | lossvalue, epevalue = criteration(out_flow, flow_gt)
128 | total_loss += lossvalue
129 | total_epe+=epevalue
130 | # total_loss += loss.item()
131 | # total_epe += epe.item()
132 | # for l, (loss_, epe_) in enumerate(zip(loss_levels, epe_levels)):
133 | # total_loss_levels[l] += loss_.item()
134 | # total_epe_levels[l] += epe_.item()
135 |
136 | t_backward = time.time()
137 | optimizer.zero_grad()
138 | # loss.backward()
139 | lossvalue.backward()
140 | optimizer.step()
141 | backward_time += time.time() - t_backward
142 | print('step,,,' + str(step) + ' ' + str(ix) + '\\ loss ' + str(len(train_loader)))
143 | print('loss value :', lossvalue)
144 | print('epe :', epevalue)
145 | # if step % ConstV.summary_interval == 0:
146 | # print('step:::',step)
147 | # # Scalar Summaries
148 | # # ============================================================
149 | # print('lr', optimizer.param_groups[0]['lr'], step)
150 | # print('loss', total_loss / step, step)
151 | # print('EPE', total_epe / step, step)
152 | #
153 | # for l, (loss_, epe_) in enumerate(zip(loss_levels, epe_levels)):
154 | # print(f'loss_lv{l}', total_loss_levels[l] / step, step)
155 | # print(f'EPE_lv{l}', total_epe_levels[l] / step, step)
156 | # # ============================================================
157 | # B = out_flow[0].size(0)
158 | # vis_batch = []
159 | # for b in range(B):
160 | # batch = [np.array(
161 | # F.upsample(out_flow[l][b].unsqueeze(0), scale_factor=2 ** ((len(out_flow) - l + 1))).cpu().detach().squeeze(
162 | # 0)).transpose(1, 2, 0) for l in range(len(out_flow) - 1)]
163 | # # for i in batch:
164 | # # print(i.shape)
165 | # # print(flows[-1][b].detach().cpu().numpy().transpose(1,2,0))
166 | # # print(flow_gt[b].detach().cpu().numpy().transpose(1,2,0).shape)
167 | # vis = batch + [out_flow[-1][b].detach().cpu().numpy().transpose(1, 2, 0),
168 | # flow_gt[b].detach().cpu().numpy().transpose(1, 2, 0)]
169 | # vis = np.concatenate(list(map(vis_flow, vis)), axis=1)
170 | # vis_batch.append(vis.transpose(2, 0, 1))
171 | # logger.image_summary(f'flow', vis_batch, step)
172 | print('epoch ' + str(step) + 'avg loss :' + str(total_loss / len(train_loader))+ 'avg epe :' + str(total_epe / len(train_loader)))
173 | def test():
174 | model_path = './weights/network-default.pytorch'
175 | num_workers = 0
176 | batch_size = 4
177 | print('load model...')
178 | model = Network().cuda().eval()
179 | model.load_state_dict({ strKey.replace('module', 'net'): tenWeight for strKey, tenWeight in torch.load(model_path).items()})
180 |
181 | print('build eval dataset...')
182 |
183 | test_dataset =Sintel(dataset_dir=ConstV.dataset_dir, train_or_test='test')
184 | test_loader = DataLoader(test_dataset,
185 | batch_size=1,
186 | shuffle=True,
187 | num_workers=num_workers,
188 | pin_memory=True)
189 |
190 | total_batches = len(test_loader)
191 |
192 | # logs
193 | # ============================================================
194 |
195 | total_epe = 0
196 | print(len(test_loader))
197 | for batch_idx, (img1,img2 ,flow_gt) in enumerate(test_loader):
198 | # Forward Pass
199 | # ============================================================
200 | # t_start = time.time()
201 | # data, target = [d.to(args.device) for d in data], [t.to(args.device) for t in target]
202 |
203 | with torch.no_grad():
204 | img1 = img1.to(ConstV.my_device)
205 | img2 = img2.to(ConstV.my_device)
206 | flow_gt = flow_gt.to(ConstV.my_device)
207 | intWidth = img1.shape[3]
208 | intHeight = img2.shape[2]
209 | tenPreprocessedFirst = img1.view(-1, 3, intHeight, intWidth)
210 | tenPreprocessedSecond = img2.view(-1, 3, intHeight, intWidth)
211 | intPreprocessedWidth = int(math.floor(math.ceil(intWidth / 64.0) * 64.0))
212 | intPreprocessedHeight = int(math.floor(math.ceil(intHeight / 64.0) * 64.0))
213 |
214 | tenPreprocessedFirst = torch.nn.functional.interpolate(input=tenPreprocessedFirst,
215 | size=(intPreprocessedHeight, intPreprocessedWidth),
216 | mode='bilinear', align_corners=False)
217 | tenPreprocessedSecond = torch.nn.functional.interpolate(input=tenPreprocessedSecond,
218 | size=(intPreprocessedHeight, intPreprocessedWidth),
219 | mode='bilinear', align_corners=False)
220 | flow_out = model(tenPreprocessedFirst,tenPreprocessedSecond)
221 |
222 | #要把形状改的跟gt一样
223 | flow_out = torch.nn.functional.interpolate(input=flow_out,
224 | size=(intHeight, intWidth),
225 | mode='bilinear', align_corners=False)
226 | show_compare(flow_out.cpu().numpy().squeeze().transpose(1,2,0),flow_gt.cpu().numpy().squeeze().transpose(1,2,0))
227 |
228 |
229 | epe = EPE(flow_out, flow_gt)
230 | total_epe+=epe
231 | print(f'[{batch_idx}/{total_batches}] Time: {batch_idx:.2f}s') # EPE:{total_epe / batch_idx}')
232 | print('avg epe :',total_epe/batch_idx)
233 | # time_logs.append(time.time() - t_start)
234 |
235 | # Compute EPE
236 |
237 | if __name__ == '__main__':
238 | if ConstV.train_or_test=='train':
239 | train()
240 | else:
241 | test()
--------------------------------------------------------------------------------
/softcode/pwc/utils/__pycache__/constv.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gangsterless/pytorch-softmax-splatting/6a7ff3b876050ded9957c4e68528b04d49621ad0/softcode/pwc/utils/__pycache__/constv.cpython-36.pyc
--------------------------------------------------------------------------------
/softcode/pwc/utils/__pycache__/flow_utils.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gangsterless/pytorch-softmax-splatting/6a7ff3b876050ded9957c4e68528b04d49621ad0/softcode/pwc/utils/__pycache__/flow_utils.cpython-36.pyc
--------------------------------------------------------------------------------
/softcode/pwc/utils/__pycache__/losses.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gangsterless/pytorch-softmax-splatting/6a7ff3b876050ded9957c4e68528b04d49621ad0/softcode/pwc/utils/__pycache__/losses.cpython-36.pyc
--------------------------------------------------------------------------------
/softcode/pwc/utils/constv.py:
--------------------------------------------------------------------------------
1 | import torch
2 | class ConstV:
3 | mutil_l = True
4 | #是否拿出来嵌入整个softsplat的框架,如果嵌入整个框架最后返回的flow的分辨率是不一样的
5 | integrated = True
6 | epsilon = 0.02
7 | q = 0.4
8 | weightsls = [0.32,0.08,0.02,0.01,0.005]
9 | dataset_dir = 'D:/dataset/Sintel'
10 | train_or_test = 'train'
11 | num_workers = 0
12 | batch_size = 4
13 | lr = 1e-4
14 | weight_decay = 4e-4
15 | total_step = 100
16 | my_device = torch.device('cuda')
17 | num_levels = 7
18 | output_level = 4
19 | summary_interval = 2
20 | lv_chs =[529, 661, 629, 597, 565]
21 |
--------------------------------------------------------------------------------
/softcode/pwc/utils/flow_utils.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import matplotlib.pyplot as plt
3 | __all__ = ['load_flow', 'save_flow', 'vis_flow']
4 | def show_compare(flow_out,flow_gt):
5 | flow_out_img = vis_flow(flow_out)
6 | flow_gt_img = vis_flow(flow_gt)
7 | _, (ax1, ax) = plt.subplots(1, 2, figsize=(6, 6))
8 | auto_show = True
9 |
10 |
11 | height, width = flow_gt_img.shape[:2]
12 | ax.set_ylim(height + 10, -10)
13 | ax.set_xlim(-10, width + 10)
14 | ax.axis('off')
15 | ax.set_title('flow_gt_img')
16 |
17 | ax1.set_ylim(height + 10, -10)
18 | ax1.set_xlim(-10, width + 10)
19 | ax1.axis('off')
20 | ax1.set_title("flow_out_img")
21 |
22 | ax.imshow(flow_gt_img.astype(np.uint8))
23 | ax1.imshow(flow_out_img.astype(np.uint8))
24 |
25 | plt.show()
26 |
27 | def load_flow(path):
28 | with open(path, 'rb') as f:
29 | magic = float(np.fromfile(f, np.float32, count = 1)[0])
30 | if magic == 202021.25:
31 | w, h = np.fromfile(f, np.int32, count = 1)[0], np.fromfile(f, np.int32, count = 1)[0]
32 | data = np.fromfile(f, np.float32, count = h*w*2)
33 | data.resize((h, w, 2))
34 | return data
35 | return None
36 |
37 | def save_flow(path, flow):
38 | magic = np.array([202021.25], np.float32)
39 | h, w = flow.shape[:2]
40 | h, w = np.array([h], np.int32), np.array([w], np.int32)
41 |
42 | with open(path, 'wb') as f:
43 | magic.tofile(f); w.tofile(f); h.tofile(f); flow.tofile(f)
44 |
45 | import cv2
46 | import sys
47 | import numpy as np
48 | import argparse
49 |
50 | def makeColorwheel():
51 |
52 | # color encoding scheme
53 |
54 | # adapted from the color circle idea described at
55 | # http://members.shaw.ca/quadibloc/other/colint.htm
56 |
57 | RY = 15
58 | YG = 6
59 | GC = 4
60 | CB = 11
61 | BM = 13
62 | MR = 6
63 |
64 | ncols = RY + YG + GC + CB + BM + MR
65 |
66 | colorwheel = np.zeros([ncols, 3]) # r g b
67 |
68 | col = 0
69 | #RY
70 | colorwheel[0:RY, 0] = 255
71 | colorwheel[0:RY, 1] = np.floor(255*np.arange(0, RY, 1)/RY)
72 | col += RY
73 |
74 | #YG
75 | colorwheel[col:YG+col, 0]= 255 - np.floor(255*np.arange(0, YG, 1)/YG)
76 | colorwheel[col:YG+col, 1] = 255;
77 | col += YG;
78 |
79 | #GC
80 | colorwheel[col:GC+col, 1]= 255
81 | colorwheel[col:GC+col, 2] = np.floor(255*np.arange(0, GC, 1)/GC)
82 | col += GC;
83 |
84 | #CB
85 | colorwheel[col:CB+col, 1]= 255 - np.floor(255*np.arange(0, CB, 1)/CB)
86 | colorwheel[col:CB+col, 2] = 255
87 | col += CB;
88 |
89 | #BM
90 | colorwheel[col:BM+col, 2]= 255
91 | colorwheel[col:BM+col, 0] = np.floor(255*np.arange(0, BM, 1)/BM)
92 | col += BM;
93 |
94 | #MR
95 | colorwheel[col:MR+col, 2]= 255 - np.floor(255*np.arange(0, MR, 1)/MR)
96 | colorwheel[col:MR+col, 0] = 255
97 | return colorwheel
98 |
99 | def computeColor(u, v):
100 |
101 | colorwheel = makeColorwheel();
102 | nan_u = np.isnan(u)
103 | nan_v = np.isnan(v)
104 | nan_u = np.where(nan_u)
105 | nan_v = np.where(nan_v)
106 |
107 | u[nan_u] = 0
108 | u[nan_v] = 0
109 | v[nan_u] = 0
110 | v[nan_v] = 0
111 |
112 | ncols = colorwheel.shape[0]
113 | radius = np.sqrt(u**2 + v**2)
114 | a = np.arctan2(-v, -u) / np.pi
115 | fk = (a+1) /2 * (ncols-1) # -1~1 maped to 1~ncols
116 | k0 = fk.astype(np.uint8) # 1, 2, ..., ncols
117 | k1 = k0+1
118 | k1[k1 == ncols] = 0
119 | f = fk - k0
120 |
121 | img = np.empty([k1.shape[0], k1.shape[1],3])
122 | ncolors = colorwheel.shape[1]
123 | for i in range(ncolors):
124 | tmp = colorwheel[:,i]
125 | col0 = tmp[k0]/255
126 | col1 = tmp[k1]/255
127 | col = (1-f)*col0 + f*col1
128 | idx = radius <= 1
129 | col[idx] = 1 - radius[idx]*(1-col[idx]) # increase saturation with radius
130 | col[~idx] *= 0.75 # out of range
131 | img[:,:,2-i] = np.floor(255*col).astype(np.uint8)
132 |
133 | return img.astype(np.uint8)
134 |
135 |
136 | def vis_flow(flow):
137 | eps = sys.float_info.epsilon
138 | UNKNOWN_FLOW_THRESH = 1e9
139 | UNKNOWN_FLOW = 1e10
140 |
141 | u = flow[:,:,0]
142 | v = flow[:,:,1]
143 |
144 | maxu = -999
145 | maxv = -999
146 |
147 | minu = 999
148 | minv = 999
149 |
150 | maxrad = -1
151 | #fix unknown flow
152 | greater_u = np.where(u > UNKNOWN_FLOW_THRESH)
153 | greater_v = np.where(v > UNKNOWN_FLOW_THRESH)
154 | u[greater_u] = 0
155 | u[greater_v] = 0
156 | v[greater_u] = 0
157 | v[greater_v] = 0
158 |
159 | maxu = max([maxu, np.amax(u)])
160 | minu = min([minu, np.amin(u)])
161 |
162 | maxv = max([maxv, np.amax(v)])
163 | minv = min([minv, np.amin(v)])
164 | rad = np.sqrt(np.multiply(u,u)+np.multiply(v,v))
165 | maxrad = max([maxrad, np.amax(rad)])
166 | # print('max flow: %.4f flow range: u = %.3f .. %.3f; v = %.3f .. %.3f\n' % (maxrad, minu, maxu, minv, maxv))
167 |
168 | u = u/(maxrad+eps)
169 | v = v/(maxrad+eps)
170 | img = computeColor(u, v)
171 | return img[:,:,[2,1,0]]
172 |
173 | # if __name__ == '__main__':
174 | # parser = argparse.ArgumentParser()
175 | # parser.add_argument(
176 | # '--flowfile',
177 | # type=str,
178 | # default='colorTest.flo',
179 | # help='Flow file'
180 | # )
181 | # parser.add_argument(
182 | # '--write',
183 | # type=bool,
184 | # default=False,
185 | # help='write flow as png'
186 | # )
187 | # file = parser.parse_args().flowfile
188 | # flow = load_flow(file)
189 | # img = computeImg(flow)
190 | # cv2.imshow(file, img)
191 | # k = cv2.waitKey()
192 | # if parser.parse_args().write:
193 | # cv2.imwrite(file[:-4]+'.png', img)
194 |
195 | if __name__ == '__main__':
196 | import matplotlib.pyplot as plt
197 |
198 | flow = load_flow('13382_flow.flo')
199 | flow = load_flow('datasets/Sintel/training/flow/alley_1/frame_0001.flo')
200 | img = vis_flow(flow)
201 | import imageio
202 | imageio.imsave('test.png', img)
203 | import cv2
204 | cv2.imshow('', img[:,:,:])
205 | cv2.waitKey()
--------------------------------------------------------------------------------
/softcode/pwc/utils/losses.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 | import torch.nn.functional as F
4 | from .constv import ConstV
5 |
6 | #const value
7 |
8 |
9 |
10 |
11 | def L1loss(x, y): return (x - y).abs().mean()
12 | def L2loss(x, y): return torch.norm(x - y, p = 2, dim = 1).mean()
13 |
14 | def training_loss( flow_pyramid, flow_gt_pyramid):
15 | return sum(w * L2loss(flow, gt) for w, flow, gt in zip(ConstV.weights, flow_pyramid, flow_gt_pyramid))
16 |
17 | def robust_training_loss( flow_pyramid, flow_gt_pyramid):
18 | return sum((w * L1loss(flow, gt) + ConstV.epsilon) ** ConstV.q for w, flow, gt in zip(ConstV.weightsls, flow_pyramid, flow_gt_pyramid))
19 |
20 |
21 |
22 | def EPE(input_flow, target_flow):
23 | return torch.norm(target_flow-input_flow,p=2,dim=1).mean()
24 |
25 |
26 | class L1(nn.Module):
27 | def __init__(self):
28 | super(L1, self).__init__()
29 | def forward(self, output, target):
30 | lossvalue = torch.abs(output - target).mean()
31 | return lossvalue
32 |
33 |
34 | class L2(nn.Module):
35 | def __init__(self):
36 | super(L2, self).__init__()
37 | def forward(self, output, target):
38 | lossvalue = torch.norm(output-target,p=2,dim=1).mean()
39 | return lossvalue
40 |
41 |
42 | class L1Loss(nn.Module):
43 | def __init__(self):
44 | super(L1Loss, self).__init__()
45 | self.loss = L1()
46 | self.loss_labels = ['L1', 'EPE']
47 |
48 | def forward(self, outputs, target):
49 | lossvalue = self.loss(outputs[-1], target)
50 | epevalue = EPE(outputs[-1], target)
51 | return [lossvalue, epevalue]
52 |
53 |
54 | class L2Loss(nn.Module):
55 | def __init__(self):
56 | super(L2Loss, self).__init__()
57 | self.loss = L2()
58 | self.loss_labels = ['L2', 'EPE']
59 |
60 | def forward(self, outputs, target):
61 | lossvalue = self.loss(outputs[-1], target)
62 | epevalue = EPE(output, target)
63 | return [lossvalue, epevalue]
64 |
65 |
66 | class MultiScale(nn.Module):
67 | def __init__(self, startScale = 5, numScales = 6, l_weight= 0.32, norm= 'L1'):
68 | super(MultiScale,self).__init__()
69 |
70 | self.startScale = startScale
71 | self.numScales = numScales
72 | self.loss_weights = torch.FloatTensor([(l_weight / 2 ** scale) for scale in range(self.numScales)]).to(ConstV.my_device)
73 |
74 | self.l_type = norm
75 | self.div_flow = 0.05
76 | assert(len(self.loss_weights) == self.numScales)
77 |
78 | if self.l_type == 'L1': self.loss = L1()
79 | else: self.loss = L2()
80 |
81 | self.multiScales = [nn.AvgPool2d(2**l, 2**l) for l in range(ConstV.num_levels)][::-1][:ConstV.output_level]
82 | self.loss_labels = ['MultiScale-'+self.l_type, 'EPE'],
83 |
84 | def forward(self, outputs, target):
85 |
86 | # if flow is normalized, every output is multiplied by its size
87 | # correspondingly, groundtruth should be scaled at each level
88 | targets = [avg_pool(target) / 2 ** (ConstV.num_levels - l -1 ) for l, avg_pool in enumerate(self.multiScales)] + [target]
89 | loss, epe = 0, 0
90 | loss_levels, epe_levels = [], []
91 | for w, o, t in zip(ConstV.weightsls, outputs, targets):
92 | # print(f'flow值域: ({o.min()}, {o.max()})')
93 | # print(f'gt值域: ({t.min()}, {t.max()})')
94 | # print(f'EPE:', EPE(o, t))
95 | loss += w * self.loss(o, t)
96 | epe += EPE(o, t)
97 | loss_levels.append(self.loss(o, t))
98 | epe_levels.append(EPE(o, t))
99 | return [loss, epe, loss_levels, epe_levels]
100 |
101 |
--------------------------------------------------------------------------------
/softcode/pwc/utils/test.py:
--------------------------------------------------------------------------------
1 | # import torch
2 | # # self.load_state_dict({ strKey.replace('module', 'net'): tenWeight for strKey, tenWeight in torch.load('weights/network-default.pytorch').items()})
3 | # for each in torch.load('../weights/network-default.pytorch'):
4 | # print(each)
5 | # print(50*'-')
6 | # for strKey, tenWeight in torch.load('../weights/network-default.pytorch').items():
7 | # print(strKey)
8 | # # print(tenWeight)
9 | # new_state_dict = { strKey.replace('module', 'net'): tenWeight for strKey, tenWeight in torch.load('../weights/network-default.pytorch').items()}
10 | # print(50*'-')
11 | # for k,v in new_state_dict.items():
12 | # print(k)
13 | #
14 | import numpy as np
15 | dd = np.cumsum([128,128,96,64,32])
16 | for each in dd:
17 | print(each)
--------------------------------------------------------------------------------
/softcode/readme.md:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/softcode/run_a_pair.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import torch
3 | import cv2
4 | from main_net import Main_net
5 | tenFirst = torch.FloatTensor(np.ascontiguousarray(cv2.imread(filename='./pair_img/im1.png', flags=-1).transpose(2, 0, 1)[None, :, :, :].astype(np.float32) * (1.0 / 255.0))).cuda()
6 |
7 | tenSecond = torch.FloatTensor(np.ascontiguousarray(cv2.imread(filename='./pair_img/im3.png', flags=-1).transpose(2, 0, 1)[None, :, :, :].astype(np.float32) * (1.0 / 255.0))).cuda()
8 |
9 | gt = cv2.imread('./pair_img/im2.png')
10 | H = 256
11 | W = 448
12 | shape = [1,3,H,W]
13 | model = Main_net(shape).cuda().eval()
14 | with torch.no_grad():
15 | net_state = { strKey.replace('module.', ''): tenWeight for strKey, tenWeight in torch.load('weights/model_weight_48.pth')['net'].items()}
16 | model.load_state_dict(net_state)
17 |
18 | img_out = model(tenFirst,tenSecond)
19 | img_out = img_out.squeeze().detach().cpu().numpy().transpose(1,2,0)
20 | cv2.imshow('out',img_out)
21 | cv2.imshow('ground truth',gt)
22 | while cv2.waitKey(0) & 0xFF == ord('q'):
23 | break
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/softcode/softsplatting/README.md:
--------------------------------------------------------------------------------
1 | # softmax-splatting
2 | This is a reference implementation of the softmax splatting operator, which has been proposed in Softmax Splatting for Video Frame Interpolation [1], using PyTorch. Softmax splatting is a well-motivated approach for differentiable forward warping. It uses a translational invariant importance metric to disambiguate cases where multiple source pixels map to the same target pixel. Should you be making use of our work, please cite our paper [1].
3 |
4 |
5 |
6 | ## setup
7 | The softmax splatting is implemented in CUDA using CuPy, which is why CuPy is a required dependency. It can be installed using `pip install cupy` or alternatively using one of the provided binary packages as outlined in the CuPy repository.
8 |
9 | The provided example script is using OpenCV to load and display images, as well as to read the provided optical flow file. An easy way to install OpenCV for Python is using the `pip install opencv-contrib-python` package.
10 |
11 | ## usage
12 | We provide a small script to replicate the third figure of our paper [1]. You can simply run `python run.py` to obtain the comparison between summation splatting, average splatting, linear splatting, and softmax splatting. Please see this exemplatory `run.py` for additional information on how to use the provided reference implementation of our proposed softmax splatting operator for differentiable forward warping.
13 |
14 | ## xiph
15 | In our paper, we propose to use 4K video clips from Xiph to evaluate video frame interpolation on high-resolution footage. Please see the supplementary `benchmark.py` on how to reproduce the shown metrics.
16 |
17 | ## video
18 |
19 |
20 | ## license
21 | The provided implementation is strictly for academic purposes only. Should you be interested in using our technology for any commercial use, please feel free to contact us.
22 |
23 | ## references
24 | ```
25 | [1] @inproceedings{Niklaus_CVPR_2020,
26 | author = {Simon Niklaus and Feng Liu},
27 | title = {Softmax Splatting for Video Frame Interpolation},
28 | booktitle = {IEEE Conference on Computer Vision and Pattern Recognition},
29 | year = {2020}
30 | }
31 | ```
32 |
33 | ## acknowledgment
34 | The video above uses materials under a Creative Common license as detailed at the end.
--------------------------------------------------------------------------------
/softcode/softsplatting/__init__.py:
--------------------------------------------------------------------------------
1 | # @Time : 2021/1/23 9:27
2 |
3 | # @Author : xx
4 |
5 | # @File : __init__.py.py
6 |
7 | # @Software: PyCharm
8 |
9 | # @description=''
--------------------------------------------------------------------------------
/softcode/softsplatting/benchmark.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import cv2
4 | import glob
5 | import numpy
6 | import os
7 | import skimage
8 | import skimage.metrics
9 | import sys
10 | import torch
11 |
12 | ##########################################################
13 |
14 | print('this benchmark script can be used to compute the Xiph metrics from our paper')
15 | print('please note that it uses the SepConv method for doing the actual interpolation')
16 | print('be aware that the script first downloads about 12 gigabytes of data from Xiph')
17 | print('do you want to continue with the execution of this script? [y/n]')
18 |
19 | if input().lower() != 'y':
20 | sys.exit(0)
21 | # end
22 |
23 | ##########################################################
24 |
25 | if os.path.exists('./netflix') == False:
26 | os.makedirs('./netflix')
27 | # end
28 |
29 | if len(glob.glob('./netflix/BoxingPractice-*.png')) != 100:
30 | os.system('ffmpeg -i https://media.xiph.org/video/derf/ElFuente/Netflix_BoxingPractice_4096x2160_60fps_10bit_420.y4m -pix_fmt rgb24 -vframes 100 ./netflix/BoxingPractice-%03d.png')
31 | # end
32 |
33 | if len(glob.glob('./netflix/Crosswalk-*.png')) != 100:
34 | os.system('ffmpeg -i https://media.xiph.org/video/derf/ElFuente/Netflix_Crosswalk_4096x2160_60fps_10bit_420.y4m -pix_fmt rgb24 -vframes 100 ./netflix/Crosswalk-%03d.png')
35 | # end
36 |
37 | if len(glob.glob('./netflix/DrivingPOV-*.png')) != 100:
38 | os.system('ffmpeg -i https://media.xiph.org/video/derf/Chimera/Netflix_DrivingPOV_4096x2160_60fps_10bit_420.y4m -pix_fmt rgb24 -vframes 100 ./netflix/DrivingPOV-%03d.png')
39 | # end
40 |
41 | if len(glob.glob('./netflix/FoodMarket-*.png')) != 100:
42 | os.system('ffmpeg -i https://media.xiph.org/video/derf/ElFuente/Netflix_FoodMarket_4096x2160_60fps_10bit_420.y4m -pix_fmt rgb24 -vframes 100 ./netflix/FoodMarket-%03d.png')
43 | # end
44 |
45 | if len(glob.glob('./netflix/FoodMarket2-*.png')) != 100:
46 | os.system('ffmpeg -i https://media.xiph.org/video/derf/ElFuente/Netflix_FoodMarket2_4096x2160_60fps_10bit_420.y4m -pix_fmt rgb24 -vframes 100 ./netflix/FoodMarket2-%03d.png')
47 | # end
48 |
49 | if len(glob.glob('./netflix/RitualDance-*.png')) != 100:
50 | os.system('ffmpeg -i https://media.xiph.org/video/derf/ElFuente/Netflix_RitualDance_4096x2160_60fps_10bit_420.y4m -pix_fmt rgb24 -vframes 100 ./netflix/RitualDance-%03d.png')
51 | # end
52 |
53 | if len(glob.glob('./netflix/SquareAndTimelapse-*.png')) != 100:
54 | os.system('ffmpeg -i https://media.xiph.org/video/derf/ElFuente/Netflix_SquareAndTimelapse_4096x2160_60fps_10bit_420.y4m -pix_fmt rgb24 -vframes 100 ./netflix/SquareAndTimelapse-%03d.png')
55 | # end
56 |
57 | if len(glob.glob('./netflix/Tango-*.png')) != 100:
58 | os.system('ffmpeg -i https://media.xiph.org/video/derf/ElFuente/Netflix_Tango_4096x2160_60fps_10bit_420.y4m -pix_fmt rgb24 -vframes 100 ./netflix/Tango-%03d.png')
59 | # end
60 |
61 | ##########################################################
62 |
63 | if os.path.exists('./sepconv-slomo') == False:
64 | os.system('git clone https://github.com/sniklaus/sepconv-slomo')
65 | os.system('cd ./sepconv-slomo && bash download.bash')
66 | os.system('sed -i "s#assert(intWidth <= 1280)##g" ./sepconv-slomo/pwc_network.py')
67 | os.system('sed -i "s#assert(intHeight <= 720)##g" ./sepconv-slomo/pwc_network.py')
68 | # end
69 |
70 | sys.path.insert(0, './sepconv-slomo')
71 | sys.path.insert(0, './sepconv-slomo/sepconv')
72 | import run
73 | run.arguments_strModel = 'l1'
74 | run.arguments_strPadding = 'paper'
75 |
76 | ##########################################################
77 |
78 | for strCategory in ['resized', 'cropped']:
79 | fltPsnr = []
80 | fltSsim = []
81 |
82 | for strFile in ['BoxingPractice', 'Crosswalk', 'DrivingPOV', 'FoodMarket', 'FoodMarket2', 'RitualDance', 'SquareAndTimelapse', 'Tango']:
83 | for intFrame in range(2, 99, 2):
84 | npyFirst = cv2.imread(filename='./netflix/' + strFile + '-' + str(intFrame - 1).zfill(3) + '.png', flags=-1)
85 | npySecond = cv2.imread(filename='./netflix/' + strFile + '-' + str(intFrame + 1).zfill(3) + '.png', flags=-1)
86 | npyReference = cv2.imread(filename='./netflix/' + strFile + '-' + str(intFrame).zfill(3) + '.png', flags=-1)
87 |
88 | if strCategory == 'resized':
89 | npyFirst = cv2.resize(src=npyFirst, dsize=(2048, 1080), fx=0.0, fy=0.0, interpolation=cv2.INTER_AREA)
90 | npySecond = cv2.resize(src=npySecond, dsize=(2048, 1080), fx=0.0, fy=0.0, interpolation=cv2.INTER_AREA)
91 | npyReference = cv2.resize(src=npyReference, dsize=(2048, 1080), fx=0.0, fy=0.0, interpolation=cv2.INTER_AREA)
92 |
93 | elif strCategory == 'cropped':
94 | npyFirst = npyFirst[540:-540, 1024:-1024, :]
95 | npySecond = npySecond[540:-540, 1024:-1024, :]
96 | npyReference = npyReference[540:-540, 1024:-1024, :]
97 |
98 | # end
99 |
100 | tenFirst = torch.FloatTensor(numpy.ascontiguousarray(npyFirst.transpose(2, 0, 1).astype(numpy.float32) * (1.0 / 255.0)))
101 | tenSecond = torch.FloatTensor(numpy.ascontiguousarray(npySecond.transpose(2, 0, 1).astype(numpy.float32) * (1.0 / 255.0)))
102 |
103 | npyEstimate = (run.estimate(tenFirst, tenSecond).clamp(0.0, 1.0).numpy().transpose(1, 2, 0) * 255.0).astype(numpy.uint8)
104 |
105 | fltPsnr.append(skimage.metrics.peak_signal_noise_ratio(image_true=npyReference, image_test=npyEstimate, data_range=255))
106 | fltSsim.append(skimage.metrics.structural_similarity(im1=npyReference, im2=npyEstimate, data_range=255, multichannel=True))
107 | # end
108 | # end
109 |
110 | print('category', strCategory)
111 | print('computed average psnr', numpy.mean(fltPsnr))
112 | print('computed average ssim', numpy.mean(fltSsim))
113 | # end
114 |
--------------------------------------------------------------------------------
/softcode/softsplatting/requirements.txt:
--------------------------------------------------------------------------------
1 | cupy>=5.0.0
2 | numpy>=1.15.0
3 | opencv-contrib-python>=3.4.0
4 | torch>=1.6.0
--------------------------------------------------------------------------------
/softcode/softsplatting/run.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import torch
4 |
5 | import cv2
6 | import numpy
7 |
8 | from softsplatting import softsplat
9 |
10 | ##########################################################
11 |
12 | assert(int(str('').join(torch.__version__.split('.')[0:2])) >= 13) # requires at least pytorch version 1.3.0
13 |
14 | ##########################################################
15 |
16 | def read_flo(strFile):
17 | with open(strFile, 'rb') as objFile:
18 | strFlow = objFile.read()
19 | # end
20 |
21 | assert(numpy.frombuffer(buffer=strFlow, dtype=numpy.float32, count=1, offset=0) == 202021.25)
22 |
23 | intWidth = numpy.frombuffer(buffer=strFlow, dtype=numpy.int32, count=1, offset=4)[0]
24 | intHeight = numpy.frombuffer(buffer=strFlow, dtype=numpy.int32, count=1, offset=8)[0]
25 |
26 | return numpy.frombuffer(buffer=strFlow, dtype=numpy.float32, count=intHeight * intWidth * 2, offset=12).reshape([ intHeight, intWidth, 2 ])
27 | # end
28 |
29 | ##########################################################
30 |
31 | backwarp_tenGrid = {}
32 |
33 | def backwarp(tenInput, tenFlow):
34 | if str(tenFlow.shape) not in backwarp_tenGrid:
35 | tenHor = torch.linspace(-1.0 + (1.0 / tenFlow.shape[3]), 1.0 - (1.0 / tenFlow.shape[3]), tenFlow.shape[3]).view(1, 1, 1, -1).expand(-1, -1, tenFlow.shape[2], -1)
36 | tenVer = torch.linspace(-1.0 + (1.0 / tenFlow.shape[2]), 1.0 - (1.0 / tenFlow.shape[2]), tenFlow.shape[2]).view(1, 1, -1, 1).expand(-1, -1, -1, tenFlow.shape[3])
37 |
38 | backwarp_tenGrid[str(tenFlow.shape)] = torch.cat([ tenHor, tenVer ], 1).cuda()
39 | # end
40 |
41 | tenFlow = torch.cat([ tenFlow[:, 0:1, :, :] / ((tenInput.shape[3] - 1.0) / 2.0), tenFlow[:, 1:2, :, :] / ((tenInput.shape[2] - 1.0) / 2.0) ], 1)
42 |
43 | return torch.nn.functional.grid_sample(input=tenInput, grid=(backwarp_tenGrid[str(tenFlow.shape)] + tenFlow).permute(0, 2, 3, 1), mode='bilinear', padding_mode='zeros', align_corners=False)
44 | # end
45 |
46 | ##########################################################
47 |
48 |
49 | # end
50 |
51 | if __name__=='__main__':
52 | #
53 | W = 448
54 | H = 328
55 | N = 2
56 | tenFirst = torch.rand(size=(N,32,H,W)).cuda()
57 | tenFlow = torch.rand(size=(N,2,H,W)).cuda()
58 | tenMetric = torch.rand(size=(N,1,H,W)).cuda()
59 | tenSoftmax = softsplat.FunctionSoftsplat(tenInput=tenFirst, tenFlow=tenFlow * 0.5, tenMetric=-20.0 * tenMetric,
60 | strType='softmax')
61 | print(tenSoftmax.shape)
62 | # torch.Size([2, 32, 328, 448]) 这说明不仅仅可以warp images 其实几通道都可以warp
63 |
64 |
65 | # tenFirst = torch.FloatTensor(numpy.ascontiguousarray(
66 | # cv2.imread(filename='./images/first.png', flags=-1).transpose(2, 0, 1)[None, :, :, :].astype(numpy.float32) * (
67 | # 1.0 / 255.0))).cuda()
68 | # tenSecond = torch.FloatTensor(numpy.ascontiguousarray(
69 | # cv2.imread(filename='./images/second.png', flags=-1).transpose(2, 0, 1)[None, :, :, :].astype(numpy.float32) * (
70 | # 1.0 / 255.0))).cuda()
71 | # tenFlow = torch.FloatTensor(
72 | # numpy.ascontiguousarray(read_flo('./images/flow.flo').transpose(2, 0, 1)[None, :, :, :])).cuda()
73 | #
74 | # tenMetric = torch.nn.functional.l1_loss(input=tenFirst, target=backwarp(tenInput=tenSecond, tenFlow=tenFlow),
75 | # reduction='none').mean(1, True)
76 | #
77 | # for intTime, fltTime in enumerate(numpy.linspace(0.0, 1.0, 11).tolist()):
78 | # tenSummation = softsplat.FunctionSoftsplat(tenInput=tenFirst, tenFlow=tenFlow * fltTime, tenMetric=None,
79 | # strType='summation')
80 | # tenAverage = softsplat.FunctionSoftsplat(tenInput=tenFirst, tenFlow=tenFlow * fltTime, tenMetric=None,
81 | # strType='average')
82 | # tenLinear = softsplat.FunctionSoftsplat(tenInput=tenFirst, tenFlow=tenFlow * fltTime,
83 | # tenMetric=(0.3 - tenMetric).clamp(0.0000001, 1.0),
84 | # strType='linear') # finding a good linearly metric is difficult, and it is not invariant to translations
85 | # tenSoftmax = softsplat.FunctionSoftsplat(tenInput=tenFirst, tenFlow=tenFlow * fltTime,
86 | # tenMetric=-20.0 * tenMetric,
87 | # strType='softmax') # -20.0 is a hyperparameter, called 'beta' in the paper, that could be learned using a torch.Parameter
88 | #
89 | # cv2.imshow(winname='summation', mat=tenSummation[0, :, :, :].cpu().numpy().transpose(1, 2, 0))
90 | # cv2.imshow(winname='average', mat=tenAverage[0, :, :, :].cpu().numpy().transpose(1, 2, 0))
91 | # cv2.imshow(winname='linear', mat=tenLinear[0, :, :, :].cpu().numpy().transpose(1, 2, 0))
92 | # cv2.imshow(winname='softmax', mat=tenSoftmax[0, :, :, :].cpu().numpy().transpose(1, 2, 0))
93 | # cv2.waitKey(delay=0)
94 |
--------------------------------------------------------------------------------
/softcode/softsplatting/softsplat.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import torch
4 |
5 | import cupy
6 | import re
7 |
8 | kernel_Softsplat_updateOutput = '''
9 | extern "C" __global__ void kernel_Softsplat_updateOutput(
10 | const int n,
11 | const float* input,
12 | const float* flow,
13 | float* output
14 | ) { for (int intIndex = (blockIdx.x * blockDim.x) + threadIdx.x; intIndex < n; intIndex += blockDim.x * gridDim.x) {
15 | const int intN = ( intIndex / SIZE_3(output) / SIZE_2(output) / SIZE_1(output) ) % SIZE_0(output);
16 | const int intC = ( intIndex / SIZE_3(output) / SIZE_2(output) ) % SIZE_1(output);
17 | const int intY = ( intIndex / SIZE_3(output) ) % SIZE_2(output);
18 | const int intX = ( intIndex ) % SIZE_3(output);
19 |
20 | float fltOutputX = (float) (intX) + VALUE_4(flow, intN, 0, intY, intX);
21 | float fltOutputY = (float) (intY) + VALUE_4(flow, intN, 1, intY, intX);
22 |
23 | int intNorthwestX = (int) (floor(fltOutputX));
24 | int intNorthwestY = (int) (floor(fltOutputY));
25 | int intNortheastX = intNorthwestX + 1;
26 | int intNortheastY = intNorthwestY;
27 | int intSouthwestX = intNorthwestX;
28 | int intSouthwestY = intNorthwestY + 1;
29 | int intSoutheastX = intNorthwestX + 1;
30 | int intSoutheastY = intNorthwestY + 1;
31 |
32 | float fltNorthwest = ((float) (intSoutheastX) - fltOutputX ) * ((float) (intSoutheastY) - fltOutputY );
33 | float fltNortheast = (fltOutputX - (float) (intSouthwestX)) * ((float) (intSouthwestY) - fltOutputY );
34 | float fltSouthwest = ((float) (intNortheastX) - fltOutputX ) * (fltOutputY - (float) (intNortheastY));
35 | float fltSoutheast = (fltOutputX - (float) (intNorthwestX)) * (fltOutputY - (float) (intNorthwestY));
36 |
37 | if ((intNorthwestX >= 0) & (intNorthwestX < SIZE_3(output)) & (intNorthwestY >= 0) & (intNorthwestY < SIZE_2(output))) {
38 | atomicAdd(&output[OFFSET_4(output, intN, intC, intNorthwestY, intNorthwestX)], VALUE_4(input, intN, intC, intY, intX) * fltNorthwest);
39 | }
40 |
41 | if ((intNortheastX >= 0) & (intNortheastX < SIZE_3(output)) & (intNortheastY >= 0) & (intNortheastY < SIZE_2(output))) {
42 | atomicAdd(&output[OFFSET_4(output, intN, intC, intNortheastY, intNortheastX)], VALUE_4(input, intN, intC, intY, intX) * fltNortheast);
43 | }
44 |
45 | if ((intSouthwestX >= 0) & (intSouthwestX < SIZE_3(output)) & (intSouthwestY >= 0) & (intSouthwestY < SIZE_2(output))) {
46 | atomicAdd(&output[OFFSET_4(output, intN, intC, intSouthwestY, intSouthwestX)], VALUE_4(input, intN, intC, intY, intX) * fltSouthwest);
47 | }
48 |
49 | if ((intSoutheastX >= 0) & (intSoutheastX < SIZE_3(output)) & (intSoutheastY >= 0) & (intSoutheastY < SIZE_2(output))) {
50 | atomicAdd(&output[OFFSET_4(output, intN, intC, intSoutheastY, intSoutheastX)], VALUE_4(input, intN, intC, intY, intX) * fltSoutheast);
51 | }
52 | } }
53 | '''
54 |
55 | kernel_Softsplat_updateGradInput = '''
56 | extern "C" __global__ void kernel_Softsplat_updateGradInput(
57 | const int n,
58 | const float* input,
59 | const float* flow,
60 | const float* gradOutput,
61 | float* gradInput,
62 | float* gradFlow
63 | ) { for (int intIndex = (blockIdx.x * blockDim.x) + threadIdx.x; intIndex < n; intIndex += blockDim.x * gridDim.x) {
64 | const int intN = ( intIndex / SIZE_3(gradInput) / SIZE_2(gradInput) / SIZE_1(gradInput) ) % SIZE_0(gradInput);
65 | const int intC = ( intIndex / SIZE_3(gradInput) / SIZE_2(gradInput) ) % SIZE_1(gradInput);
66 | const int intY = ( intIndex / SIZE_3(gradInput) ) % SIZE_2(gradInput);
67 | const int intX = ( intIndex ) % SIZE_3(gradInput);
68 |
69 | float fltGradInput = 0.0;
70 |
71 | float fltOutputX = (float) (intX) + VALUE_4(flow, intN, 0, intY, intX);
72 | float fltOutputY = (float) (intY) + VALUE_4(flow, intN, 1, intY, intX);
73 |
74 | int intNorthwestX = (int) (floor(fltOutputX));
75 | int intNorthwestY = (int) (floor(fltOutputY));
76 | int intNortheastX = intNorthwestX + 1;
77 | int intNortheastY = intNorthwestY;
78 | int intSouthwestX = intNorthwestX;
79 | int intSouthwestY = intNorthwestY + 1;
80 | int intSoutheastX = intNorthwestX + 1;
81 | int intSoutheastY = intNorthwestY + 1;
82 |
83 | float fltNorthwest = ((float) (intSoutheastX) - fltOutputX ) * ((float) (intSoutheastY) - fltOutputY );
84 | float fltNortheast = (fltOutputX - (float) (intSouthwestX)) * ((float) (intSouthwestY) - fltOutputY );
85 | float fltSouthwest = ((float) (intNortheastX) - fltOutputX ) * (fltOutputY - (float) (intNortheastY));
86 | float fltSoutheast = (fltOutputX - (float) (intNorthwestX)) * (fltOutputY - (float) (intNorthwestY));
87 |
88 | if ((intNorthwestX >= 0) & (intNorthwestX < SIZE_3(gradOutput)) & (intNorthwestY >= 0) & (intNorthwestY < SIZE_2(gradOutput))) {
89 | fltGradInput += VALUE_4(gradOutput, intN, intC, intNorthwestY, intNorthwestX) * fltNorthwest;
90 | }
91 |
92 | if ((intNortheastX >= 0) & (intNortheastX < SIZE_3(gradOutput)) & (intNortheastY >= 0) & (intNortheastY < SIZE_2(gradOutput))) {
93 | fltGradInput += VALUE_4(gradOutput, intN, intC, intNortheastY, intNortheastX) * fltNortheast;
94 | }
95 |
96 | if ((intSouthwestX >= 0) & (intSouthwestX < SIZE_3(gradOutput)) & (intSouthwestY >= 0) & (intSouthwestY < SIZE_2(gradOutput))) {
97 | fltGradInput += VALUE_4(gradOutput, intN, intC, intSouthwestY, intSouthwestX) * fltSouthwest;
98 | }
99 |
100 | if ((intSoutheastX >= 0) & (intSoutheastX < SIZE_3(gradOutput)) & (intSoutheastY >= 0) & (intSoutheastY < SIZE_2(gradOutput))) {
101 | fltGradInput += VALUE_4(gradOutput, intN, intC, intSoutheastY, intSoutheastX) * fltSoutheast;
102 | }
103 |
104 | gradInput[intIndex] = fltGradInput;
105 | } }
106 | '''
107 |
108 | kernel_Softsplat_updateGradFlow = '''
109 | extern "C" __global__ void kernel_Softsplat_updateGradFlow(
110 | const int n,
111 | const float* input,
112 | const float* flow,
113 | const float* gradOutput,
114 | float* gradInput,
115 | float* gradFlow
116 | ) { for (int intIndex = (blockIdx.x * blockDim.x) + threadIdx.x; intIndex < n; intIndex += blockDim.x * gridDim.x) {
117 | float fltGradFlow = 0.0;
118 |
119 | const int intN = ( intIndex / SIZE_3(gradFlow) / SIZE_2(gradFlow) / SIZE_1(gradFlow) ) % SIZE_0(gradFlow);
120 | const int intC = ( intIndex / SIZE_3(gradFlow) / SIZE_2(gradFlow) ) % SIZE_1(gradFlow);
121 | const int intY = ( intIndex / SIZE_3(gradFlow) ) % SIZE_2(gradFlow);
122 | const int intX = ( intIndex ) % SIZE_3(gradFlow);
123 |
124 | float fltOutputX = (float) (intX) + VALUE_4(flow, intN, 0, intY, intX);
125 | float fltOutputY = (float) (intY) + VALUE_4(flow, intN, 1, intY, intX);
126 |
127 | int intNorthwestX = (int) (floor(fltOutputX));
128 | int intNorthwestY = (int) (floor(fltOutputY));
129 | int intNortheastX = intNorthwestX + 1;
130 | int intNortheastY = intNorthwestY;
131 | int intSouthwestX = intNorthwestX;
132 | int intSouthwestY = intNorthwestY + 1;
133 | int intSoutheastX = intNorthwestX + 1;
134 | int intSoutheastY = intNorthwestY + 1;
135 |
136 | float fltNorthwest = 0.0;
137 | float fltNortheast = 0.0;
138 | float fltSouthwest = 0.0;
139 | float fltSoutheast = 0.0;
140 |
141 | if (intC == 0) {
142 | fltNorthwest = ((float) (-1.0)) * ((float) (intSoutheastY) - fltOutputY );
143 | fltNortheast = ((float) (+1.0)) * ((float) (intSouthwestY) - fltOutputY );
144 | fltSouthwest = ((float) (-1.0)) * (fltOutputY - (float) (intNortheastY));
145 | fltSoutheast = ((float) (+1.0)) * (fltOutputY - (float) (intNorthwestY));
146 |
147 | } else if (intC == 1) {
148 | fltNorthwest = ((float) (intSoutheastX) - fltOutputX ) * ((float) (-1.0));
149 | fltNortheast = (fltOutputX - (float) (intSouthwestX)) * ((float) (-1.0));
150 | fltSouthwest = ((float) (intNortheastX) - fltOutputX ) * ((float) (+1.0));
151 | fltSoutheast = (fltOutputX - (float) (intNorthwestX)) * ((float) (+1.0));
152 |
153 | }
154 |
155 | for (int intChannel = 0; intChannel < SIZE_1(gradOutput); intChannel += 1) {
156 | float fltInput = VALUE_4(input, intN, intChannel, intY, intX);
157 |
158 | if ((intNorthwestX >= 0) & (intNorthwestX < SIZE_3(gradOutput)) & (intNorthwestY >= 0) & (intNorthwestY < SIZE_2(gradOutput))) {
159 | fltGradFlow += fltInput * VALUE_4(gradOutput, intN, intChannel, intNorthwestY, intNorthwestX) * fltNorthwest;
160 | }
161 |
162 | if ((intNortheastX >= 0) & (intNortheastX < SIZE_3(gradOutput)) & (intNortheastY >= 0) & (intNortheastY < SIZE_2(gradOutput))) {
163 | fltGradFlow += fltInput * VALUE_4(gradOutput, intN, intChannel, intNortheastY, intNortheastX) * fltNortheast;
164 | }
165 |
166 | if ((intSouthwestX >= 0) & (intSouthwestX < SIZE_3(gradOutput)) & (intSouthwestY >= 0) & (intSouthwestY < SIZE_2(gradOutput))) {
167 | fltGradFlow += fltInput * VALUE_4(gradOutput, intN, intChannel, intSouthwestY, intSouthwestX) * fltSouthwest;
168 | }
169 |
170 | if ((intSoutheastX >= 0) & (intSoutheastX < SIZE_3(gradOutput)) & (intSoutheastY >= 0) & (intSoutheastY < SIZE_2(gradOutput))) {
171 | fltGradFlow += fltInput * VALUE_4(gradOutput, intN, intChannel, intSoutheastY, intSoutheastX) * fltSoutheast;
172 | }
173 | }
174 |
175 | gradFlow[intIndex] = fltGradFlow;
176 | } }
177 | '''
178 |
179 | def cupy_kernel(strFunction, objVariables):
180 | strKernel = globals()[strFunction]
181 |
182 | while True:
183 | objMatch = re.search('(SIZE_)([0-4])(\()([^\)]*)(\))', strKernel)
184 |
185 | if objMatch is None:
186 | break
187 | # end
188 |
189 | intArg = int(objMatch.group(2))
190 |
191 | strTensor = objMatch.group(4)
192 | intSizes = objVariables[strTensor].size()
193 |
194 | strKernel = strKernel.replace(objMatch.group(), str(intSizes[intArg]))
195 | # end
196 |
197 | while True:
198 | objMatch = re.search('(OFFSET_)([0-4])(\()([^\)]+)(\))', strKernel)
199 |
200 | if objMatch is None:
201 | break
202 | # end
203 |
204 | intArgs = int(objMatch.group(2))
205 | strArgs = objMatch.group(4).split(',')
206 |
207 | strTensor = strArgs[0]
208 | intStrides = objVariables[strTensor].stride()
209 | strIndex = [ '((' + strArgs[intArg + 1].replace('{', '(').replace('}', ')').strip() + ')*' + str(intStrides[intArg]) + ')' for intArg in range(intArgs) ]
210 |
211 | strKernel = strKernel.replace(objMatch.group(0), '(' + str.join('+', strIndex) + ')')
212 | # end
213 |
214 | while True:
215 | objMatch = re.search('(VALUE_)([0-4])(\()([^\)]+)(\))', strKernel)
216 |
217 | if objMatch is None:
218 | break
219 | # end
220 |
221 | intArgs = int(objMatch.group(2))
222 | strArgs = objMatch.group(4).split(',')
223 |
224 | strTensor = strArgs[0]
225 | intStrides = objVariables[strTensor].stride()
226 | strIndex = [ '((' + strArgs[intArg + 1].replace('{', '(').replace('}', ')').strip() + ')*' + str(intStrides[intArg]) + ')' for intArg in range(intArgs) ]
227 |
228 | strKernel = strKernel.replace(objMatch.group(0), strTensor + '[' + str.join('+', strIndex) + ']')
229 | # end
230 |
231 | return strKernel
232 | # end
233 |
234 | @cupy.memoize(for_each_device=True)
235 | def cupy_launch(strFunction, strKernel):
236 | return cupy.cuda.compile_with_cache(strKernel).get_function(strFunction)
237 | # end
238 |
239 | class _FunctionSoftsplat(torch.autograd.Function):
240 | @staticmethod
241 | def forward(self, input, flow):
242 | self.save_for_backward(input, flow)
243 |
244 | intSamples = input.shape[0]
245 | intInputDepth, intInputHeight, intInputWidth = input.shape[1], input.shape[2], input.shape[3]
246 | intFlowDepth, intFlowHeight, intFlowWidth = flow.shape[1], flow.shape[2], flow.shape[3]
247 |
248 | assert(intFlowDepth == 2)
249 | assert(intInputHeight == intFlowHeight)
250 | assert(intInputWidth == intFlowWidth)
251 |
252 | assert(input.is_contiguous() == True)
253 | assert(flow.is_contiguous() == True)
254 |
255 | output = input.new_zeros([ intSamples, intInputDepth, intInputHeight, intInputWidth ])
256 |
257 | if input.is_cuda == True:
258 | n = output.nelement()
259 | cupy_launch('kernel_Softsplat_updateOutput', cupy_kernel('kernel_Softsplat_updateOutput', {
260 | 'input': input,
261 | 'flow': flow,
262 | 'output': output
263 | }))(
264 | grid=tuple([ int((n + 512 - 1) / 512), 1, 1 ]),
265 | block=tuple([ 512, 1, 1 ]),
266 | args=[ n, input.data_ptr(), flow.data_ptr(), output.data_ptr() ]
267 | )
268 |
269 | elif input.is_cuda == False:
270 | raise NotImplementedError()
271 |
272 | # end
273 |
274 | return output
275 | # end
276 |
277 | @staticmethod
278 | def backward(self, gradOutput):
279 | input, flow = self.saved_tensors
280 |
281 | intSamples = input.shape[0]
282 | intInputDepth, intInputHeight, intInputWidth = input.shape[1], input.shape[2], input.shape[3]
283 | intFlowDepth, intFlowHeight, intFlowWidth = flow.shape[1], flow.shape[2], flow.shape[3]
284 |
285 | assert(intFlowDepth == 2)
286 | assert(intInputHeight == intFlowHeight)
287 | assert(intInputWidth == intFlowWidth)
288 |
289 | assert(gradOutput.is_contiguous() == True)
290 |
291 | gradInput = input.new_zeros([ intSamples, intInputDepth, intInputHeight, intInputWidth ]) if self.needs_input_grad[0] == True else None
292 | gradFlow = input.new_zeros([ intSamples, intFlowDepth, intFlowHeight, intFlowWidth ]) if self.needs_input_grad[1] == True else None
293 |
294 | if input.is_cuda == True:
295 | if gradInput is not None:
296 | n = gradInput.nelement()
297 | cupy_launch('kernel_Softsplat_updateGradInput', cupy_kernel('kernel_Softsplat_updateGradInput', {
298 | 'input': input,
299 | 'flow': flow,
300 | 'gradOutput': gradOutput,
301 | 'gradInput': gradInput,
302 | 'gradFlow': gradFlow
303 | }))(
304 | grid=tuple([ int((n + 512 - 1) / 512), 1, 1 ]),
305 | block=tuple([ 512, 1, 1 ]),
306 | args=[ n, input.data_ptr(), flow.data_ptr(), gradOutput.data_ptr(), gradInput.data_ptr(), None ]
307 | )
308 | # end
309 |
310 | if gradFlow is not None:
311 | n = gradFlow.nelement()
312 | cupy_launch('kernel_Softsplat_updateGradFlow', cupy_kernel('kernel_Softsplat_updateGradFlow', {
313 | 'input': input,
314 | 'flow': flow,
315 | 'gradOutput': gradOutput,
316 | 'gradInput': gradInput,
317 | 'gradFlow': gradFlow
318 | }))(
319 | grid=tuple([ int((n + 512 - 1) / 512), 1, 1 ]),
320 | block=tuple([ 512, 1, 1 ]),
321 | args=[ n, input.data_ptr(), flow.data_ptr(), gradOutput.data_ptr(), None, gradFlow.data_ptr() ]
322 | )
323 | # end
324 |
325 | elif input.is_cuda == False:
326 | raise NotImplementedError()
327 |
328 | # end
329 |
330 | return gradInput, gradFlow
331 | # end
332 | # end
333 |
334 | def FunctionSoftsplat(tenInput, tenFlow, tenMetric, strType):
335 | assert(tenMetric is None or tenMetric.shape[1] == 1)
336 | assert(strType in ['summation', 'average', 'linear', 'softmax'])
337 |
338 | if strType == 'average':
339 | tenInput = torch.cat([ tenInput, tenInput.new_ones(tenInput.shape[0], 1, tenInput.shape[2], tenInput.shape[3]) ], 1)
340 |
341 | elif strType == 'linear':
342 | tenInput = torch.cat([ tenInput * tenMetric, tenMetric ], 1)
343 |
344 | elif strType == 'softmax':
345 | tenInput = torch.cat([ tenInput * tenMetric.exp(), tenMetric.exp() ], 1)
346 |
347 | # end
348 |
349 | tenOutput = _FunctionSoftsplat.apply(tenInput, tenFlow)
350 |
351 | if strType != 'summation':
352 | tenNormalize = tenOutput[:, -1:, :, :]
353 |
354 | tenNormalize[tenNormalize == 0.0] = 1.0
355 |
356 | tenOutput = tenOutput[:, :-1, :, :] / tenNormalize
357 | # end
358 |
359 | return tenOutput
360 | # end
361 |
362 | class ModuleSoftsplat(torch.nn.Module):
363 | def __init__(self, strType):
364 | super(ModuleSoftsplat, self).__init__()
365 |
366 | self.strType = strType
367 | # end
368 |
369 | def forward(self, tenInput, tenFlow, tenMetric):
370 | return FunctionSoftsplat(tenInput, tenFlow, tenMetric, self.strType)
371 | # end
372 | # end
--------------------------------------------------------------------------------
/softcode/tmptest.py:
--------------------------------------------------------------------------------
1 | #临时测试使用
2 |
3 | import os
4 | import shutil
5 | base_dir = 'D:/dataset/vimeo_triplet'
6 | def generate_sub_dataset():
7 |
8 | sub_train_tri_ls = os.path.join(base_dir, 'sub_test_tri_ls.txt')
9 | tri_names = ['im1.png', 'im2.png', 'im3.png']
10 | sub_dataset_root = 'D:/dataset'
11 | with open(sub_train_tri_ls, 'r') as f:
12 | sub_train_tri_ls = f.readlines()
13 | for each in sub_train_tri_ls:
14 |
15 | each = each.strip('\n')
16 | new_img_dir = os.path.join(sub_dataset_root, 'vimeo_sub_triplet', 'sequences', each)
17 | if not os.path.exists(new_img_dir):
18 | os.makedirs(new_img_dir)
19 | for name in tri_names:
20 | img_dir = os.path.join(base_dir, 'sequences', each, name)
21 | dest = os.path.join(sub_dataset_root, 'vimeo_sub_triplet', 'sequences', each, name)
22 | print(dest)
23 | shutil.copy(img_dir,dest)
24 | if __name__=='__main__':
25 | generate_sub_dataset()
--------------------------------------------------------------------------------
/softcode/train_and_test.py:
--------------------------------------------------------------------------------
1 |
2 | from vimo_dataset import Vimeo
3 | from main_net import Main_net
4 | from torch.utils.data import DataLoader
5 | import torch
6 | import torch.nn as nn
7 | from loss_f import LapLoss
8 |
9 |
10 | vimo_data_dir = 'D:/dataset/vimeo_triplet'
11 |
12 | # class LaplacianPyramid(nn.Module):
13 | # def __init__(self, max_level=5):
14 | # super(LaplacianPyramid, self).__init__()
15 | # self.gaussian_conv = GaussianConv()
16 | # self.max_level = max_level
17 | #
18 | # def forward(self, X):
19 | # t_pyr = []
20 | # current = X
21 | # for level in range(self.max_level):
22 | # t_guass = self.gaussian_conv(current)
23 | # t_diff = current - t_guass
24 | # t_pyr.append(t_diff)
25 | # current = F.avg_pool2d(t_guass, 2)
26 | # t_pyr.append(current)
27 | #
28 | # return t_pyr
29 | #
30 | # class LaplacianLoss(nn.Module):
31 | # def __init__(self):
32 | # super(LaplacianLoss, self).__init__()
33 | #
34 | # self.criterion = nn.L1Loss()
35 | # self.lap = LaplacianPyramid()
36 | #
37 | # def forward(self, x, y):
38 | # x_lap, y_lap = self.lap(x), self.lap(y)
39 | # return sum(self.criterion(a, b) for a, b in zip(x_lap, y_lap))
40 | def train():
41 | batch_size = 1
42 | total_step = 100
43 | num_workers = 0
44 | crop = False
45 | if crop:
46 | W = 256
47 | H = 256
48 |
49 | else:
50 | W = 448
51 | H = 256
52 | lr = 1e-4
53 | criteration = LapLoss()
54 | vimo_dataset = Vimeo(base_dir=vimo_data_dir)
55 | train_loader = DataLoader(vimo_dataset,
56 | batch_size=batch_size,
57 | shuffle=True,
58 | num_workers=num_workers,
59 | pin_memory=True)
60 | shape= [batch_size,3,H,W]
61 | model = Main_net(shape).cuda().train(True)
62 | optimizer = torch.optim.Adam(params=model.parameters(), lr=lr, weight_decay=4e-4)
63 |
64 | for step in range(total_step):
65 | total_loss = 0
66 | for ix,data in enumerate(train_loader):
67 |
68 | img1,img2 ,tar= data
69 | img1 = img1.cuda()
70 | img2 = img2.cuda()
71 | tar = tar.cuda()
72 | img_out = model(img1,img2)
73 | # loss = torch.nn.functional.l1_loss(img_out,tar)
74 | loss = criteration(img_out, tar)
75 |
76 | optimizer.zero_grad()
77 |
78 | loss.backward()
79 | optimizer.step()
80 | if ix %5==0:
81 | print('data idx:' +' lr :'+str(lr)+' epoch: ' +str(ix)+' / '+str(len(train_loader)))
82 | print('loss value :', loss.item())
83 | total_loss+=loss
84 | f.write('epoch: '+str(step)+' avg loss :'+str(total_loss.item()/len(train_loader)))
85 | f.write('\n')
86 | print('epoch: '+str(step)+' avg loss :'+str(total_loss.item()/len(train_loader)))
87 | if (step+1)%3==0:
88 | torch.save(model,'./weights/'+'model_weight_'+str(step+1)+'.pth')
89 |
90 |
91 | if __name__=='__main__':
92 | train()
--------------------------------------------------------------------------------
/softcode/vimo_dataset.py:
--------------------------------------------------------------------------------
1 | from torch.utils.data import Dataset
2 |
3 | import numpy as np
4 | import imageio
5 | import torch
6 | import random
7 | class StaticRandomCrop(object):
8 | def __init__(self, image_size, crop_size):
9 | self.th, self.tw = crop_size
10 | h, w = image_size
11 | self.h1 = random.randint(0, h - self.th)
12 | self.w1 = random.randint(0, w - self.tw)
13 |
14 | def __call__(self, img):
15 | return img[self.h1:(self.h1+self.th), self.w1:(self.w1+self.tw),:]
16 |
17 |
18 | class StaticCenterCrop(object):
19 | def __init__(self, image_size, crop_size):
20 | self.th, self.tw = crop_size
21 | self.h, self.w = image_size
22 | def __call__(self, img):
23 | return img[(self.h-self.th)//2:(self.h+self.th)//2, (self.w-self.tw)//2:(self.w+self.tw)//2,:]
24 | class Vimeo(Dataset):
25 | def __init__(self, base_dir, augument=False, transform=None):
26 |
27 | self.width = 448
28 | self.height = 256
29 | self.augument = augument
30 | self.transform = transform
31 | self.base_dir = base_dir
32 | self.crop_shape = (256,256)
33 | self.cropper = 'random'
34 | self.files_dir_ls = self.get_file_ls()
35 |
36 | def get_file_ls(self):
37 | tri_img = ['im1.png', 'im2.png', 'im3.png']
38 | total_res_ls = []
39 | with open(self.base_dir+'/'+'tri_trainlist.txt','r') as f:
40 | each_ls = f.readlines()
41 | for each in each_ls:
42 | each = each.strip('\n')
43 | tmp_p_ls = []
44 | for sub in tri_img:
45 | tmp_p_ls.append(self.base_dir + '/' + 'sequences' + '/' + each + '/' + sub)
46 | total_res_ls.append(tmp_p_ls)
47 | return total_res_ls
48 |
49 | def __getitem__(self, idx):
50 | # files_dir_ls 包含了三张图片
51 | # device = torch.device(type='cuda')
52 | img1_path = self.files_dir_ls[idx][0]
53 | img2_path = self.files_dir_ls[idx][-1]
54 | target_path = self.files_dir_ls[idx][1]
55 |
56 | img1, img2,target = map(imageio.imread, (img1_path, img2_path,target_path))
57 | # 如果是要反向
58 | H, W = img1.shape[:2]
59 | # pad to 64
60 | img1 = np.pad(img1, ((0, (64 - H % 64) if H % 64 else 0), (0, (64 - W % 64) if H % 64 else 0), (0, 0)),
61 | mode='constant')
62 | img2 = np.pad(img2, ((0, (64 - H % 64) if H % 64 else 0), (0, (64 - W % 64) if H % 64 else 0), (0, 0)),
63 | mode='constant')
64 | target = np.pad(target, ((0, (64 - H % 64) if H % 64 else 0), (0, (64 - W % 64) if H % 64 else 0), (0, 0)),
65 | mode='constant')
66 | images = [img1, img2, target]
67 | if self.augument:
68 | cropper = StaticRandomCrop(img1.shape[:2],
69 | self.crop_shape) if self.cropper == 'random' else StaticCenterCrop(
70 | img1.shape[:2], self.crop_shape)
71 | # print(cropper)
72 | images = list(map(cropper, images))
73 | images = [torch.from_numpy( each.transpose(2, 0, 1).astype(np.float32)) * (1.0 / 255.0) for each in images]
74 |
75 | # img1 = img1.transpose(2, 0, 1).astype(np.float32) * (1.0 / 255.0)
76 | # img2 = img2.transpose(2, 0, 1).astype(np.float32) * (1.0 / 255.0)
77 | # target = target.transpose(2, 0, 1).astype(np.float32) * (1.0 / 255.0)
78 |
79 |
80 |
81 | return images
82 | # x = torch.Tensor(x).to(device)
83 |
84 | def __len__(self):
85 | return len(self.files_dir_ls)
--------------------------------------------------------------------------------