This repository was archived by the owner on Jan 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 542
/
Copy pathupsample.py
53 lines (42 loc) · 1.8 KB
/
upsample.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
class BilinearInterpolation2d(nn.Module):
"""Bilinear interpolation in space of scale.
Takes input of NxKxHxW and outputs NxKx(sH)x(sW), where s:= up_scale
Adapted from the CVPR'15 FCN code.
See: https://github.com/shelhamer/fcn.berkeleyvision.org/blob/master/surgery.py
"""
def __init__(self, in_channels, out_channels, up_scale):
super(BilinearInterpolation2d, self).__init__()
assert in_channels == out_channels
assert up_scale % 2 == 0, 'Scale should be even'
self.in_channes = in_channels
self.out_channels = out_channels
self.up_scale = int(up_scale)
self.padding = up_scale // 2
def upsample_filt(size):
factor = (size + 1) // 2
if size % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = np.ogrid[:size, :size]
return ((1 - abs(og[0] - center) / factor) *
(1 - abs(og[1] - center) / factor))
kernel_size = up_scale * 2
bil_filt = upsample_filt(kernel_size)
kernel = np.zeros(
(in_channels, out_channels, kernel_size, kernel_size), dtype=np.float32
)
kernel[range(in_channels), range(out_channels), :, :] = bil_filt
self.upconv = nn.ConvTranspose2d(in_channels, out_channels, kernel_size,
stride=self.up_scale, padding=self.padding)
self.upconv.weight.data.copy_(torch.from_numpy(kernel))
self.upconv.bias.data.fill_(0)
self.upconv.weight.requires_grad = False
self.upconv.bias.requires_grad = False
def forward(self, x):
return self.upconv(x)