-
Notifications
You must be signed in to change notification settings - Fork 38
/
test.py
347 lines (300 loc) · 11.4 KB
/
test.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
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
"""
Estimate optical flow on standard test datasets.
Use this script to generate the predictions to be submitted to the benchmark website.
Note that this script will only generate the flow files in the format specified by the respective benchmark. However,
additional steps may be necessary before submitting. For example, for the MPI-Sintel benchmark you need to download and run the
official bundler on the results generated by this script.
"""
# =============================================================================
# Copyright 2021 Henrique Morimitsu
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================
from pathlib import Path
import sys
from typing import Any, Dict, Optional
import cv2 as cv
from jsonargparse import ArgumentParser, Namespace
from loguru import logger
import numpy as np
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
import ptlflow
from ptlflow.data.flow_datamodule import FlowDataModule
from ptlflow.models.base_model.base_model import BaseModel
from ptlflow.utils import flow_utils
from ptlflow.utils.io_adapter import IOAdapter
from ptlflow.utils.lightning.ptlflow_cli import PTLFlowCLI
from ptlflow.utils.registry import RegisteredModel
from ptlflow.utils.utils import (
tensor_dict_to_numpy,
)
def _init_parser() -> ArgumentParser:
parser = ArgumentParser(add_help=False)
parser.add_argument(
"--ckpt_path",
type=str,
default=None,
help=("Path to a ckpt file for the chosen model."),
)
parser.add_argument(
"--output_path",
type=str,
default=str(Path("outputs/test")),
help="Path to the directory where the validation results will be saved.",
)
parser.add_argument(
"--show",
action="store_true",
help="If set, the results are shown on the screen.",
)
parser.add_argument(
"--max_forward_side",
type=int,
default=None,
help=(
"If max(height, width) of the input image is larger than this value, then the image is downscaled "
"before the forward and the outputs are bilinearly upscaled to the original resolution."
),
)
parser.add_argument(
"--scale_factor",
type=float,
default=None,
help=("Multiply the input image by this scale factor before forwarding."),
)
parser.add_argument(
"--max_show_side",
type=int,
default=1000,
help=(
"If max(height, width) of the output image is larger than this value, then the image is downscaled "
"before showing it on the screen."
),
)
parser.add_argument("--save_viz", action="store_true")
return parser
def generate_outputs(
args: Namespace,
inputs: Dict[str, torch.Tensor],
preds: Dict[str, torch.Tensor],
dataloader_name: str,
batch_idx: int,
metadata: Optional[Dict[str, Any]] = None,
) -> None:
"""Display on screen and/or save outputs to disk, if required.
Parameters
----------
args : Namespace
The arguments with the required values to manage the outputs.
inputs : Dict[str, torch.Tensor]
The inputs loaded from the dataset (images, groundtruth).
preds : Dict[str, torch.Tensor]
The model predictions (optical flow and others).
dataloader_name : str
A string to identify from which dataloader these inputs came from.
batch_idx : int
Indicates in which position of the loader this input is.
metadata : Dict[str, Any], optional
Metadata about this input, if available.
"""
inputs = tensor_dict_to_numpy(inputs)
preds = tensor_dict_to_numpy(preds)
preds["flows_viz"] = flow_utils.flow_to_rgb(preds["flows"])[:, :, ::-1]
if preds.get("flows_b") is not None:
preds["flows_b_viz"] = flow_utils.flow_to_rgb(preds["flows_b"])[:, :, ::-1]
_write_to_file(args, preds, dataloader_name, batch_idx, metadata)
if args.show:
_show(inputs, preds, args.max_show_side)
def test(args: Namespace, model: BaseModel, data_module: FlowDataModule) -> None:
"""Run predictions on the test dataset.
Parameters
----------
args : Namespace
Arguments to configure the model and the test.
model : BaseModel
The model to be used for testing.
See Also
--------
ptlflow.models.base_model.base_model.BaseModel : The parent class of the available models.
"""
model.eval()
if torch.cuda.is_available():
model = model.cuda()
dataloaders = data_module.test_dataloader()
dataloaders = {
data_module.test_dataloader_names[i]: dataloaders[i]
for i in range(len(dataloaders))
}
for i, (dataset_name, dl) in enumerate(dataloaders.items()):
test_one_dataloader(args, model, dl, i, dataset_name)
@torch.no_grad()
def test_one_dataloader(
args: Namespace,
model: BaseModel,
dataloader: DataLoader,
dataloader_idx: int,
dataloader_name: str,
) -> None:
"""Perform predictions for all examples of one test dataloader.
Parameters
----------
args : Namespace
Arguments to configure the model and the validation.
model : BaseModel
The model to be used for validation.
dataloader : DataLoader
The dataloader for the validation.
dataloader_idx : int
The index of this dataloader.
dataloader_name : str
A string to identify this dataloader.
"""
prev_preds = None
for i, inputs in enumerate(tqdm(dataloader)):
if args.scale_factor is not None:
scale_factor = args.scale_factor
else:
scale_factor = (
None
if args.max_forward_side is None
else float(args.max_forward_side) / min(inputs["images"].shape[-2:])
)
io_adapter = IOAdapter(
model.output_stride,
inputs["images"].shape[-2:],
target_scale_factor=scale_factor,
cuda=torch.cuda.is_available(),
)
inputs = io_adapter.prepare_inputs(inputs=inputs)
inputs["prev_preds"] = prev_preds
preds = model.test_step(inputs, i, dataloader_idx)
inputs = io_adapter.unscale(inputs)
preds = io_adapter.unscale(preds)
generate_outputs(args, inputs, preds, dataloader_name, i, inputs.get("meta"))
def _show(
inputs: Dict[str, np.ndarray], preds: Dict[str, np.ndarray], max_show_side: int
) -> None:
for k, v in inputs.items():
if isinstance(v, np.ndarray) and (
len(v.shape) == 2 or v.shape[2] == 1 or v.shape[2] == 3
):
if max(v.shape[:2]) > max_show_side:
scale_factor = float(max_show_side) / max(v.shape[:2])
v = cv.resize(
v, (int(scale_factor * v.shape[1]), int(scale_factor * v.shape[0]))
)
cv.imshow(k, v)
for k, v in preds.items():
if isinstance(v, np.ndarray) and (
len(v.shape) == 2 or v.shape[2] == 1 or v.shape[2] == 3
):
if max(v.shape[:2]) > max_show_side:
scale_factor = float(max_show_side) / max(v.shape[:2])
v = cv.resize(
v, (int(scale_factor * v.shape[1]), int(scale_factor * v.shape[0]))
)
cv.imshow("pred_" + k, v)
cv.waitKey(1)
def _write_to_file(
args: Namespace,
preds: Dict[str, np.ndarray],
dataloader_name: str,
batch_idx: int,
metadata: Optional[Dict[str, Any]] = None,
) -> None:
out_root_dir = Path(args.output_path)
out_viz_root_dir = out_root_dir / "viz"
dataloader_tokens = dataloader_name.split("-")
if dataloader_tokens[0] == "kitti":
out_root_dir /= f"{dataloader_tokens[0]}{dataloader_tokens[1]}"
out_viz_root_dir /= f"{dataloader_tokens[0]}{dataloader_tokens[1]}"
flow_ext = "png"
elif dataloader_tokens[0] == "sintel":
out_root_dir = out_root_dir / dataloader_tokens[0] / dataloader_tokens[1]
out_viz_root_dir = (
out_viz_root_dir / dataloader_tokens[0] / dataloader_tokens[1]
)
flow_ext = "flo"
elif dataloader_tokens[0] == "spring":
out_root_dir = out_root_dir / dataloader_tokens[0]
out_viz_root_dir = out_viz_root_dir / dataloader_tokens[0]
flow_ext = "flo5"
extra_dirs = ""
if metadata is not None:
img_path = Path(metadata["image_paths"][0][0])
image_name = img_path.stem
if "kitti-2015" in dataloader_name:
extra_dirs = "flow"
elif "sintel" in dataloader_name:
seq_name = img_path.parts[-2]
extra_dirs = seq_name
elif "spring" in dataloader_name:
if "revonly" in dataloader_tokens:
direc = "BW"
else:
direc = "FW"
side, idx = img_path.stem.split("_")[-2:]
extra_dirs = f"{img_path.parts[-3]}/flow_{direc}_{side}"
image_name = f"flow_{direc}_{side}_{idx}"
else:
image_name = f"{batch_idx:08d}"
out_dir = out_root_dir / extra_dirs
out_dir.mkdir(parents=True, exist_ok=True)
flow_utils.flow_write(out_dir / f"{image_name}.{flow_ext}", preds["flows"])
if args.save_viz:
out_viz_dir = out_viz_root_dir / extra_dirs
out_viz_dir.mkdir(parents=True, exist_ok=True)
flow_viz = flow_utils.flow_to_rgb(preds["flows"])
viz_path = out_viz_dir / f"{image_name}.png"
cv.imwrite(str(viz_path), flow_viz[:, :, ::-1])
def _show_v04_warning():
ignore_args = ["-h", "--help", "--model", "--config"]
for arg in ignore_args:
if arg in sys.argv:
return
logger.warning(
"Since v0.4, it is now necessary to inform the model using the --model argument. For example, use: python infer.py --model raft --ckpt_path things"
)
if __name__ == "__main__":
_show_v04_warning()
parser = _init_parser()
cli = PTLFlowCLI(
model_class=RegisteredModel,
subclass_mode_model=True,
datamodule_class=FlowDataModule,
parser_kwargs={"parents": [parser]},
run=False,
parse_only=False,
auto_configure_optimizers=False,
)
datamodule = cli.datamodule
datamodule.setup("test")
cfg = cli.config
cfg.model_name = cfg.model.class_path.split(".")[-1]
model_id = cfg.model_name
if cfg.ckpt_path is not None:
model_id += f"_{Path(cfg.ckpt_path).stem}"
if cfg.max_forward_side is not None:
model_id += f"_maxside{cfg.max_forward_side}"
if cfg.scale_factor is not None:
model_id += f"_scale{cfg.scale_factor}"
if cfg.model.init_args.warm_start:
model_id += f"_warm"
cfg.output_path = str(Path(cfg.output_path) / model_id)
Path(cfg.output_path).mkdir(parents=True, exist_ok=True)
logger.info("The outputs will be saved to {}.", cfg.output_path)
model = cli.model
model = ptlflow.restore_model(model, cfg.ckpt_path)
metrics_df = test(cfg, model, datamodule)