File size: 9,372 Bytes
fc16538
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# TRI-VIDAR - Copyright 2022 Toyota Research Institute.  All rights reserved.

from copy import deepcopy

import cv2
import numpy as np
import torch
import torchvision.transforms as transforms
from torchvision.transforms import InterpolationMode

from vidar.utils.data import keys_with
from vidar.utils.decorators import iterate1
from vidar.utils.types import is_seq


@iterate1
def resize_pil(image, shape, interpolation=InterpolationMode.LANCZOS):
    """
    Resizes input image

    Parameters
    ----------
    image : Image PIL
        Input image
    shape : Tuple
        Output shape [H,W]
    interpolation : Int
        Interpolation mode

    Returns
    -------
    image : Image PIL
        Resized image
    """
    transform = transforms.Resize(shape, interpolation=interpolation)
    return transform(image)


@iterate1
def resize_npy(depth, shape, expand=True):
    """
    Resizes depth map

    Parameters
    ----------
    depth : np.Array
        Depth map [h,w]
    shape : Tuple
        Output shape (H,W)
    expand : Bool
        Expand output to [H,W,1]

    Returns
    -------
    depth : np.Array
        Resized depth map [H,W]
    """
    # If a single number is provided, use resize ratio
    if not is_seq(shape):
        shape = tuple(int(s * shape) for s in depth.shape)
    # Resize depth map
    depth = cv2.resize(depth, dsize=tuple(shape[::-1]), interpolation=cv2.INTER_NEAREST)
    # Return resized depth map
    return np.expand_dims(depth, axis=2) if expand else depth


@iterate1
def resize_npy_preserve(depth, shape):
    """
    Resizes depth map preserving all valid depth pixels
    Multiple downsampled points can be assigned to the same pixel.

    Parameters
    ----------
    depth : np.Array
        Depth map [h,w]
    shape : Tuple
        Output shape (H,W)

    Returns
    -------
    depth : np.Array
        Resized depth map [H,W,1]
    """
    # If a single number is provided, use resize ratio
    if not is_seq(shape):
        shape = tuple(int(s * shape) for s in depth.shape)
    # Store dimensions and reshapes to single column
    depth = np.squeeze(depth)
    h, w = depth.shape
    x = depth.reshape(-1)
    # Create coordinate grid
    uv = np.mgrid[:h, :w].transpose(1, 2, 0).reshape(-1, 2)
    # Filters valid points
    idx = x > 0
    crd, val = uv[idx], x[idx]
    # Downsamples coordinates
    crd[:, 0] = (crd[:, 0] * (shape[0] / h)).astype(np.int32)
    crd[:, 1] = (crd[:, 1] * (shape[1] / w)).astype(np.int32)
    # Filters points inside image
    idx = (crd[:, 0] < shape[0]) & (crd[:, 1] < shape[1])
    crd, val = crd[idx], val[idx]
    # Creates downsampled depth image and assigns points
    depth = np.zeros(shape)
    depth[crd[:, 0], crd[:, 1]] = val
    # Return resized depth map
    return np.expand_dims(depth, axis=2)


@iterate1
def resize_torch_preserve(depth, shape):
    """
    Resizes depth map preserving all valid depth pixels
    Multiple downsampled points can be assigned to the same pixel.

    Parameters
    ----------
    depth : torch.Tensor
        Depth map [B,1,h,w]
    shape : Tuple
        Output shape (H,W)

    Returns
    -------
    depth : torch.Tensor
        Resized depth map [B,1,H,W]
    """
    if depth.dim() == 4:
        return torch.stack([resize_torch_preserve(depth[i], shape)
                            for i in range(depth.shape[0])], 0)
    # If a single number is provided, use resize ratio
    if not is_seq(shape):
        shape = tuple(int(s * shape) for s in depth.shape)
    # Store dimensions and reshapes to single column
    c, h, w = depth.shape
    # depth = np.squeeze(depth)
    # h, w = depth.shape
    x = depth.reshape(-1)
    # Create coordinate grid
    uv = np.mgrid[:h, :w].transpose(1, 2, 0).reshape(-1, 2)
    # Filters valid points
    idx = x > 0
    crd, val = uv[idx], x[idx]
    # Downsamples coordinates
    crd[:, 0] = (crd[:, 0] * (shape[0] / h)).astype(np.int32)
    crd[:, 1] = (crd[:, 1] * (shape[1] / w)).astype(np.int32)
    # Filters points inside image
    idx = (crd[:, 0] < shape[0]) & (crd[:, 1] < shape[1])
    crd, val = crd[idx], val[idx]
    # Creates downsampled depth image and assigns points
    depth = torch.zeros(shape, device=depth.device, dtype=depth.dtype)
    depth[crd[:, 0], crd[:, 1]] = val
    # Return resized depth map
    return depth.unsqueeze(0)


@iterate1
def resize_npy_multiply(data, shape):
    """Resize a numpy array and scale its content accordingly"""
    ratio_w = shape[0] / data.shape[0]
    ratio_h = shape[1] / data.shape[1]
    out = resize_npy(data, shape, expand=False)
    out[..., 0] *= ratio_h
    out[..., 1] *= ratio_w
    return out


@iterate1
def resize_intrinsics(intrinsics, original, resized):
    """
    Resize camera intrinsics matrix to match a target resolution

    Parameters
    ----------
    intrinsics : np.Array
        Original intrinsics matrix [3,3]
    original : Tuple
        Original image resolution [W,H]
    resized : Tuple
        Target image resolution [w,h]
    Returns
    -------
    intrinsics : np.Array
        Resized intrinsics matrix [3,3]
    """
    intrinsics = np.copy(intrinsics)
    intrinsics[0] *= resized[0] / original[0]
    intrinsics[1] *= resized[1] / original[1]
    return intrinsics


@iterate1
def resize_sample_input(sample, shape, shape_supervision=None,
                        depth_downsample=1.0, preserve_depth=False,
                        pil_interpolation=InterpolationMode.LANCZOS):
    """
    Resizes the input information of a sample

    Parameters
    ----------
    sample : Dict
        Dictionary with sample values
    shape : tuple (H,W)
        Output shape
    shape_supervision : Tuple
        Output supervision shape (H,W)
    depth_downsample: Float
        Resize ratio for depth maps
    preserve_depth : Bool
        Preserve depth maps when resizing
    pil_interpolation : Int
        Interpolation mode

    Returns
    -------
    sample : Dict
        Resized sample
    """
    # Intrinsics
    for key in keys_with(sample, 'intrinsics', without='raw'):
        if f'raw_{key}' not in sample.keys():
            sample[f'raw_{key}'] = deepcopy(sample[key])
        sample[key] = resize_intrinsics(sample[key], list(sample['rgb'].values())[0].size, shape[::-1])
    # RGB
    for key in keys_with(sample, 'rgb', without='raw'):
        sample[key] = resize_pil(sample[key], shape, interpolation=pil_interpolation)
    # Mask
    for key in keys_with(sample, 'mask', without='raw'):
        sample[key] = resize_pil(sample[key], shape, interpolation=InterpolationMode.NEAREST)
    # Input depth
    for key in keys_with(sample, 'input_depth'):
        shape_depth = [int(s * depth_downsample) for s in shape]
        resize_npy_depth = resize_npy_preserve if preserve_depth else resize_npy
        sample[key] = resize_npy_depth(sample[key], shape_depth)
    return sample


@iterate1
def resize_sample_supervision(sample, shape, depth_downsample=1.0, preserve_depth=False):
    """
    Resizes the output information of a sample

    Parameters
    ----------
    sample : Dict
        Dictionary with sample values
    shape : Tuple
        Output shape (H,W)
    depth_downsample: Float
        Resize ratio for depth maps
    preserve_depth : Bool
        Preserve depth maps when resizing

    Returns
    -------
    sample : Dict
        Resized sample
    """
    # Depth
    for key in keys_with(sample, 'depth', without='input_depth'):
        shape_depth = [int(s * depth_downsample) for s in shape]
        resize_npy_depth = resize_npy_preserve if preserve_depth else resize_npy
        sample[key] = resize_npy_depth(sample[key], shape_depth)
    # Semantic
    for key in keys_with(sample, 'semantic'):
        sample[key] = resize_npy(sample[key], shape, expand=False)
    # Optical flow
    for key in keys_with(sample, 'optical_flow'):
        sample[key] = resize_npy_multiply(sample[key], shape)
    # Scene flow
    for key in keys_with(sample, 'scene_flow'):
        sample[key] = resize_npy(sample[key], shape, expand=False)
    # Return resized sample
    return sample


def resize_sample(sample, shape, shape_supervision=None, depth_downsample=1.0, preserve_depth=False,
                  pil_interpolation=InterpolationMode.LANCZOS):
    """
    Resizes a sample, including image, intrinsics and depth maps.

    Parameters
    ----------
    sample : Dict
        Dictionary with sample values
    shape : Tuple
        Output shape (H,W)
    shape_supervision : Tuple
        Output shape (H,W)
    depth_downsample: Float
        Resize ratio for depth maps
    preserve_depth : Bool
        Preserve depth maps when resizing
    pil_interpolation : Int
        Interpolation mode

    Returns
    -------
    sample : Dict
        Resized sample
    """
    # Resize input information
    sample = resize_sample_input(sample, shape,
                                 depth_downsample=depth_downsample,
                                 preserve_depth=preserve_depth,
                                 pil_interpolation=pil_interpolation)
    # Resize output information
    sample = resize_sample_supervision(sample, shape_supervision,
                                       depth_downsample=depth_downsample,
                                       preserve_depth=preserve_depth)
    # Return resized sample
    return sample