Repository navigation
Expand file tree
/
Copy pathdota_task1_submit.py
More file actions
268 lines (241 loc) · 9.56 KB
/
Copy pathdota_task1_submit.py
File metadata and controls
268 lines (241 loc) · 9.56 KB
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
#!/usr/bin/env python3
"""Build a DOTA v1.0 Task 1 zip from ``predictions.json``, a training run, or Hub zoo weights.
Usage:
odet dota-submit --from-json predictions/<ts>/predictions.json --output-dir work_dirs/Task1
odet dota-submit --checkpoint hf://oriented_rcnn_dota_le90_3x \\
--test-dir /path/to/data/DOTA-v1.0/test --output-dir work_dirs/Task1
odet dota-submit --experiment-dir runs/oriented_rcnn/<id> --test-dir /path/to/data/DOTA-v1.0/test \\
--output-dir work_dirs/Task1
Official test labels are not public. Upload the zip to the DOTA v1.0 Task 1 server.
This path uses sliding-window inference on full images: last tiles flush to the
image edge (same as ``tile_dota.py``) and overlap copies are kept, then NMS
(ResultMerge-style). It is not MMRotate's on-disk pre-tile merge.
Pass ``--resize-rates 0.5,1.0,1.5`` for live multiscale Task 1 (resize → windows
per rate with overlap 500 by default → map boxes back → one NMS 0.1).
"""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
from typing import List, Optional
_REPO_ROOT = Path(__file__).resolve().parent.parent
if str(_REPO_ROOT) not in sys.path:
sys.path.insert(0, str(_REPO_ROOT))
from oriented_det.data.dota_classes import DOTA_V1_CLASSES
from oriented_det.data.dota_task1 import write_task1_submission
def _resolve_predictions_json(from_json: Path) -> Path:
if from_json.is_dir():
candidate = from_json / "predictions.json"
if not candidate.is_file():
raise FileNotFoundError(f"No predictions.json in {from_json}")
return candidate
if not from_json.is_file():
raise FileNotFoundError(f"predictions JSON not found: {from_json}")
return from_json
def _predictions_json_from_run(meta: dict, output_dir: str | None = None) -> Path:
"""Locate ``predictions.json`` after ``run_inference_and_save``.
Older metadata dicts omitted ``output_dir``; prefer ``predictions_json`` then
``output_dir`` then the directory we passed in.
"""
raw = meta.get("predictions_json")
if raw:
path = Path(raw)
if path.is_file():
return path
for key in ("output_dir", "output_directory"):
raw = meta.get(key)
if raw:
path = Path(raw) / "predictions.json"
if path.is_file():
return path
if output_dir:
path = Path(output_dir) / "predictions.json"
if path.is_file():
return path
raise FileNotFoundError(
"Inference did not write predictions.json "
f"(meta keys={sorted(meta)}, output_dir={output_dir!r})"
)
def _official_unlabeled_test_dir(test_dir: str | None, data_root: str | None) -> str:
"""Task 1 images. Never ``dataset.test_tiles_dir`` (DOTA points that at leaky val)."""
if test_dir:
return test_dir
if not data_root:
raise ValueError(
"dota-submit needs --test-dir or --data-root for unlabeled official test images. "
"dataset.test_tiles_dir is the labeled test_map split, not Task 1."
)
return str(Path(data_root) / "test")
def _run_test_preds(
*,
experiment_dir: str | None,
checkpoint: str | None,
config_path: str | None,
data_root: str | None,
test_dir: str | None,
output_dir: str | None,
window_margin_pixels: float = 0.0,
resize_rates: Optional[List[float]] = None,
overlap_pixels: Optional[int] = None,
) -> Path:
from tools.save_predictions import resolve_preds_model_paths, run_inference_and_save
test_dir = _official_unlabeled_test_dir(test_dir, data_root)
exp_dir, ckpt, cfg = resolve_preds_model_paths(
experiment_dir=experiment_dir,
checkpoint=checkpoint,
config_path=config_path,
auto_detect=False,
)
# Hub sidecars often still have production.final_nms_iou_threshold 0.5; Task 1 / eval-val is 0.1.
# window_margin_pixels=0 keeps overlap copies, then NMS (ResultMerge-style).
# With resize_rates, save_predictions defaults overlap to 500 (MS train convention).
meta = run_inference_and_save(
experiment_dir=exp_dir,
checkpoint_path=ckpt,
config_path=cfg,
data_root=data_root,
output_dir=output_dir,
data_split="test",
test_dir=test_dir,
nms_threshold=0.1,
window_margin_pixels=window_margin_pixels,
resize_rates=resize_rates,
overlap_pixels=overlap_pixels,
run_diagnostics=False,
)
return _predictions_json_from_run(meta, output_dir)
def main(argv: list[str] | None = None) -> None:
parser = argparse.ArgumentParser(
description="Write DOTA v1.0 Task 1 txt files + zip for the official evaluation server."
)
parser.add_argument(
"--from-json",
type=Path,
default=None,
help="predictions.json or a directory that contains it.",
)
parser.add_argument(
"--experiment-dir",
type=str,
default=None,
help="If --from-json is omitted, run odet-preds on unlabeled test images from this run.",
)
parser.add_argument(
"--checkpoint",
type=str,
default=None,
help="Hub slug (hf://oriented_rcnn_dota_le90_3x) or .pth. Sidecar JSON is used if --config is omitted.",
)
parser.add_argument(
"--config",
type=str,
default=None,
help="Config JSON (optional with Hub slugs; pretrained sidecar is used).",
)
parser.add_argument(
"--data-root",
type=str,
default=None,
help="DOTA root (used when config has no dataset.data_root, or to override a Hub sidecar placeholder).",
)
parser.add_argument(
"--test-dir",
type=str,
default=None,
help="Unlabeled test images (test/ or test/images/). Default: data_root/test.",
)
parser.add_argument(
"--output-dir",
type=Path,
required=True,
help="Directory for Task1_*.txt (created). Zip is written beside it unless --zip is set.",
)
parser.add_argument(
"--zip",
dest="zip_path",
type=Path,
default=None,
help="Zip path (default: <output-dir>.zip next to the txt directory).",
)
parser.add_argument(
"--no-dummy",
action="store_true",
help="Do not write a dummy line for classes with zero detections (server may reject empty files).",
)
parser.add_argument(
"--preds-output-dir",
type=str,
default=None,
help="When running inference, write predictions.json here (default: predictions/<timestamp>/).",
)
parser.add_argument(
"--window-margin-pixels",
type=float,
default=0.0,
help="Per-window centroid margin before merge (default 0: keep overlap copies, then NMS). "
"Pass a positive value (e.g. overlap/2) to drop the interior overlap band.",
)
parser.add_argument(
"--resize-rates",
type=str,
default=None,
help="Comma-separated multiscale rates (e.g. 0.5,1.0,1.5). Live MS Task 1: "
"resize → windows per rate → map boxes back → one NMS. Default overlap 500.",
)
parser.add_argument(
"--overlap-pixels",
type=int,
default=None,
help="Sliding-window overlap per axis. With --resize-rates, default is 500 "
"(MS train / Ultralytics gap=500 base). SS default remains config/200.",
)
args = parser.parse_args(argv)
if args.from_json is None and not args.experiment_dir and not args.checkpoint:
parser.error("Provide --from-json, --checkpoint (hf://<slug>), or --experiment-dir")
if args.from_json is None and not args.test_dir and not args.data_root:
parser.error(
"Pass --test-dir (e.g. /path/to/data/DOTA-v1.0/test) or --data-root "
"(official test images under <root>/test). dataset.test_tiles_dir is the "
"labeled test_map split (DOTA: leaky val tiles), not Task 1."
)
from oriented_det.runtime.inference import parse_resize_rates
rates = parse_resize_rates(args.resize_rates)
if args.from_json is not None:
pred_json = _resolve_predictions_json(args.from_json)
else:
pred_json = _run_test_preds(
experiment_dir=args.experiment_dir,
checkpoint=args.checkpoint,
config_path=args.config,
data_root=args.data_root,
test_dir=args.test_dir,
output_dir=args.preds_output_dir,
window_margin_pixels=args.window_margin_pixels,
resize_rates=rates,
overlap_pixels=args.overlap_pixels,
)
print(f"Wrote predictions: {pred_json}")
zip_path = write_task1_submission(
pred_json,
args.output_dir,
class_names=DOTA_V1_CLASSES,
dummy_if_empty=not args.no_dummy,
zip_path=args.zip_path,
)
n_files = len(list(args.output_dir.glob("Task1_*.txt")))
print(f"Wrote {n_files} Task1_*.txt under {args.output_dir}")
print(f"Zip: {zip_path}")
print("Upload to https://captain-whu.github.io/DOTA/evaluation.html (DOTA-v1.0 Task 1).")
if rates is not None:
print(
f"Note: live MS rates [{', '.join(f'{r:g}' for r in rates)}]; "
"overlap default 500 in resized space; boxes mapped to original; NMS 0.1 "
"(not MMRotate on-disk pre-tile merge)."
)
else:
print(
"Note: last tiles flush to the image edge; overlap copies kept, then NMS 0.1 "
"(live sliding-window ResultMerge-style, not MMRotate on-disk pre-tile merge)."
)
if __name__ == "__main__":
main()