tensor2d.py 1.58 KB
Newer Older
lishj6's avatar
init  
lishj6 committed
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
# Copyright 2021 Toyota Research Institute.  All rights reserved.
import torch
import torch.nn.functional as F


def compute_features_locations(h, w, stride, dtype=torch.float32, device='cpu', offset="none"):
    """Adapted from AdelaiDet:
        https://github.com/aim-uofa/AdelaiDet/blob/master/adet/utils/comm.py

    Key differnece: offset is configurable.
    """
    shifts_x = torch.arange(0, w * stride, step=stride, dtype=dtype, device=device)
    shifts_y = torch.arange(0, h * stride, step=stride, dtype=dtype, device=device)
    shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x)
    shift_x = shift_x.reshape(-1)
    shift_y = shift_y.reshape(-1)
    # (dennis.park)
    # locations = torch.stack((shift_x, shift_y), dim=1) + stride // 2
    locations = torch.stack((shift_x, shift_y), dim=1)
    if offset == "half":
        locations += stride // 2
    else:
        assert offset == "none"

    return locations


def aligned_bilinear(tensor, factor, offset="none"):
    """Adapted from AdelaiDet:
        https://github.com/aim-uofa/AdelaiDet/blob/master/adet/utils/comm.py
    """
    assert tensor.dim() == 4
    assert factor >= 1
    assert int(factor) == factor

    if factor == 1:
        return tensor

    h, w = tensor.size()[2:]
    tensor = F.pad(tensor, pad=(0, 1, 0, 1), mode="replicate")
    oh = factor * h + 1
    ow = factor * w + 1
    tensor = F.interpolate(tensor, size=(oh, ow), mode='bilinear', align_corners=True)
    if offset == "half":
        tensor = F.pad(tensor, pad=(factor // 2, 0, factor // 2, 0), mode="replicate")

    return tensor[:, :, :oh - 1, :ow - 1]