| 33 | |
| 34 | |
| 35 | class DepthModel(nn.Module): |
| 36 | def __init__(self): |
| 37 | super().__init__() |
| 38 | self.device = 'cpu' |
| 39 | |
| 40 | def to(self, device) -> nn.Module: |
| 41 | self.device = device |
| 42 | return super().to(device) |
| 43 | |
| 44 | def forward(self, x, *args, **kwargs): |
| 45 | raise NotImplementedError |
| 46 | |
| 47 | def _infer(self, x: torch.Tensor): |
| 48 | """ |
| 49 | Inference interface for the model |
| 50 | Args: |
| 51 | x (torch.Tensor): input tensor of shape (b, c, h, w) |
| 52 | Returns: |
| 53 | torch.Tensor: output tensor of shape (b, 1, h, w) |
| 54 | """ |
| 55 | return self(x)['metric_depth'] |
| 56 | |
| 57 | def _infer_with_pad_aug(self, x: torch.Tensor, pad_input: bool=True, fh: float=3, fw: float=3, upsampling_mode: str='bicubic', padding_mode="reflect", **kwargs) -> torch.Tensor: |
| 58 | """ |
| 59 | Inference interface for the model with padding augmentation |
| 60 | Padding augmentation fixes the boundary artifacts in the output depth map. |
| 61 | Boundary artifacts are sometimes caused by the fact that the model is trained on NYU raw dataset which has a black or white border around the image. |
| 62 | This augmentation pads the input image and crops the prediction back to the original size / view. |
| 63 | |
| 64 | Note: This augmentation is not required for the models trained with 'avoid_boundary'=True. |
| 65 | Args: |
| 66 | x (torch.Tensor): input tensor of shape (b, c, h, w) |
| 67 | pad_input (bool, optional): whether to pad the input or not. Defaults to True. |
| 68 | fh (float, optional): height padding factor. The padding is calculated as sqrt(h/2) * fh. Defaults to 3. |
| 69 | fw (float, optional): width padding factor. The padding is calculated as sqrt(w/2) * fw. Defaults to 3. |
| 70 | upsampling_mode (str, optional): upsampling mode. Defaults to 'bicubic'. |
| 71 | padding_mode (str, optional): padding mode. Defaults to "reflect". |
| 72 | Returns: |
| 73 | torch.Tensor: output tensor of shape (b, 1, h, w) |
| 74 | """ |
| 75 | # assert x is nchw and c = 3 |
| 76 | assert x.dim() == 4, "x must be 4 dimensional, got {}".format(x.dim()) |
| 77 | assert x.shape[1] == 3, "x must have 3 channels, got {}".format(x.shape[1]) |
| 78 | |
| 79 | if pad_input: |
| 80 | assert fh > 0 or fw > 0, "atlease one of fh and fw must be greater than 0" |
| 81 | pad_h = int(np.sqrt(x.shape[2]/2) * fh) |
| 82 | pad_w = int(np.sqrt(x.shape[3]/2) * fw) |
| 83 | padding = [pad_w, pad_w] |
| 84 | if pad_h > 0: |
| 85 | padding += [pad_h, pad_h] |
| 86 | |
| 87 | x = F.pad(x, padding, mode=padding_mode, **kwargs) |
| 88 | out = self._infer(x) |
| 89 | if out.shape[-2:] != x.shape[-2:]: |
| 90 | out = F.interpolate(out, size=(x.shape[2], x.shape[3]), mode=upsampling_mode, align_corners=False) |
| 91 | if pad_input: |
| 92 | # crop to the original size, handling the case where pad_h and pad_w is 0 |
nothing calls this directly
no outgoing calls
no test coverage detected