AhmedLabib1 commited on
Commit
d301b87
·
verified ·
1 Parent(s): bc4eb4b

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +2 -0
  2. LICENSE +21 -0
  3. MODEL_ZOO.md +123 -0
  4. README.md +150 -0
  5. UNOTC.sh +17 -0
  6. experiments/stark_lightning_X_trt/baseline_rephead_4_lite_search5.yaml +84 -0
  7. experiments/stark_s/baseline.yaml +85 -0
  8. experiments/stark_s/baseline_got10k_only.yaml +79 -0
  9. experiments/stark_st1/baseline.yaml +81 -0
  10. experiments/stark_st1/baseline_R101.yaml +81 -0
  11. experiments/stark_st1/baseline_R101_got10k_only.yaml +75 -0
  12. experiments/stark_st1/baseline_got10k_only.yaml +75 -0
  13. experiments/stark_st2/baseline.yaml +92 -0
  14. experiments/stark_st2/baseline_R101.yaml +92 -0
  15. experiments/stark_st2/baseline_R101_got10k_only.yaml +80 -0
  16. experiments/stark_st2/baseline_got10k_only.yaml +80 -0
  17. external/AR/README.md +42 -0
  18. external/AR/ltr/README.md +75 -0
  19. external/AR/ltr/__init__.py +3 -0
  20. external/AR/ltr/actors/__init__.py +3 -0
  21. external/AR/ltr/actors/base_actor.py +44 -0
  22. external/AR/ltr/actors/bbreg.py +58 -0
  23. external/AR/ltr/actors/tracking.py +193 -0
  24. external/AR/ltr/admin/__init__.py +0 -0
  25. external/AR/ltr/admin/environment.py +53 -0
  26. external/AR/ltr/admin/loading.py +150 -0
  27. external/AR/ltr/admin/model_constructor.py +45 -0
  28. external/AR/ltr/admin/multigpu.py +15 -0
  29. external/AR/ltr/admin/settings.py +13 -0
  30. external/AR/ltr/admin/stats.py +71 -0
  31. external/AR/ltr/admin/tensorboard.py +28 -0
  32. external/AR/ltr/data/__init__.py +1 -0
  33. external/AR/ltr/data/bounding_box_utils.py +94 -0
  34. external/AR/ltr/data/image_loader.py +103 -0
  35. external/AR/ltr/data/loader.py +190 -0
  36. external/AR/ltr/data/processing.py +662 -0
  37. external/AR/ltr/data/processing_utils.py +627 -0
  38. external/AR/ltr/data/processing_utils_SE.py +450 -0
  39. external/AR/ltr/data/sampler.py +189 -0
  40. external/AR/ltr/data/transforms.py +440 -0
  41. external/AR/ltr/dataset/__init__.py +15 -0
  42. external/AR/ltr/dataset/base_image_dataset.py +92 -0
  43. external/AR/ltr/dataset/base_video_dataset.py +109 -0
  44. external/AR/ltr/dataset/coco.py +156 -0
  45. external/AR/ltr/dataset/coco_seq.py +168 -0
  46. external/AR/ltr/dataset/davis.py +83 -0
  47. external/AR/ltr/dataset/ecssd.py +84 -0
  48. external/AR/ltr/dataset/got10k.py +183 -0
  49. external/AR/ltr/dataset/hku_is.py +90 -0
  50. external/AR/ltr/dataset/imagenetvid.py +161 -0
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ external/STARK-ExtreMart.pdf filter=lfs diff=lfs merge=lfs -text
37
+ tracking/Framework.png filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2021 Multimedia Research
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
MODEL_ZOO.md ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # STARK Model Zoo
2
+
3
+ Here we provide the performance of the STARK trackers on multiple tracking benchmarks and the corresponding raw results.
4
+ The model weights and the corresponding training logs are also given by the links.
5
+
6
+ ## Tracking
7
+ ### Models & Logs
8
+
9
+ <table>
10
+ <tr>
11
+ <th>Model</th>
12
+ <th>LaSOT<br>AUC (%)</th>
13
+ <th>GOT-10k<br>AO (%)</th>
14
+ <th>TrackingNet<br>AUC (%)</th>
15
+ <th>VOT2020<br>EAO</th>
16
+ <th>VOT2020-LT<br>F-score (%)</th>
17
+ <th>Models</th>
18
+ <th>Logs</th>
19
+ <th>Logs(GOT10K)</th>
20
+ </tr>
21
+ <tr>
22
+ <td>STARK-S50</td>
23
+ <td>65.8</td>
24
+ <td>67.2</td>
25
+ <td>80.3</td>
26
+ <td>0.462</td>
27
+ <td>-</td>
28
+ <td><a href="https://drive.google.com/drive/folders/1144cEuF_yn9UwTfrSVl5wmaMK3F92q42?usp=sharing">model</a></td>
29
+ <td><a href="https://drive.google.com/file/d/1_YI0CX52vg8zN6hWsYK22_78FXPiukdv/view?usp=sharing">log</a></td>
30
+ <td><a href="https://drive.google.com/file/d/1xLUeV9I9tejT4eYd1mYpeB_AsndiaJNI/view?usp=sharing">log</a></td>
31
+ </tr>
32
+ <tr>
33
+ <td>STARK-ST50</td>
34
+ <td>66.4</td>
35
+ <td>68.0</td>
36
+ <td>81.3</td>
37
+ <td>0.505</td>
38
+ <td>70.2</td>
39
+ <td><a href="https://drive.google.com/drive/folders/1fSgll53ZnVKeUn22W37Nijk-b9LGhMdN?usp=sharing">model</a></td>
40
+ <td><a href="https://drive.google.com/drive/folders/1RcPoBxI1_E6U9s5Y6BEhQH_ov-sT7SJM?usp=sharing">log</a></td>
41
+ <td><a href="https://drive.google.com/drive/folders/13guPF1MUOaRa09_4y_K9do9yhQsC_y_y?usp=sharing">log</a></td>
42
+ </tr>
43
+ <tr>
44
+ <td>STARK-ST101</td>
45
+ <td>67.1</td>
46
+ <td>68.8</td>
47
+ <td>82.0</td>
48
+ <td>0.497</td>
49
+ <td>70.1</td>
50
+ <td><a href="https://drive.google.com/drive/folders/1fSgll53ZnVKeUn22W37Nijk-b9LGhMdN?usp=sharing">model</a></td>
51
+ <td><a href="https://drive.google.com/drive/folders/1nTDRfG0K0w2XiP5RDrYJXhotUYQJBNoY?usp=sharing">log</a></td>
52
+ <td><a href="https://drive.google.com/drive/folders/1PR6PRdARHFKBDSjoqeO7qxx9y87AZWSD?usp=sharing">log</a></td>
53
+ </tr>
54
+
55
+
56
+ </table>
57
+
58
+ The downloaded checkpoints should be organized in the following structure
59
+ ```
60
+ ${STARK_ROOT}
61
+ -- checkpoints
62
+ -- train
63
+ -- stark_s
64
+ -- baseline
65
+ STARKS_ep0500.pth.tar
66
+ -- baseline_got10k_only
67
+ STARKS_ep0500.pth.tar
68
+ -- stark_st2
69
+ -- baseline
70
+ STARKST_ep0050.pth.tar
71
+ -- baseline_got10k_only
72
+ STARKST_ep0050.pth.tar
73
+ -- baseline_R101
74
+ STARKST_ep0050.pth.tar
75
+ -- baseline_R101_got10k_only
76
+ STARKST_ep0050.pth.tar
77
+ ```
78
+ ### Raw Results
79
+ The [raw results](https://drive.google.com/drive/folders/16rWehrDmJVmvMsadffOPaCczz7pst4PH?usp=sharing) are in the format [top_left_x, top_left_y, width, height]. Raw results of GOT-10K and TrackingNet can be
80
+ directly submitted to the corresponding evaluation servers. The folder ```test/tracking_results/``` contains raw results
81
+ for the LaSOT dataset and results should be organized in the following structure
82
+ ```
83
+ ${STARK_ROOT}
84
+ -- test
85
+ -- tracking_results
86
+ -- stark_s
87
+ -- baseline
88
+ airplane-1.txt
89
+ airplane-13.txt
90
+ ...
91
+ -- stark_st2
92
+ -- baseline
93
+ airplane-1.txt
94
+ airplane-13.txt
95
+ ...
96
+ -- baseline_R101
97
+ airplane-1.txt
98
+ airplane-13.txt
99
+ ...
100
+ ```
101
+ The raw results of VOT2020 and VOT2020-LT should be organized in the following structure
102
+ ```
103
+ ${STARK_ROOT}
104
+ -- external
105
+ -- vot20
106
+ -- stark_s50
107
+ -- results
108
+ -- stark_s50_ar
109
+ -- results
110
+ -- stark_st50
111
+ -- results
112
+ -- stark_st50_ar
113
+ -- results
114
+ -- stark_st101
115
+ -- results
116
+ -- stark_st101_ar
117
+ -- results
118
+ -- vot20_lt
119
+ -- stark_st50
120
+ -- results
121
+ -- stark_st101
122
+ -- results
123
+ ```
README.md ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # STARK
2
+ <!--
3
+ [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/learning-spatio-temporal-transformer-for/visual-object-tracking-on-lasot)](https://paperswithcode.com/sota/visual-object-tracking-on-lasot?p=learning-spatio-temporal-transformer-for)
4
+ [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/learning-spatio-temporal-transformer-for/visual-object-tracking-on-got-10k)](https://paperswithcode.com/sota/visual-object-tracking-on-got-10k?p=learning-spatio-temporal-transformer-for)
5
+ [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/learning-spatio-temporal-transformer-for/visual-object-tracking-on-trackingnet)](https://paperswithcode.com/sota/visual-object-tracking-on-trackingnet?p=learning-spatio-temporal-transformer-for)
6
+ -->
7
+
8
+ The official implementation of the **ICCV2021** paper [**Learning Spatio-Temporal Transformer for Visual Tracking**](https://openaccess.thecvf.com/content/ICCV2021/papers/Yan_Learning_Spatio-Temporal_Transformer_for_Visual_Tracking_ICCV_2021_paper.pdf)
9
+
10
+ Hiring research interns for visual transformer projects: houwen.peng@microsoft.com
11
+ ## News
12
+ - STARK has been integrated into the [mmtracking](https://github.com/open-mmlab/mmtracking/tree/master/configs/sot/stark) library!
13
+ - :trophy: **We are the Winner of VOT-21 RGB-D challenge**
14
+ - :trophy: **We won the Runner-ups in VOT-21 Real-Time and Long-term challenges**
15
+ - We release an extremely fast version of STARK called **STARK-Lightning** :zap: . It can run at **200~300 FPS** on a RTX TITAN GPU.
16
+ Besides, its performance can beat DiMP50, while the model size is even less than that of SiamFC!
17
+ More details can be found at [STARK_Lightning_En.md](lib/tutorials/STARK_Lightning_En.md)/[中文教程](lib/tutorials/STARK_Lightning_Ch.md)
18
+ - The raw results of STARK and other trackers on NOTU (NFS, OTB100, TC128, UAV123) have been uploaded to [here](https://drive.google.com/file/d/1KbtTdxxvvtC6_rlBM3Gi_H7HzpCdrX1F/view?usp=sharing)
19
+ ![STARK_Framework](tracking/Framework.png)
20
+ ## Highlights
21
+ ### End-to-End, Post-processing Free
22
+
23
+ STARK is an **end-to-end** tracking approach, which directly predicts one accurate bounding box as the tracking result.
24
+ Besides, STARK does not use any hyperparameters-sensitive post-processing, leading to stable performances.
25
+
26
+ ### Real-Time Speed
27
+ STARK-ST50 and STARK-ST101 run at **40FPS** and **30FPS** respectively on a Tesla V100 GPU.
28
+
29
+ ### Strong performance
30
+ | Tracker | LaSOT (AUC)| GOT-10K (AO)| TrackingNet (AUC)|
31
+ |---|---|---|---|
32
+ |**STARK**|**67.1**|**68.8**|**82.0**|
33
+ |TransT|64.9|67.1|81.4|
34
+ |TrDiMP|63.7|67.1|78.4|
35
+ |Siam R-CNN|64.8|64.9|81.2|
36
+
37
+ ### Purely PyTorch-based Code
38
+
39
+ STARK is implemented purely based on the PyTorch.
40
+
41
+ ## Install the environment
42
+ **Option1**: Use the Anaconda
43
+ ```
44
+ conda create -n stark python=3.6
45
+ conda activate stark
46
+ bash install_pytorch17.sh
47
+ ```
48
+ **Option2**: Use the docker file
49
+
50
+ We provide the complete docker at [here](https://hub.docker.com/repository/docker/alphabin/stark)
51
+
52
+ ## Data Preparation
53
+ Put the tracking datasets in ./data. It should look like:
54
+ ```
55
+ ${STARK_ROOT}
56
+ -- data
57
+ -- lasot
58
+ |-- airplane
59
+ |-- basketball
60
+ |-- bear
61
+ ...
62
+ -- got10k
63
+ |-- test
64
+ |-- train
65
+ |-- val
66
+ -- coco
67
+ |-- annotations
68
+ |-- images
69
+ -- trackingnet
70
+ |-- TRAIN_0
71
+ |-- TRAIN_1
72
+ ...
73
+ |-- TRAIN_11
74
+ |-- TEST
75
+ ```
76
+ ## Set project paths
77
+ Run the following command to set paths for this project
78
+ ```
79
+ python tracking/create_default_local_file.py --workspace_dir . --data_dir ./data --save_dir .
80
+ ```
81
+ After running this command, you can also modify paths by editing these two files
82
+ ```
83
+ lib/train/admin/local.py # paths about training
84
+ lib/test/evaluation/local.py # paths about testing
85
+ ```
86
+
87
+ ## Train STARK
88
+ Training with multiple GPUs using DDP
89
+ ```
90
+ # STARK-S50
91
+ python tracking/train.py --script stark_s --config baseline --save_dir . --mode multiple --nproc_per_node 8 # STARK-S50
92
+ # STARK-ST50
93
+ python tracking/train.py --script stark_st1 --config baseline --save_dir . --mode multiple --nproc_per_node 8 # STARK-ST50 Stage1
94
+ python tracking/train.py --script stark_st2 --config baseline --save_dir . --mode multiple --nproc_per_node 8 --script_prv stark_st1 --config_prv baseline # STARK-ST50 Stage2
95
+ # STARK-ST101
96
+ python tracking/train.py --script stark_st1 --config baseline_R101 --save_dir . --mode multiple --nproc_per_node 8 # STARK-ST101 Stage1
97
+ python tracking/train.py --script stark_st2 --config baseline_R101 --save_dir . --mode multiple --nproc_per_node 8 --script_prv stark_st1 --config_prv baseline_R101 # STARK-ST101 Stage2
98
+ ```
99
+ (Optionally) Debugging training with a single GPU
100
+ ```
101
+ python tracking/train.py --script stark_s --config baseline --save_dir . --mode single
102
+ ```
103
+ ## Test and evaluate STARK on benchmarks
104
+
105
+ - LaSOT
106
+ ```
107
+ python tracking/test.py stark_st baseline --dataset lasot --threads 32
108
+ python tracking/analysis_results.py # need to modify tracker configs and names
109
+ ```
110
+ - GOT10K-test
111
+ ```
112
+ python tracking/test.py stark_st baseline_got10k_only --dataset got10k_test --threads 32
113
+ python lib/test/utils/transform_got10k.py --tracker_name stark_st --cfg_name baseline_got10k_only
114
+ ```
115
+ - TrackingNet
116
+ ```
117
+ python tracking/test.py stark_st baseline --dataset trackingnet --threads 32
118
+ python lib/test/utils/transform_trackingnet.py --tracker_name stark_st --cfg_name baseline
119
+ ```
120
+ - VOT2020
121
+ Before evaluating "STARK+AR" on VOT2020, please install some extra packages following [external/AR/README.md](external/AR/README.md)
122
+ ```
123
+ cd external/vot20/<workspace_dir>
124
+ export PYTHONPATH=<path to the stark project>:$PYTHONPATH
125
+ bash exp.sh
126
+ ```
127
+ - VOT2020-LT
128
+ ```
129
+ cd external/vot20_lt/<workspace_dir>
130
+ export PYTHONPATH=<path to the stark project>:$PYTHONPATH
131
+ bash exp.sh
132
+ ```
133
+ ## Test FLOPs, Params, and Speed
134
+ ```
135
+ # Profiling STARK-S50 model
136
+ python tracking/profile_model.py --script stark_s --config baseline
137
+ # Profiling STARK-ST50 model
138
+ python tracking/profile_model.py --script stark_st2 --config baseline
139
+ # Profiling STARK-ST101 model
140
+ python tracking/profile_model.py --script stark_st2 --config baseline_R101
141
+ # Profiling STARK-Lightning-X-trt
142
+ python tracking/profile_model_lightning_X_trt.py
143
+ ```
144
+
145
+ ## Model Zoo
146
+ The trained models, the training logs, and the raw tracking results are provided in the [model zoo](MODEL_ZOO.md)
147
+
148
+ ## Acknowledgments
149
+ * Thanks for the great [PyTracking](https://github.com/visionml/pytracking) Library, which helps us to quickly implement our ideas.
150
+ * We use the implementation of the DETR from the official repo [https://github.com/facebookresearch/detr](https://github.com/facebookresearch/detr).
UNOTC.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # OTB2015
2
+ CUDA_VISIBLE_DEVICES=1,2,3,4,5,6,7 python tracking/test.py stark_s baseline --dataset otb --threads 28 --num_gpus 7
3
+ CUDA_VISIBLE_DEVICES=1,2,3,4,5,6,7 python tracking/test.py stark_st baseline --dataset otb --threads 28 --num_gpus 7
4
+ CUDA_VISIBLE_DEVICES=1,2,3,4,5,6,7 python tracking/test.py stark_st baseline_R101 --dataset otb --threads 28 --num_gpus 7
5
+ # UAV123
6
+ CUDA_VISIBLE_DEVICES=1,2,3,4,5,6,7 python tracking/test.py stark_s baseline --dataset uav --threads 28 --num_gpus 7
7
+ CUDA_VISIBLE_DEVICES=1,2,3,4,5,6,7 python tracking/test.py stark_st baseline --dataset uav --threads 28 --num_gpus 7
8
+ CUDA_VISIBLE_DEVICES=1,2,3,4,5,6,7 python tracking/test.py stark_st baseline_R101 --dataset uav --threads 28 --num_gpus 7
9
+ # NFS
10
+ CUDA_VISIBLE_DEVICES=1,2,3,4,5,6,7 python tracking/test.py stark_s baseline --dataset nfs --threads 28 --num_gpus 7
11
+ CUDA_VISIBLE_DEVICES=1,2,3,4,5,6,7 python tracking/test.py stark_st baseline --dataset nfs --threads 28 --num_gpus 7
12
+ CUDA_VISIBLE_DEVICES=1,2,3,4,5,6,7 python tracking/test.py stark_st baseline_R101 --dataset nfs --threads 28 --num_gpus 7
13
+ # TC128
14
+ CUDA_VISIBLE_DEVICES=1,2,3,4,5,6,7 python tracking/test.py stark_s baseline --dataset tc128 --threads 28 --num_gpus 7
15
+ CUDA_VISIBLE_DEVICES=1,2,3,4,5,6,7 python tracking/test.py stark_st baseline --dataset tc128 --threads 28 --num_gpus 7
16
+ CUDA_VISIBLE_DEVICES=1,2,3,4,5,6,7 python tracking/test.py stark_st baseline_R101 --dataset tc128 --threads 28 --num_gpus 7
17
+
experiments/stark_lightning_X_trt/baseline_rephead_4_lite_search5.yaml ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DATA:
2
+ MAX_SAMPLE_INTERVAL: 200
3
+ MEAN:
4
+ - 0.485
5
+ - 0.456
6
+ - 0.406
7
+ SEARCH:
8
+ CENTER_JITTER: 4.5 # ori 4.5
9
+ FACTOR: 5.0 # ori 5.0
10
+ SCALE_JITTER: 0.5 # ori 0.5
11
+ SIZE: 320 # ori 320
12
+ FEAT_SIZE: 20
13
+ STD:
14
+ - 0.229
15
+ - 0.224
16
+ - 0.225
17
+ TEMPLATE:
18
+ CENTER_JITTER: 0
19
+ FACTOR: 2.0
20
+ SCALE_JITTER: 0
21
+ SIZE: 128
22
+ FEAT_SIZE: 8
23
+ TRAIN:
24
+ DATASETS_NAME:
25
+ - LASOT
26
+ - GOT10K_vottrain
27
+ - COCO17
28
+ - TRACKINGNET
29
+ DATASETS_RATIO:
30
+ - 1
31
+ - 1
32
+ - 1
33
+ - 1
34
+ SAMPLE_PER_EPOCH: 60000
35
+ VAL:
36
+ DATASETS_NAME:
37
+ - GOT10K_votval
38
+ DATASETS_RATIO:
39
+ - 1
40
+ SAMPLE_PER_EPOCH: 10000
41
+ MODEL:
42
+ BACKBONE:
43
+ LAST_STAGE_BLOCK: 4
44
+ DILATION: false
45
+ OUTPUT_LAYERS:
46
+ - stage3 # ori layer3
47
+ TYPE: RepVGG-A0 # ori resnet50
48
+ HEAD_TYPE: CORNER_LITE_REP_v2 # ori CORNER
49
+ HIDDEN_DIM: 128
50
+ HEAD_DIM: 128 # ori 256
51
+ TRANSFORMER:
52
+ DIM_FEEDFORWARD: 1024
53
+ DROPOUT: 0.1
54
+ NHEADS: 8
55
+ TRAIN:
56
+ AMP: False
57
+ BACKBONE_MULTIPLIER: 0.1
58
+ BATCH_SIZE: 16
59
+ DEEP_SUPERVISION: false
60
+ EPOCH: 500
61
+ FREEZE_BACKBONE_BN: true
62
+ BACKBONE_TRAINED_LAYERS:
63
+ - stage1
64
+ - stage2
65
+ - stage3
66
+ GIOU_WEIGHT: 2.0
67
+ GRAD_CLIP_NORM: 0.1
68
+ L1_WEIGHT: 5.0
69
+ LR: 0.0001
70
+ LR_DROP_EPOCH: 400
71
+ NUM_WORKER: 8
72
+ OPTIMIZER: ADAMW
73
+ PRINT_INTERVAL: 50
74
+ SCHEDULER:
75
+ TYPE: step
76
+ DECAY_RATE: 0.1
77
+ VAL_EPOCH_INTERVAL: 20
78
+ WEIGHT_DECAY: 0.0001
79
+ TEST:
80
+ EPOCH: 500
81
+ SEARCH_FACTOR: 5.0 # ori 5.0
82
+ SEARCH_SIZE: 320 # ori 320
83
+ TEMPLATE_FACTOR: 2.0
84
+ TEMPLATE_SIZE: 128
experiments/stark_s/baseline.yaml ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DATA:
2
+ MAX_SAMPLE_INTERVAL: 200
3
+ MEAN:
4
+ - 0.485
5
+ - 0.456
6
+ - 0.406
7
+ SEARCH:
8
+ CENTER_JITTER: 4.5
9
+ FACTOR: 5.0
10
+ SCALE_JITTER: 0.5
11
+ SIZE: 320
12
+ STD:
13
+ - 0.229
14
+ - 0.224
15
+ - 0.225
16
+ TEMPLATE:
17
+ CENTER_JITTER: 0
18
+ FACTOR: 2.0
19
+ SCALE_JITTER: 0
20
+ SIZE: 128
21
+ TRAIN:
22
+ DATASETS_NAME:
23
+ - LASOT
24
+ - GOT10K_vottrain
25
+ - COCO17
26
+ - TRACKINGNET
27
+ DATASETS_RATIO:
28
+ - 1
29
+ - 1
30
+ - 1
31
+ - 1
32
+ SAMPLE_PER_EPOCH: 60000
33
+ VAL:
34
+ DATASETS_NAME:
35
+ - GOT10K_votval
36
+ DATASETS_RATIO:
37
+ - 1
38
+ SAMPLE_PER_EPOCH: 10000
39
+ MODEL:
40
+ BACKBONE:
41
+ DILATION: false
42
+ OUTPUT_LAYERS:
43
+ - layer3
44
+ TYPE: resnet50
45
+ HEAD_TYPE: CORNER
46
+ HIDDEN_DIM: 256
47
+ NUM_OBJECT_QUERIES: 1
48
+ POSITION_EMBEDDING: sine
49
+ PREDICT_MASK: false
50
+ TRANSFORMER:
51
+ DEC_LAYERS: 6
52
+ DIM_FEEDFORWARD: 2048
53
+ DIVIDE_NORM: false
54
+ DROPOUT: 0.1
55
+ ENC_LAYERS: 6
56
+ NHEADS: 8
57
+ PRE_NORM: false
58
+ TRAIN:
59
+ BACKBONE_MULTIPLIER: 0.1
60
+ BATCH_SIZE: 16
61
+ DEEP_SUPERVISION: false
62
+ EPOCH: 500
63
+ FREEZE_BACKBONE_BN: true
64
+ FREEZE_LAYERS:
65
+ - conv1
66
+ - layer1
67
+ GIOU_WEIGHT: 2.0
68
+ GRAD_CLIP_NORM: 0.1
69
+ L1_WEIGHT: 5.0
70
+ LR: 0.0001
71
+ LR_DROP_EPOCH: 400
72
+ NUM_WORKER: 8
73
+ OPTIMIZER: ADAMW
74
+ PRINT_INTERVAL: 50
75
+ SCHEDULER:
76
+ TYPE: step
77
+ DECAY_RATE: 0.1
78
+ VAL_EPOCH_INTERVAL: 20
79
+ WEIGHT_DECAY: 0.0001
80
+ TEST:
81
+ EPOCH: 500
82
+ SEARCH_FACTOR: 5.0
83
+ SEARCH_SIZE: 320
84
+ TEMPLATE_FACTOR: 2.0
85
+ TEMPLATE_SIZE: 128
experiments/stark_s/baseline_got10k_only.yaml ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DATA:
2
+ MAX_SAMPLE_INTERVAL: 200
3
+ MEAN:
4
+ - 0.485
5
+ - 0.456
6
+ - 0.406
7
+ SEARCH:
8
+ CENTER_JITTER: 4.5
9
+ FACTOR: 5.0
10
+ SCALE_JITTER: 0.5
11
+ SIZE: 320
12
+ STD:
13
+ - 0.229
14
+ - 0.224
15
+ - 0.225
16
+ TEMPLATE:
17
+ CENTER_JITTER: 0
18
+ FACTOR: 2.0
19
+ SCALE_JITTER: 0
20
+ SIZE: 128
21
+ TRAIN:
22
+ DATASETS_NAME:
23
+ - GOT10K_train_full
24
+ DATASETS_RATIO:
25
+ - 1
26
+ SAMPLE_PER_EPOCH: 60000
27
+ VAL:
28
+ DATASETS_NAME:
29
+ - GOT10K_votval
30
+ DATASETS_RATIO:
31
+ - 1
32
+ SAMPLE_PER_EPOCH: 10000
33
+ MODEL:
34
+ BACKBONE:
35
+ DILATION: false
36
+ OUTPUT_LAYERS:
37
+ - layer3
38
+ TYPE: resnet50
39
+ HEAD_TYPE: CORNER
40
+ HIDDEN_DIM: 256
41
+ NUM_OBJECT_QUERIES: 1
42
+ POSITION_EMBEDDING: sine
43
+ PREDICT_MASK: false
44
+ TRANSFORMER:
45
+ DEC_LAYERS: 6
46
+ DIM_FEEDFORWARD: 2048
47
+ DIVIDE_NORM: false
48
+ DROPOUT: 0.1
49
+ ENC_LAYERS: 6
50
+ NHEADS: 8
51
+ PRE_NORM: false
52
+ TRAIN:
53
+ BACKBONE_MULTIPLIER: 0.1
54
+ BATCH_SIZE: 16
55
+ DEEP_SUPERVISION: false
56
+ EPOCH: 500
57
+ FREEZE_BACKBONE_BN: true
58
+ FREEZE_LAYERS:
59
+ - conv1
60
+ - layer1
61
+ GIOU_WEIGHT: 2.0
62
+ GRAD_CLIP_NORM: 0.1
63
+ L1_WEIGHT: 5.0
64
+ LR: 0.0001
65
+ LR_DROP_EPOCH: 400
66
+ NUM_WORKER: 8
67
+ OPTIMIZER: ADAMW
68
+ PRINT_INTERVAL: 50
69
+ SCHEDULER:
70
+ TYPE: step
71
+ DECAY_RATE: 0.1
72
+ VAL_EPOCH_INTERVAL: 20
73
+ WEIGHT_DECAY: 0.0001
74
+ TEST:
75
+ EPOCH: 500
76
+ SEARCH_FACTOR: 5.0
77
+ SEARCH_SIZE: 320
78
+ TEMPLATE_FACTOR: 2.0
79
+ TEMPLATE_SIZE: 128
experiments/stark_st1/baseline.yaml ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DATA:
2
+ SAMPLER_MODE: trident_pro
3
+ MAX_SAMPLE_INTERVAL:
4
+ - 200
5
+ MEAN:
6
+ - 0.485
7
+ - 0.456
8
+ - 0.406
9
+ SEARCH:
10
+ CENTER_JITTER: 4.5
11
+ FACTOR: 5.0
12
+ SCALE_JITTER: 0.5
13
+ SIZE: 320
14
+ NUMBER: 1
15
+ STD:
16
+ - 0.229
17
+ - 0.224
18
+ - 0.225
19
+ TEMPLATE:
20
+ CENTER_JITTER: 0
21
+ FACTOR: 2.0
22
+ SCALE_JITTER: 0
23
+ SIZE: 128
24
+ NUMBER: 2
25
+ TRAIN:
26
+ DATASETS_NAME:
27
+ - LASOT
28
+ - GOT10K_vottrain
29
+ - COCO17
30
+ - TRACKINGNET
31
+ DATASETS_RATIO:
32
+ - 1
33
+ - 1
34
+ - 1
35
+ - 1
36
+ SAMPLE_PER_EPOCH: 60000
37
+ VAL:
38
+ DATASETS_NAME:
39
+ - GOT10K_votval
40
+ DATASETS_RATIO:
41
+ - 1
42
+ SAMPLE_PER_EPOCH: 10000
43
+ MODEL:
44
+ HEAD_TYPE: CORNER
45
+ BACKBONE:
46
+ DILATION: false
47
+ OUTPUT_LAYERS:
48
+ - layer3
49
+ STRIDE: 16
50
+ TYPE: resnet50
51
+ HIDDEN_DIM: 256
52
+ NUM_OBJECT_QUERIES: 1
53
+ POSITION_EMBEDDING: sine
54
+ PREDICT_MASK: false
55
+ TRANSFORMER:
56
+ DEC_LAYERS: 6
57
+ DIM_FEEDFORWARD: 2048
58
+ DIVIDE_NORM: false
59
+ DROPOUT: 0.1
60
+ ENC_LAYERS: 6
61
+ NHEADS: 8
62
+ PRE_NORM: false
63
+ TRAIN:
64
+ BACKBONE_MULTIPLIER: 0.1
65
+ BATCH_SIZE: 16
66
+ DEEP_SUPERVISION: false
67
+ EPOCH: 500
68
+ FREEZE_BACKBONE_BN: true
69
+ FREEZE_LAYERS:
70
+ - conv1
71
+ - layer1
72
+ GIOU_WEIGHT: 2.0
73
+ GRAD_CLIP_NORM: 0.1
74
+ L1_WEIGHT: 5.0
75
+ LR: 0.0001
76
+ LR_DROP_EPOCH: 400
77
+ NUM_WORKER: 8
78
+ OPTIMIZER: ADAMW
79
+ PRINT_INTERVAL: 50
80
+ VAL_EPOCH_INTERVAL: 20
81
+ WEIGHT_DECAY: 0.0001
experiments/stark_st1/baseline_R101.yaml ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DATA:
2
+ SAMPLER_MODE: trident_pro
3
+ MAX_SAMPLE_INTERVAL:
4
+ - 200
5
+ MEAN:
6
+ - 0.485
7
+ - 0.456
8
+ - 0.406
9
+ SEARCH:
10
+ CENTER_JITTER: 4.5
11
+ FACTOR: 5.0
12
+ SCALE_JITTER: 0.5
13
+ SIZE: 320
14
+ NUMBER: 1
15
+ STD:
16
+ - 0.229
17
+ - 0.224
18
+ - 0.225
19
+ TEMPLATE:
20
+ CENTER_JITTER: 0
21
+ FACTOR: 2.0
22
+ SCALE_JITTER: 0
23
+ SIZE: 128
24
+ NUMBER: 2
25
+ TRAIN:
26
+ DATASETS_NAME:
27
+ - LASOT
28
+ - GOT10K_vottrain
29
+ - COCO17
30
+ - TRACKINGNET
31
+ DATASETS_RATIO:
32
+ - 1
33
+ - 1
34
+ - 1
35
+ - 1
36
+ SAMPLE_PER_EPOCH: 60000
37
+ VAL:
38
+ DATASETS_NAME:
39
+ - GOT10K_votval
40
+ DATASETS_RATIO:
41
+ - 1
42
+ SAMPLE_PER_EPOCH: 10000
43
+ MODEL:
44
+ HEAD_TYPE: CORNER
45
+ BACKBONE:
46
+ DILATION: false
47
+ OUTPUT_LAYERS:
48
+ - layer3
49
+ STRIDE: 16
50
+ TYPE: resnet101
51
+ HIDDEN_DIM: 256
52
+ NUM_OBJECT_QUERIES: 1
53
+ POSITION_EMBEDDING: sine
54
+ PREDICT_MASK: false
55
+ TRANSFORMER:
56
+ DEC_LAYERS: 6
57
+ DIM_FEEDFORWARD: 2048
58
+ DIVIDE_NORM: false
59
+ DROPOUT: 0.1
60
+ ENC_LAYERS: 6
61
+ NHEADS: 8
62
+ PRE_NORM: false
63
+ TRAIN:
64
+ BACKBONE_MULTIPLIER: 0.1
65
+ BATCH_SIZE: 16
66
+ DEEP_SUPERVISION: false
67
+ EPOCH: 500
68
+ FREEZE_BACKBONE_BN: true
69
+ FREEZE_LAYERS:
70
+ - conv1
71
+ - layer1
72
+ GIOU_WEIGHT: 2.0
73
+ GRAD_CLIP_NORM: 0.1
74
+ L1_WEIGHT: 5.0
75
+ LR: 0.0001
76
+ LR_DROP_EPOCH: 400
77
+ NUM_WORKER: 8
78
+ OPTIMIZER: ADAMW
79
+ PRINT_INTERVAL: 50
80
+ VAL_EPOCH_INTERVAL: 20
81
+ WEIGHT_DECAY: 0.0001
experiments/stark_st1/baseline_R101_got10k_only.yaml ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DATA:
2
+ SAMPLER_MODE: trident_pro
3
+ MAX_SAMPLE_INTERVAL:
4
+ - 200
5
+ MEAN:
6
+ - 0.485
7
+ - 0.456
8
+ - 0.406
9
+ SEARCH:
10
+ CENTER_JITTER: 4.5
11
+ FACTOR: 5.0
12
+ SCALE_JITTER: 0.5
13
+ SIZE: 320
14
+ NUMBER: 1
15
+ STD:
16
+ - 0.229
17
+ - 0.224
18
+ - 0.225
19
+ TEMPLATE:
20
+ CENTER_JITTER: 0
21
+ FACTOR: 2.0
22
+ SCALE_JITTER: 0
23
+ SIZE: 128
24
+ NUMBER: 2
25
+ TRAIN:
26
+ DATASETS_NAME:
27
+ - GOT10K_train_full
28
+ DATASETS_RATIO:
29
+ - 1
30
+ SAMPLE_PER_EPOCH: 60000
31
+ VAL:
32
+ DATASETS_NAME:
33
+ - GOT10K_votval
34
+ DATASETS_RATIO:
35
+ - 1
36
+ SAMPLE_PER_EPOCH: 10000
37
+ MODEL:
38
+ HEAD_TYPE: CORNER
39
+ BACKBONE:
40
+ DILATION: false
41
+ OUTPUT_LAYERS:
42
+ - layer3
43
+ STRIDE: 16
44
+ TYPE: resnet101
45
+ HIDDEN_DIM: 256
46
+ NUM_OBJECT_QUERIES: 1
47
+ POSITION_EMBEDDING: sine
48
+ PREDICT_MASK: false
49
+ TRANSFORMER:
50
+ DEC_LAYERS: 6
51
+ DIM_FEEDFORWARD: 2048
52
+ DIVIDE_NORM: false
53
+ DROPOUT: 0.1
54
+ ENC_LAYERS: 6
55
+ NHEADS: 8
56
+ PRE_NORM: false
57
+ TRAIN:
58
+ BACKBONE_MULTIPLIER: 0.1
59
+ BATCH_SIZE: 16
60
+ DEEP_SUPERVISION: false
61
+ EPOCH: 500
62
+ FREEZE_BACKBONE_BN: true
63
+ FREEZE_LAYERS:
64
+ - conv1
65
+ - layer1
66
+ GIOU_WEIGHT: 2.0
67
+ GRAD_CLIP_NORM: 0.1
68
+ L1_WEIGHT: 5.0
69
+ LR: 0.0001
70
+ LR_DROP_EPOCH: 400
71
+ NUM_WORKER: 8
72
+ OPTIMIZER: ADAMW
73
+ PRINT_INTERVAL: 50
74
+ VAL_EPOCH_INTERVAL: 20
75
+ WEIGHT_DECAY: 0.0001
experiments/stark_st1/baseline_got10k_only.yaml ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DATA:
2
+ SAMPLER_MODE: trident_pro
3
+ MAX_SAMPLE_INTERVAL:
4
+ - 200
5
+ MEAN:
6
+ - 0.485
7
+ - 0.456
8
+ - 0.406
9
+ SEARCH:
10
+ CENTER_JITTER: 4.5
11
+ FACTOR: 5.0
12
+ SCALE_JITTER: 0.5
13
+ SIZE: 320
14
+ NUMBER: 1
15
+ STD:
16
+ - 0.229
17
+ - 0.224
18
+ - 0.225
19
+ TEMPLATE:
20
+ CENTER_JITTER: 0
21
+ FACTOR: 2.0
22
+ SCALE_JITTER: 0
23
+ SIZE: 128
24
+ NUMBER: 2
25
+ TRAIN:
26
+ DATASETS_NAME:
27
+ - GOT10K_train_full
28
+ DATASETS_RATIO:
29
+ - 1
30
+ SAMPLE_PER_EPOCH: 60000
31
+ VAL:
32
+ DATASETS_NAME:
33
+ - GOT10K_votval
34
+ DATASETS_RATIO:
35
+ - 1
36
+ SAMPLE_PER_EPOCH: 10000
37
+ MODEL:
38
+ HEAD_TYPE: CORNER
39
+ BACKBONE:
40
+ DILATION: false
41
+ OUTPUT_LAYERS:
42
+ - layer3
43
+ STRIDE: 16
44
+ TYPE: resnet50
45
+ HIDDEN_DIM: 256
46
+ NUM_OBJECT_QUERIES: 1
47
+ POSITION_EMBEDDING: sine
48
+ PREDICT_MASK: false
49
+ TRANSFORMER:
50
+ DEC_LAYERS: 6
51
+ DIM_FEEDFORWARD: 2048
52
+ DIVIDE_NORM: false
53
+ DROPOUT: 0.1
54
+ ENC_LAYERS: 6
55
+ NHEADS: 8
56
+ PRE_NORM: false
57
+ TRAIN:
58
+ BACKBONE_MULTIPLIER: 0.1
59
+ BATCH_SIZE: 16
60
+ DEEP_SUPERVISION: false
61
+ EPOCH: 500
62
+ FREEZE_BACKBONE_BN: true
63
+ FREEZE_LAYERS:
64
+ - conv1
65
+ - layer1
66
+ GIOU_WEIGHT: 2.0
67
+ GRAD_CLIP_NORM: 0.1
68
+ L1_WEIGHT: 5.0
69
+ LR: 0.0001
70
+ LR_DROP_EPOCH: 400
71
+ NUM_WORKER: 8
72
+ OPTIMIZER: ADAMW
73
+ PRINT_INTERVAL: 50
74
+ VAL_EPOCH_INTERVAL: 20
75
+ WEIGHT_DECAY: 0.0001
experiments/stark_st2/baseline.yaml ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DATA:
2
+ SAMPLER_MODE: trident_pro
3
+ MAX_SAMPLE_INTERVAL:
4
+ - 200
5
+ MEAN:
6
+ - 0.485
7
+ - 0.456
8
+ - 0.406
9
+ SEARCH:
10
+ CENTER_JITTER: 4.5
11
+ FACTOR: 5.0
12
+ SCALE_JITTER: 0.5
13
+ SIZE: 320
14
+ NUMBER: 1
15
+ STD:
16
+ - 0.229
17
+ - 0.224
18
+ - 0.225
19
+ TEMPLATE:
20
+ CENTER_JITTER: 0
21
+ FACTOR: 2.0
22
+ SCALE_JITTER: 0
23
+ SIZE: 128
24
+ NUMBER: 2
25
+ TRAIN:
26
+ DATASETS_NAME:
27
+ - LASOT
28
+ - GOT10K_vottrain
29
+ - COCO17
30
+ - TRACKINGNET
31
+ DATASETS_RATIO:
32
+ - 1
33
+ - 1
34
+ - 1
35
+ - 1
36
+ SAMPLE_PER_EPOCH: 60000
37
+ VAL:
38
+ DATASETS_NAME:
39
+ - GOT10K_votval
40
+ DATASETS_RATIO:
41
+ - 1
42
+ SAMPLE_PER_EPOCH: 10000
43
+ MODEL:
44
+ HEAD_TYPE: CORNER
45
+ NLAYER_HEAD: 3
46
+ BACKBONE:
47
+ DILATION: false
48
+ OUTPUT_LAYERS:
49
+ - layer3
50
+ STRIDE: 16
51
+ TYPE: resnet50
52
+ HIDDEN_DIM: 256
53
+ NUM_OBJECT_QUERIES: 1
54
+ POSITION_EMBEDDING: sine
55
+ PREDICT_MASK: false
56
+ TRANSFORMER:
57
+ DEC_LAYERS: 6
58
+ DIM_FEEDFORWARD: 2048
59
+ DIVIDE_NORM: false
60
+ DROPOUT: 0.1
61
+ ENC_LAYERS: 6
62
+ NHEADS: 8
63
+ PRE_NORM: false
64
+ TRAIN:
65
+ BACKBONE_MULTIPLIER: 0.1
66
+ BATCH_SIZE: 16
67
+ DEEP_SUPERVISION: false
68
+ EPOCH: 50
69
+ FREEZE_BACKBONE_BN: true
70
+ FREEZE_LAYERS:
71
+ - conv1
72
+ - layer1
73
+ GRAD_CLIP_NORM: 0.1
74
+ LR: 0.0001
75
+ LR_DROP_EPOCH: 40
76
+ NUM_WORKER: 8
77
+ OPTIMIZER: ADAMW
78
+ PRINT_INTERVAL: 50
79
+ VAL_EPOCH_INTERVAL: 10
80
+ WEIGHT_DECAY: 0.0001
81
+ TEST:
82
+ EPOCH: 50
83
+ SEARCH_FACTOR: 5.0
84
+ SEARCH_SIZE: 320
85
+ TEMPLATE_FACTOR: 2.0
86
+ TEMPLATE_SIZE: 128
87
+ UPDATE_INTERVALS:
88
+ LASOT: [200]
89
+ GOT10K_TEST: [200]
90
+ TRACKINGNET: [25]
91
+ VOT20: [10]
92
+ VOT20LT: [200]
experiments/stark_st2/baseline_R101.yaml ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DATA:
2
+ SAMPLER_MODE: trident_pro
3
+ MAX_SAMPLE_INTERVAL:
4
+ - 200
5
+ MEAN:
6
+ - 0.485
7
+ - 0.456
8
+ - 0.406
9
+ SEARCH:
10
+ CENTER_JITTER: 4.5
11
+ FACTOR: 5.0
12
+ SCALE_JITTER: 0.5
13
+ SIZE: 320
14
+ NUMBER: 1
15
+ STD:
16
+ - 0.229
17
+ - 0.224
18
+ - 0.225
19
+ TEMPLATE:
20
+ CENTER_JITTER: 0
21
+ FACTOR: 2.0
22
+ SCALE_JITTER: 0
23
+ SIZE: 128
24
+ NUMBER: 2
25
+ TRAIN:
26
+ DATASETS_NAME:
27
+ - LASOT
28
+ - GOT10K_vottrain
29
+ - COCO17
30
+ - TRACKINGNET
31
+ DATASETS_RATIO:
32
+ - 1
33
+ - 1
34
+ - 1
35
+ - 1
36
+ SAMPLE_PER_EPOCH: 60000
37
+ VAL:
38
+ DATASETS_NAME:
39
+ - GOT10K_votval
40
+ DATASETS_RATIO:
41
+ - 1
42
+ SAMPLE_PER_EPOCH: 10000
43
+ MODEL:
44
+ HEAD_TYPE: CORNER
45
+ NLAYER_HEAD: 3
46
+ BACKBONE:
47
+ DILATION: false
48
+ OUTPUT_LAYERS:
49
+ - layer3
50
+ STRIDE: 16
51
+ TYPE: resnet101
52
+ HIDDEN_DIM: 256
53
+ NUM_OBJECT_QUERIES: 1
54
+ POSITION_EMBEDDING: sine
55
+ PREDICT_MASK: false
56
+ TRANSFORMER:
57
+ DEC_LAYERS: 6
58
+ DIM_FEEDFORWARD: 2048
59
+ DIVIDE_NORM: false
60
+ DROPOUT: 0.1
61
+ ENC_LAYERS: 6
62
+ NHEADS: 8
63
+ PRE_NORM: false
64
+ TRAIN:
65
+ BACKBONE_MULTIPLIER: 0.1
66
+ BATCH_SIZE: 16
67
+ DEEP_SUPERVISION: false
68
+ EPOCH: 50
69
+ FREEZE_BACKBONE_BN: true
70
+ FREEZE_LAYERS:
71
+ - conv1
72
+ - layer1
73
+ GRAD_CLIP_NORM: 0.1
74
+ LR: 0.0001
75
+ LR_DROP_EPOCH: 40
76
+ NUM_WORKER: 8
77
+ OPTIMIZER: ADAMW
78
+ PRINT_INTERVAL: 50
79
+ VAL_EPOCH_INTERVAL: 10
80
+ WEIGHT_DECAY: 0.0001
81
+ TEST:
82
+ EPOCH: 50
83
+ SEARCH_FACTOR: 5.0
84
+ SEARCH_SIZE: 320
85
+ TEMPLATE_FACTOR: 2.0
86
+ TEMPLATE_SIZE: 128
87
+ UPDATE_INTERVALS:
88
+ LASOT: [200]
89
+ GOT10K_TEST: [200]
90
+ TRACKINGNET: [25]
91
+ VOT20: [10]
92
+ VOT20LT: [100]
experiments/stark_st2/baseline_R101_got10k_only.yaml ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DATA:
2
+ SAMPLER_MODE: trident_pro
3
+ MAX_SAMPLE_INTERVAL:
4
+ - 200
5
+ MEAN:
6
+ - 0.485
7
+ - 0.456
8
+ - 0.406
9
+ SEARCH:
10
+ CENTER_JITTER: 4.5
11
+ FACTOR: 5.0
12
+ SCALE_JITTER: 0.5
13
+ SIZE: 320
14
+ NUMBER: 1
15
+ STD:
16
+ - 0.229
17
+ - 0.224
18
+ - 0.225
19
+ TEMPLATE:
20
+ CENTER_JITTER: 0
21
+ FACTOR: 2.0
22
+ SCALE_JITTER: 0
23
+ SIZE: 128
24
+ NUMBER: 2
25
+ TRAIN:
26
+ DATASETS_NAME:
27
+ - GOT10K_train_full
28
+ DATASETS_RATIO:
29
+ - 1
30
+ SAMPLE_PER_EPOCH: 60000
31
+ VAL:
32
+ DATASETS_NAME:
33
+ - GOT10K_votval
34
+ DATASETS_RATIO:
35
+ - 1
36
+ SAMPLE_PER_EPOCH: 10000
37
+ MODEL:
38
+ HEAD_TYPE: CORNER
39
+ NLAYER_HEAD: 3
40
+ BACKBONE:
41
+ DILATION: false
42
+ OUTPUT_LAYERS:
43
+ - layer3
44
+ STRIDE: 16
45
+ TYPE: resnet101
46
+ HIDDEN_DIM: 256
47
+ NUM_OBJECT_QUERIES: 1
48
+ POSITION_EMBEDDING: sine
49
+ PREDICT_MASK: false
50
+ TRANSFORMER:
51
+ DEC_LAYERS: 6
52
+ DIM_FEEDFORWARD: 2048
53
+ DIVIDE_NORM: false
54
+ DROPOUT: 0.1
55
+ ENC_LAYERS: 6
56
+ NHEADS: 8
57
+ PRE_NORM: false
58
+ TRAIN:
59
+ BACKBONE_MULTIPLIER: 0.1
60
+ BATCH_SIZE: 16
61
+ DEEP_SUPERVISION: false
62
+ EPOCH: 50
63
+ FREEZE_BACKBONE_BN: true
64
+ FREEZE_LAYERS:
65
+ - conv1
66
+ - layer1
67
+ GRAD_CLIP_NORM: 0.1
68
+ LR: 0.0001
69
+ LR_DROP_EPOCH: 40
70
+ NUM_WORKER: 8
71
+ OPTIMIZER: ADAMW
72
+ PRINT_INTERVAL: 50
73
+ VAL_EPOCH_INTERVAL: 10
74
+ WEIGHT_DECAY: 0.0001
75
+ TEST:
76
+ EPOCH: 50
77
+ SEARCH_FACTOR: 5.0
78
+ SEARCH_SIZE: 320
79
+ TEMPLATE_FACTOR: 2.0
80
+ TEMPLATE_SIZE: 128
experiments/stark_st2/baseline_got10k_only.yaml ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DATA:
2
+ SAMPLER_MODE: trident_pro
3
+ MAX_SAMPLE_INTERVAL:
4
+ - 200
5
+ MEAN:
6
+ - 0.485
7
+ - 0.456
8
+ - 0.406
9
+ SEARCH:
10
+ CENTER_JITTER: 4.5
11
+ FACTOR: 5.0
12
+ SCALE_JITTER: 0.5
13
+ SIZE: 320
14
+ NUMBER: 1
15
+ STD:
16
+ - 0.229
17
+ - 0.224
18
+ - 0.225
19
+ TEMPLATE:
20
+ CENTER_JITTER: 0
21
+ FACTOR: 2.0
22
+ SCALE_JITTER: 0
23
+ SIZE: 128
24
+ NUMBER: 2
25
+ TRAIN:
26
+ DATASETS_NAME:
27
+ - GOT10K_train_full
28
+ DATASETS_RATIO:
29
+ - 1
30
+ SAMPLE_PER_EPOCH: 60000
31
+ VAL:
32
+ DATASETS_NAME:
33
+ - GOT10K_votval
34
+ DATASETS_RATIO:
35
+ - 1
36
+ SAMPLE_PER_EPOCH: 10000
37
+ MODEL:
38
+ HEAD_TYPE: CORNER
39
+ NLAYER_HEAD: 3
40
+ BACKBONE:
41
+ DILATION: false
42
+ OUTPUT_LAYERS:
43
+ - layer3
44
+ STRIDE: 16
45
+ TYPE: resnet50
46
+ HIDDEN_DIM: 256
47
+ NUM_OBJECT_QUERIES: 1
48
+ POSITION_EMBEDDING: sine
49
+ PREDICT_MASK: false
50
+ TRANSFORMER:
51
+ DEC_LAYERS: 6
52
+ DIM_FEEDFORWARD: 2048
53
+ DIVIDE_NORM: false
54
+ DROPOUT: 0.1
55
+ ENC_LAYERS: 6
56
+ NHEADS: 8
57
+ PRE_NORM: false
58
+ TRAIN:
59
+ BACKBONE_MULTIPLIER: 0.1
60
+ BATCH_SIZE: 16
61
+ DEEP_SUPERVISION: false
62
+ EPOCH: 50
63
+ FREEZE_BACKBONE_BN: true
64
+ FREEZE_LAYERS:
65
+ - conv1
66
+ - layer1
67
+ GRAD_CLIP_NORM: 0.1
68
+ LR: 0.0001
69
+ LR_DROP_EPOCH: 40
70
+ NUM_WORKER: 8
71
+ OPTIMIZER: ADAMW
72
+ PRINT_INTERVAL: 50
73
+ VAL_EPOCH_INTERVAL: 10
74
+ WEIGHT_DECAY: 0.0001
75
+ TEST:
76
+ EPOCH: 50
77
+ SEARCH_FACTOR: 5.0
78
+ SEARCH_SIZE: 320
79
+ TEMPLATE_FACTOR: 2.0
80
+ TEMPLATE_SIZE: 128
external/AR/README.md ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Alpha-Refine
2
+ ## Introduction
3
+ Alpha-Refine is the winner of the VOT Real-Time Challenge 2020, which has great ability to predict high-quality masks.
4
+ In this work, we combine the STARK tracker with Alpha-Refine to test on the VOT2020 benchamark.
5
+
6
+ ## Installation
7
+ After the environment has been installed according to the README.md of STARK, you only need to install a few more packages as shown below.
8
+
9
+ * Install ninja-build for Precise ROI pooling
10
+ ```bash
11
+ sudo apt-get install ninja-build
12
+ ```
13
+ In case of issues, we refer to https://github.com/vacancy/PreciseRoIPooling.
14
+
15
+ * Install the Precise ROI pooling
16
+ ```
17
+ cd ltr/external
18
+ git clone https://github.com/vacancy/PreciseRoIPooling.git
19
+ cd ../..
20
+ ```
21
+ * Add the project path to environment variables
22
+ ```
23
+ export PYTHONPATH=<absolute_path_of_AR>:$PYTHONPATH
24
+ ```
25
+
26
+ * Setup the environment
27
+
28
+ Create the default environment setting files.
29
+ ```bash
30
+ # Environment settings for pytracking. Saved at pytracking/evaluation/local.py
31
+ python -c "from pytracking.evaluation.environment import create_default_local_file; create_default_local_file()"
32
+
33
+ # Environment settings for ltr. Saved at ltr/admin/local.py
34
+ python -c "from ltr.admin.environment import create_default_local_file; create_default_local_file()"
35
+ ```
36
+
37
+ You can modify these files to set the paths to datasets, results paths etc.
38
+
39
+ * Download the pre-trained Alpha-Refine network
40
+ Download the network for [Alpha-Refine](https://drive.google.com/open?id=1qOQRfaRMbQ2nmgX1NFjoQHfXOAn609QM)
41
+ and put it under the ltr/checkpoints/ltr/ARcm_seg/ARcm_coco_seg_only_mask_384 dir.
42
+
external/AR/ltr/README.md ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LTR
2
+
3
+ A general PyTorch based framework for learning tracking representations.
4
+ ## Table of Contents
5
+
6
+ * [Quick Start](#quick-start)
7
+ * [Overview](#overview)
8
+ * [Trackers](#trackers)
9
+ * [PrDiMP](#PrDiMP)
10
+ * [DiMP](#DiMP)
11
+ * [ATOM](#ATOM)
12
+ * [Training your own networks](#training-your-own-networks)
13
+
14
+ ## Quick Start
15
+ The installation script will automatically generate a local configuration file "admin/local.py". In case the file was not generated, run ```admin.environment.create_default_local_file()``` to generate it. Next, set the paths to the training workspace,
16
+ i.e. the directory where the checkpoints will be saved. Also set the paths to the datasets you want to use. If all the dependencies have been correctly installed, you can train a network using the run_training.py script in the correct conda environment.
17
+ ```bash
18
+ conda activate pytracking
19
+ python run_training.py train_module train_name
20
+ ```
21
+ Here, ```train_module``` is the sub-module inside ```train_settings``` and ```train_name``` is the name of the train setting file to be used.
22
+
23
+ For example, you can train using the included default ATOM settings by running:
24
+ ```bash
25
+ python run_training bbreg atom_default
26
+ ```
27
+
28
+
29
+ ## Overview
30
+ The framework consists of the following sub-modules.
31
+ - [actors](actors): Contains the actor classes for different trainings. The actor class is responsible for passing the input data through the network can calculating losses.
32
+ - [admin](admin): Includes functions for loading networks, tensorboard etc. and also contains environment settings.
33
+ - [dataset](dataset): Contains integration of a number of training datasets, namely [TrackingNet](https://tracking-net.org/), [GOT-10k](http://got-10k.aitestunion.com/), [LaSOT](https://cis.temple.edu/lasot/),
34
+ [ImageNet-VID](http://image-net.org/), [DAVIS](https://davischallenge.org), [YouTube-VOS](https://youtube-vos.org), [MS-COCO](http://cocodataset.org/#home), [SBD](http://home.bharathh.info/pubs/codes/SBD), [LVIS](https://www.lvisdataset.org), [ECSSD](http://www.cse.cuhk.edu.hk/leojia/projects/hsaliency/dataset.html), [MSRA10k](https://mmcheng.net/msra10k), and [HKU-IS](https://sites.google.com/site/ligb86/hkuis). Additionally, it includes modules to generate synthetic videos from image datasets.
35
+ - [data_specs](data_specs): Information about train/val splits of different datasets.
36
+ - [data](data): Contains functions for processing data, e.g. loading images, data augmentations, sampling frames from videos.
37
+ - [external](external): External libraries needed for training. Added as submodules.
38
+ - [models](models): Contains different layers and network definitions.
39
+ - [trainers](trainers): The main class which runs the training.
40
+ - [train_settings](train_settings): Contains settings files, specifying the training of a network.
41
+
42
+ ## Trackers
43
+ The framework currently contains the training code for the following trackers.
44
+
45
+ ### PrDiMP
46
+ The following setting files can be used train the DiMP networks, or to know the exact training details.
47
+ - [dimp.prdimp18](train_settings/dimp/prdimp18.py): The default settings used for training the PrDiMP model with ResNet-18 backbone.
48
+ - [dimp.prdimp50](train_settings/dimp/prdimp50.py): The default settings used for training the PrDiMP model with ResNet-50 backbone.
49
+ - [dimp.super_dimp](train_settings/dimp/super_dimp.py): Combines the bounding-box regressor of PrDiMP with the standard DiMP classifier and better training and inference settings.
50
+
51
+ ### DiMP
52
+ The following setting files can be used train the DiMP networks, or to know the exact training details.
53
+ - [dimp.dimp18](train_settings/dimp/dimp18.py): The default settings used for training the DiMP model with ResNet-18 backbone.
54
+ - [dimp.dimp50](train_settings/dimp/dimp50.py): The default settings used for training the DiMP model with ResNet-50 backbone.
55
+
56
+ ### ATOM
57
+ The following setting file can be used train the ATOM network, or to know the exact training details.
58
+ - [bbreg.atom](train_settings/bbreg/atom_paper.py): The settings used in the paper for training the network in ATOM.
59
+ - [bbreg.atom](train_settings/bbreg/atom.py): Newer settings used for training the network in ATOM, also utilizing the GOT10k dataset.
60
+ - [bbreg.atom](train_settings/bbreg/atom_prob_ml.py): Settings for ATOM with the probabilistic bounding box regression proposed in [this paper](https://arxiv.org/abs/1909.12297).
61
+ - [bbreg.atom](train_settings/bbreg/atom_paper.py): The baseline ATOM* setting evaluated in [this paper](https://arxiv.org/abs/1909.12297).
62
+
63
+ ## Training your own networks
64
+ To train a custom network using the toolkit, the following components need to be specified in the train settings. For reference, see [atom.py](train_settings/bbreg/atom.py).
65
+ - Datasets: The datasets to be used for training. A number of standard tracking datasets are already available in ```dataset``` module.
66
+ - Processing: This function should perform the necessary post-processing of the data, e.g. cropping of target region, data augmentations etc.
67
+ - Sampler: Determines how the frames are sampled from a video sequence to form the batches.
68
+ - Network: The network module to be trained.
69
+ - Objective: The training objective.
70
+ - Actor: The trainer passes the training batch to the actor who is responsible for passing the data through the network correctly, and calculating the training loss.
71
+ - Optimizer: Optimizer to be used, e.g. Adam.
72
+ - Trainer: The main class which runs the epochs and saves checkpoints.
73
+
74
+
75
+
external/AR/ltr/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .admin.loading import load_network
2
+ from .admin.model_constructor import model_constructor
3
+ from .admin.multigpu import MultiGPU
external/AR/ltr/actors/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .base_actor import BaseActor
2
+ from .bbreg import AtomActor
3
+ from .tracking import DiMPActor
external/AR/ltr/actors/base_actor.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pytracking import TensorDict
2
+
3
+
4
+ class BaseActor:
5
+ """ Base class for actor. The actor class handles the passing of the data through the network
6
+ and calculation the loss"""
7
+ def __init__(self, net, objective):
8
+ """
9
+ args:
10
+ net - The network to train
11
+ objective - The loss function
12
+ """
13
+ self.net = net
14
+ self.objective = objective
15
+
16
+ def __call__(self, data: TensorDict):
17
+ """ Called in each training iteration. Should pass in input data through the network, calculate the loss, and
18
+ return the training stats for the input data
19
+ args:
20
+ data - A TensorDict containing all the necessary data blocks.
21
+
22
+ returns:
23
+ loss - loss for the input data
24
+ stats - a dict containing detailed losses
25
+ """
26
+ raise NotImplementedError
27
+
28
+ def to(self, device):
29
+ """ Move the network to device
30
+ args:
31
+ device - device to use. 'cpu' or 'cuda'
32
+ """
33
+ self.net.to(device)
34
+
35
+ def train(self, mode=True):
36
+ """ Set whether the network is in train mode.
37
+ args:
38
+ mode (True) - Bool specifying whether in training mode.
39
+ """
40
+ self.net.train(mode)
41
+
42
+ def eval(self):
43
+ """ Set network to eval mode"""
44
+ self.train(False)
external/AR/ltr/actors/bbreg.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from . import BaseActor
2
+
3
+
4
+ class AtomActor(BaseActor):
5
+ """ Actor for training the IoU-Net in ATOM"""
6
+ def __call__(self, data):
7
+ """
8
+ args:
9
+ data - The input data, should contain the fields 'train_images', 'test_images', 'train_anno',
10
+ 'test_proposals' and 'proposal_iou'.
11
+
12
+ returns:
13
+ loss - the training loss
14
+ states - dict containing detailed losses
15
+ """
16
+ # Run network to obtain IoU prediction for each proposal in 'test_proposals'
17
+ iou_pred = self.net(data['train_images'], data['test_images'], data['train_anno'], data['test_proposals'])
18
+
19
+ iou_pred = iou_pred.view(-1, iou_pred.shape[2])
20
+ iou_gt = data['proposal_iou'].view(-1, data['proposal_iou'].shape[2])
21
+
22
+ # Compute loss
23
+ loss = self.objective(iou_pred, iou_gt)
24
+
25
+ # Return training stats
26
+ stats = {'Loss/total': loss.item(),
27
+ 'Loss/iou': loss.item()}
28
+
29
+ return loss, stats
30
+
31
+
32
+ class AtomBBKLActor(BaseActor):
33
+ """ Actor for training the IoU-Net in ATOM with BBKL"""
34
+ def __call__(self, data):
35
+ """
36
+ args:
37
+ data - The input data, should contain the fields 'train_images', 'test_images', 'train_anno',
38
+ 'test_proposals', 'proposal_density', and 'gt_density'.
39
+
40
+ returns:
41
+ loss - the training loss
42
+ states - dict containing detailed losses
43
+ """
44
+ # Run network to obtain IoU prediction for each proposal in 'test_proposals'
45
+ bb_scores = self.net(data['train_images'], data['test_images'], data['train_anno'], data['test_proposals'])
46
+
47
+ bb_scores = bb_scores.view(-1, bb_scores.shape[2])
48
+ proposal_density = data['proposal_density'].view(-1, data['proposal_density'].shape[2])
49
+ gt_density = data['gt_density'].view(-1, data['gt_density'].shape[2])
50
+
51
+ # Compute loss
52
+ loss = self.objective(bb_scores, sample_density=proposal_density, gt_density=gt_density, mc_dim=1)
53
+
54
+ # Return training stats
55
+ stats = {'Loss/total': loss.item(),
56
+ 'Loss/bb_ce': loss.item()}
57
+
58
+ return loss, stats
external/AR/ltr/actors/tracking.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from . import BaseActor
2
+ import torch
3
+
4
+
5
+ class DiMPActor(BaseActor):
6
+ """Actor for training the DiMP network."""
7
+ def __init__(self, net, objective, loss_weight=None):
8
+ super().__init__(net, objective)
9
+ if loss_weight is None:
10
+ loss_weight = {'iou': 1.0, 'test_clf': 1.0}
11
+ self.loss_weight = loss_weight
12
+
13
+ def __call__(self, data):
14
+ """
15
+ args:
16
+ data - The input data, should contain the fields 'train_images', 'test_images', 'train_anno',
17
+ 'test_proposals', 'proposal_iou' and 'test_label'.
18
+
19
+ returns:
20
+ loss - the training loss
21
+ stats - dict containing detailed losses
22
+ """
23
+ # Run network
24
+ target_scores, iou_pred = self.net(train_imgs=data['train_images'],
25
+ test_imgs=data['test_images'],
26
+ train_bb=data['train_anno'],
27
+ test_proposals=data['test_proposals'])
28
+
29
+ # Classification losses for the different optimization iterations
30
+ clf_losses_test = [self.objective['test_clf'](s, data['test_label'], data['test_anno']) for s in target_scores]
31
+
32
+ # Loss of the final filter
33
+ clf_loss_test = clf_losses_test[-1]
34
+ loss_target_classifier = self.loss_weight['test_clf'] * clf_loss_test
35
+
36
+ # Compute loss for ATOM IoUNet
37
+ loss_iou = self.loss_weight['iou'] * self.objective['iou'](iou_pred, data['proposal_iou'])
38
+
39
+ # Loss for the initial filter iteration
40
+ loss_test_init_clf = 0
41
+ if 'test_init_clf' in self.loss_weight.keys():
42
+ loss_test_init_clf = self.loss_weight['test_init_clf'] * clf_losses_test[0]
43
+
44
+ # Loss for the intermediate filter iterations
45
+ loss_test_iter_clf = 0
46
+ if 'test_iter_clf' in self.loss_weight.keys():
47
+ test_iter_weights = self.loss_weight['test_iter_clf']
48
+ if isinstance(test_iter_weights, list):
49
+ loss_test_iter_clf = sum([a*b for a, b in zip(test_iter_weights, clf_losses_test[1:-1])])
50
+ else:
51
+ loss_test_iter_clf = (test_iter_weights / (len(clf_losses_test) - 2)) * sum(clf_losses_test[1:-1])
52
+
53
+ # Total loss
54
+ loss = loss_iou + loss_target_classifier + loss_test_init_clf + loss_test_iter_clf
55
+
56
+ # Log stats
57
+ stats = {'Loss/total': loss.item(),
58
+ 'Loss/iou': loss_iou.item(),
59
+ 'Loss/target_clf': loss_target_classifier.item()}
60
+ if 'test_init_clf' in self.loss_weight.keys():
61
+ stats['Loss/test_init_clf'] = loss_test_init_clf.item()
62
+ if 'test_iter_clf' in self.loss_weight.keys():
63
+ stats['Loss/test_iter_clf'] = loss_test_iter_clf.item()
64
+ stats['ClfTrain/test_loss'] = clf_loss_test.item()
65
+ if len(clf_losses_test) > 0:
66
+ stats['ClfTrain/test_init_loss'] = clf_losses_test[0].item()
67
+ if len(clf_losses_test) > 2:
68
+ stats['ClfTrain/test_iter_loss'] = sum(clf_losses_test[1:-1]).item() / (len(clf_losses_test) - 2)
69
+
70
+ return loss, stats
71
+
72
+
73
+ class KLDiMPActor(BaseActor):
74
+ """Actor for training the DiMP network."""
75
+ def __init__(self, net, objective, loss_weight=None):
76
+ super().__init__(net, objective)
77
+ if loss_weight is None:
78
+ loss_weight = {'bb_ce': 1.0}
79
+ self.loss_weight = loss_weight
80
+
81
+ def __call__(self, data):
82
+ """
83
+ args:
84
+ data - The input data, should contain the fields 'train_images', 'test_images', 'train_anno',
85
+ 'test_proposals', 'proposal_iou' and 'test_label'.
86
+
87
+ returns:
88
+ loss - the training loss
89
+ stats - dict containing detailed losses
90
+ """
91
+ # Run network
92
+ target_scores, bb_scores = self.net(train_imgs=data['train_images'],
93
+ test_imgs=data['test_images'],
94
+ train_bb=data['train_anno'],
95
+ test_proposals=data['test_proposals'])
96
+
97
+ # Reshape bb reg variables
98
+ is_valid = data['test_anno'][:, :, 0] < 99999.0
99
+ bb_scores = bb_scores[is_valid, :]
100
+ proposal_density = data['proposal_density'][is_valid, :]
101
+ gt_density = data['gt_density'][is_valid, :]
102
+
103
+ # Compute loss
104
+ bb_ce = self.objective['bb_ce'](bb_scores, sample_density=proposal_density, gt_density=gt_density, mc_dim=1)
105
+ loss_bb_ce = self.loss_weight['bb_ce'] * bb_ce
106
+
107
+ # If standard DiMP classifier is used
108
+ loss_target_classifier = 0
109
+ loss_test_init_clf = 0
110
+ loss_test_iter_clf = 0
111
+ if 'test_clf' in self.loss_weight.keys():
112
+ # Classification losses for the different optimization iterations
113
+ clf_losses_test = [self.objective['test_clf'](s, data['test_label'], data['test_anno']) for s in target_scores]
114
+
115
+ # Loss of the final filter
116
+ clf_loss_test = clf_losses_test[-1]
117
+ loss_target_classifier = self.loss_weight['test_clf'] * clf_loss_test
118
+
119
+ # Loss for the initial filter iteration
120
+ if 'test_init_clf' in self.loss_weight.keys():
121
+ loss_test_init_clf = self.loss_weight['test_init_clf'] * clf_losses_test[0]
122
+
123
+ # Loss for the intermediate filter iterations
124
+ if 'test_iter_clf' in self.loss_weight.keys():
125
+ test_iter_weights = self.loss_weight['test_iter_clf']
126
+ if isinstance(test_iter_weights, list):
127
+ loss_test_iter_clf = sum([a * b for a, b in zip(test_iter_weights, clf_losses_test[1:-1])])
128
+ else:
129
+ loss_test_iter_clf = (test_iter_weights / (len(clf_losses_test) - 2)) * sum(clf_losses_test[1:-1])
130
+
131
+ # If PrDiMP classifier is used
132
+ loss_clf_ce = 0
133
+ loss_clf_ce_init = 0
134
+ loss_clf_ce_iter = 0
135
+ if 'clf_ce' in self.loss_weight.keys():
136
+ # Classification losses for the different optimization iterations
137
+ clf_ce_losses = [self.objective['clf_ce'](s, data['test_label_density'], grid_dim=(-2,-1)) for s in target_scores]
138
+
139
+ # Loss of the final filter
140
+ clf_ce = clf_ce_losses[-1]
141
+ loss_clf_ce = self.loss_weight['clf_ce'] * clf_ce
142
+
143
+ # Loss for the initial filter iteration
144
+ if 'clf_ce_init' in self.loss_weight.keys():
145
+ loss_clf_ce_init = self.loss_weight['clf_ce_init'] * clf_ce_losses[0]
146
+
147
+ # Loss for the intermediate filter iterations
148
+ if 'clf_ce_iter' in self.loss_weight.keys() and len(clf_ce_losses) > 2:
149
+ test_iter_weights = self.loss_weight['clf_ce_iter']
150
+ if isinstance(test_iter_weights, list):
151
+ loss_clf_ce_iter = sum([a * b for a, b in zip(test_iter_weights, clf_ce_losses[1:-1])])
152
+ else:
153
+ loss_clf_ce_iter = (test_iter_weights / (len(clf_ce_losses) - 2)) * sum(clf_ce_losses[1:-1])
154
+
155
+ # Total loss
156
+ loss = loss_bb_ce + loss_clf_ce + loss_clf_ce_init + loss_clf_ce_iter + \
157
+ loss_target_classifier + loss_test_init_clf + loss_test_iter_clf
158
+
159
+ if torch.isinf(loss) or torch.isnan(loss):
160
+ raise Exception('ERROR: Loss was nan or inf!!!')
161
+
162
+ # Log stats
163
+ stats = {'Loss/total': loss.item(),
164
+ 'Loss/bb_ce': bb_ce.item(),
165
+ 'Loss/loss_bb_ce': loss_bb_ce.item()}
166
+ if 'test_clf' in self.loss_weight.keys():
167
+ stats['Loss/target_clf'] = loss_target_classifier.item()
168
+ if 'test_init_clf' in self.loss_weight.keys():
169
+ stats['Loss/test_init_clf'] = loss_test_init_clf.item()
170
+ if 'test_iter_clf' in self.loss_weight.keys():
171
+ stats['Loss/test_iter_clf'] = loss_test_iter_clf.item()
172
+ if 'clf_ce' in self.loss_weight.keys():
173
+ stats['Loss/clf_ce'] = loss_clf_ce.item()
174
+ if 'clf_ce_init' in self.loss_weight.keys():
175
+ stats['Loss/clf_ce_init'] = loss_clf_ce_init.item()
176
+ if 'clf_ce_iter' in self.loss_weight.keys() and len(clf_ce_losses) > 2:
177
+ stats['Loss/clf_ce_iter'] = loss_clf_ce_iter.item()
178
+
179
+ if 'test_clf' in self.loss_weight.keys():
180
+ stats['ClfTrain/test_loss'] = clf_loss_test.item()
181
+ if len(clf_losses_test) > 0:
182
+ stats['ClfTrain/test_init_loss'] = clf_losses_test[0].item()
183
+ if len(clf_losses_test) > 2:
184
+ stats['ClfTrain/test_iter_loss'] = sum(clf_losses_test[1:-1]).item() / (len(clf_losses_test) - 2)
185
+
186
+ if 'clf_ce' in self.loss_weight.keys():
187
+ stats['ClfTrain/clf_ce'] = clf_ce.item()
188
+ if len(clf_ce_losses) > 0:
189
+ stats['ClfTrain/clf_ce_init'] = clf_ce_losses[0].item()
190
+ if len(clf_ce_losses) > 2:
191
+ stats['ClfTrain/clf_ce_iter'] = sum(clf_ce_losses[1:-1]).item() / (len(clf_ce_losses) - 2)
192
+
193
+ return loss, stats
external/AR/ltr/admin/__init__.py ADDED
File without changes
external/AR/ltr/admin/environment.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ import os
3
+ from collections import OrderedDict
4
+
5
+
6
+ def create_default_local_file():
7
+ path = os.path.join(os.path.dirname(__file__), 'local.py')
8
+
9
+ empty_str = '\'\''
10
+ default_settings = OrderedDict({
11
+ 'workspace_dir': empty_str,
12
+ 'tensorboard_dir': 'self.workspace_dir + \'/tensorboard/\'',
13
+ 'lasot_dir': empty_str,
14
+ 'got10k_dir': empty_str,
15
+ 'trackingnet_dir': empty_str,
16
+ 'coco_dir': empty_str,
17
+ 'lvis_dir': empty_str,
18
+ 'sbd_dir': empty_str,
19
+ 'imagenet_dir': empty_str,
20
+ 'imagenetdet_dir': empty_str,
21
+ 'ecssd_dir': empty_str,
22
+ 'hkuis_dir': empty_str,
23
+ 'msra10k_dir': empty_str,
24
+ 'davis_dir': empty_str,
25
+ 'youtubevos_dir': empty_str})
26
+
27
+ comment = {'workspace_dir': 'Base directory for saving network checkpoints.',
28
+ 'tensorboard_dir': 'Directory for tensorboard files.'}
29
+
30
+ with open(path, 'w') as f:
31
+ f.write('class EnvironmentSettings:\n')
32
+ f.write(' def __init__(self):\n')
33
+
34
+ for attr, attr_val in default_settings.items():
35
+ comment_str = None
36
+ if attr in comment:
37
+ comment_str = comment[attr]
38
+ if comment_str is None:
39
+ f.write(' self.{} = {}\n'.format(attr, attr_val))
40
+ else:
41
+ f.write(' self.{} = {} # {}\n'.format(attr, attr_val, comment_str))
42
+
43
+
44
+ def env_settings():
45
+ env_module_name = 'ltr.admin.local'
46
+ try:
47
+ env_module = importlib.import_module(env_module_name)
48
+ return env_module.EnvironmentSettings()
49
+ except:
50
+ env_file = os.path.join(os.path.dirname(__file__), 'local.py')
51
+
52
+ create_default_local_file()
53
+ raise RuntimeError('YOU HAVE NOT SETUP YOUR local.py!!!\n Go to "{}" and set all the paths you need. Then try to run again.'.format(env_file))
external/AR/ltr/admin/loading.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import os
3
+ import sys
4
+ from pathlib import Path
5
+ import importlib
6
+ import inspect
7
+ from ltr.admin import settings as ws_settings
8
+
9
+
10
+ def load_trained_network(workspace_dir, network_path, checkpoint=None):
11
+ """OUTDATED. Use load_pretrained instead!"""
12
+ checkpoint_dir = os.path.join(workspace_dir, 'checkpoints')
13
+ directory = '{}/{}'.format(checkpoint_dir, network_path)
14
+
15
+ net, _ = load_network(directory, checkpoint)
16
+ return net
17
+
18
+
19
+ def load_pretrained(module, name, checkpoint=None, **kwargs):
20
+ """Load a network trained using the LTR framework. This is useful when you want to initialize your new network with
21
+ a previously trained model.
22
+ args:
23
+ module - Name of the train script module. I.e. the name of the folder in ltr/train_scripts.
24
+ name - The name of the train_script.
25
+ checkpoint - You can supply the checkpoint number or the full path to the checkpoint file (see load_network).
26
+ **kwargs - These are passed to load_network (see that function).
27
+ """
28
+
29
+ settings = ws_settings.Settings()
30
+ network_dir = os.path.join(settings.env.workspace_dir, 'checkpoints', 'ltr', module, name)
31
+ return load_network(network_dir=network_dir, checkpoint=checkpoint, **kwargs)
32
+
33
+
34
+ def load_network(network_dir=None, checkpoint=None, constructor_fun_name=None, constructor_module=None, **kwargs):
35
+ """Loads a network checkpoint file.
36
+
37
+ Can be called in two different ways:
38
+ load_checkpoint(network_dir):
39
+ Loads the checkpoint file given by the path. If checkpoint_dir is a directory,
40
+ it tries to find the latest checkpoint in that directory.
41
+
42
+ load_checkpoint(network_dir, checkpoint=epoch_num):
43
+ Loads the network at the given epoch number (int).
44
+
45
+ The extra keyword arguments are supplied to the network constructor to replace saved ones.
46
+ """
47
+
48
+ if network_dir is not None:
49
+ net_path = Path(network_dir)
50
+ else:
51
+ net_path = None
52
+
53
+ if net_path.is_file():
54
+ checkpoint = str(net_path)
55
+
56
+ if checkpoint is None:
57
+ # Load most recent checkpoint
58
+ checkpoint_list = sorted(net_path.glob('*.pth.tar'))
59
+ if checkpoint_list:
60
+ checkpoint_path = checkpoint_list[-1]
61
+ else:
62
+ raise Exception('No matching checkpoint file found')
63
+ elif isinstance(checkpoint, int):
64
+ # Checkpoint is the epoch number
65
+ checkpoint_list = sorted(net_path.glob('*_ep{:04d}.pth.tar'.format(checkpoint)))
66
+ if not checkpoint_list or len(checkpoint_list) == 0:
67
+ raise Exception('No matching checkpoint file found')
68
+ if len(checkpoint_list) > 1:
69
+ raise Exception('Multiple matching checkpoint files found')
70
+ else:
71
+ checkpoint_path = checkpoint_list[0]
72
+ elif isinstance(checkpoint, str):
73
+ # Checkpoint is the path
74
+ checkpoint_path = os.path.expanduser(checkpoint)
75
+ else:
76
+ raise TypeError
77
+
78
+ # Load network
79
+ checkpoint_dict = torch_load_legacy(checkpoint_path)
80
+
81
+ # Construct network model
82
+ if 'constructor' in checkpoint_dict and checkpoint_dict['constructor'] is not None:
83
+ net_constr = checkpoint_dict['constructor']
84
+ if constructor_fun_name is not None:
85
+ net_constr.fun_name = constructor_fun_name
86
+ if constructor_module is not None:
87
+ net_constr.fun_module = constructor_module
88
+ # Legacy networks before refactoring
89
+ if net_constr.fun_module.startswith('dlframework.'):
90
+ net_constr.fun_module = net_constr.fun_module[len('dlframework.'):]
91
+ net_fun = getattr(importlib.import_module(net_constr.fun_module), net_constr.fun_name)
92
+ net_fun_args = list(inspect.signature(net_fun).parameters.keys())
93
+ for arg, val in kwargs.items():
94
+ if arg in net_fun_args:
95
+ net_constr.kwds[arg] = val
96
+ else:
97
+ print('WARNING: Keyword argument "{}" not found when loading network. It was ignored.'.format(arg))
98
+ net = net_constr.get()
99
+ else:
100
+ raise RuntimeError('No constructor for the given network.')
101
+
102
+ net.load_state_dict(checkpoint_dict['net'])
103
+
104
+ net.constructor = checkpoint_dict['constructor']
105
+ if 'net_info' in checkpoint_dict and checkpoint_dict['net_info'] is not None:
106
+ net.info = checkpoint_dict['net_info']
107
+
108
+ return net, checkpoint_dict
109
+
110
+
111
+ def load_weights(net, path, strict=True):
112
+ checkpoint_dict = torch.load(path)
113
+ weight_dict = checkpoint_dict['net']
114
+ net.load_state_dict(weight_dict, strict=strict)
115
+ return net
116
+
117
+
118
+ def torch_load_legacy(path):
119
+ """Load network with legacy environment."""
120
+
121
+ # Setup legacy env (for older networks)
122
+ _setup_legacy_env()
123
+
124
+ # Load network
125
+ checkpoint_dict = torch.load(path, map_location='cpu')
126
+
127
+ # Cleanup legacy
128
+ _cleanup_legacy_env()
129
+
130
+ return checkpoint_dict
131
+
132
+
133
+ def _setup_legacy_env():
134
+ importlib.import_module('ltr')
135
+ sys.modules['dlframework'] = sys.modules['ltr']
136
+ sys.modules['dlframework.common'] = sys.modules['ltr']
137
+ importlib.import_module('ltr.admin')
138
+ sys.modules['dlframework.common.utils'] = sys.modules['ltr.admin']
139
+ for m in ('model_constructor', 'stats', 'settings', 'local'):
140
+ importlib.import_module('ltr.admin.' + m)
141
+ sys.modules['dlframework.common.utils.' + m] = sys.modules['ltr.admin.' + m]
142
+
143
+
144
+ def _cleanup_legacy_env():
145
+ del_modules = []
146
+ for m in sys.modules.keys():
147
+ if m.startswith('dlframework'):
148
+ del_modules.append(m)
149
+ for m in del_modules:
150
+ del sys.modules[m]
external/AR/ltr/admin/model_constructor.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import wraps
2
+ import importlib
3
+
4
+
5
+ def model_constructor(f):
6
+ """ Wraps the function 'f' which returns the network. An extra field 'constructor' is added to the network returned
7
+ by 'f'. This field contains an instance of the 'NetConstructor' class, which contains the information needed to
8
+ re-construct the network, such as the name of the function 'f', the function arguments etc. Thus, the network can
9
+ be easily constructed from a saved checkpoint by calling NetConstructor.get() function.
10
+ """
11
+ @wraps(f)
12
+ def f_wrapper(*args, **kwds):
13
+ net_constr = NetConstructor(f.__name__, f.__module__, args, kwds)
14
+ output = f(*args, **kwds)
15
+ if isinstance(output, (tuple, list)):
16
+ # Assume first argument is the network
17
+ output[0].constructor = net_constr
18
+ else:
19
+ output.constructor = net_constr
20
+ return output
21
+ return f_wrapper
22
+
23
+
24
+ class NetConstructor:
25
+ """ Class to construct networks. Takes as input the function name (e.g. atom_resnet18), the name of the module
26
+ which contains the network function (e.g. ltr.models.bbreg.atom) and the arguments for the network
27
+ function. The class object can then be stored along with the network weights to re-construct the network."""
28
+ def __init__(self, fun_name, fun_module, args, kwds):
29
+ """
30
+ args:
31
+ fun_name - The function which returns the network
32
+ fun_module - the module which contains the network function
33
+ args - arguments which are passed to the network function
34
+ kwds - arguments which are passed to the network function
35
+ """
36
+ self.fun_name = fun_name
37
+ self.fun_module = fun_module
38
+ self.args = args
39
+ self.kwds = kwds
40
+
41
+ def get(self):
42
+ """ Rebuild the network by calling the network function with the correct arguments. """
43
+ net_module = importlib.import_module(self.fun_module)
44
+ net_fun = getattr(net_module, self.fun_name)
45
+ return net_fun(*self.args, **self.kwds)
external/AR/ltr/admin/multigpu.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+
3
+
4
+ def is_multi_gpu(net):
5
+ return isinstance(net, (MultiGPU, nn.DataParallel))
6
+
7
+
8
+ class MultiGPU(nn.DataParallel):
9
+ """Wraps a network to allow simple multi-GPU training."""
10
+ def __getattr__(self, item):
11
+ try:
12
+ return super().__getattr__(item)
13
+ except:
14
+ pass
15
+ return getattr(self.module, item)
external/AR/ltr/admin/settings.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ltr.admin.environment import env_settings
2
+
3
+
4
+ class Settings:
5
+ """ Training settings, e.g. the paths to datasets and networks."""
6
+ def __init__(self):
7
+ self.set_default()
8
+
9
+ def set_default(self):
10
+ self.env = env_settings()
11
+ self.use_gpu = True
12
+
13
+
external/AR/ltr/admin/stats.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ class StatValue:
4
+ def __init__(self):
5
+ self.clear()
6
+
7
+ def reset(self):
8
+ self.val = 0
9
+
10
+ def clear(self):
11
+ self.reset()
12
+ self.history = []
13
+
14
+ def update(self, val):
15
+ self.val = val
16
+ self.history.append(self.val)
17
+
18
+
19
+ class AverageMeter(object):
20
+ """Computes and stores the average and current value"""
21
+ def __init__(self):
22
+ self.clear()
23
+ self.has_new_data = False
24
+
25
+ def reset(self):
26
+ self.avg = 0
27
+ self.val = 0
28
+ self.sum = 0
29
+ self.count = 0
30
+
31
+ def clear(self):
32
+ self.reset()
33
+ self.history = []
34
+
35
+ def update(self, val, n=1):
36
+ self.val = val
37
+ self.sum += val * n
38
+ self.count += n
39
+ self.avg = self.sum / self.count
40
+
41
+ def new_epoch(self):
42
+ if self.count > 0:
43
+ self.history.append(self.avg)
44
+ self.reset()
45
+ self.has_new_data = True
46
+ else:
47
+ self.has_new_data = False
48
+
49
+
50
+ def topk_accuracy(output, target, topk=(1,)):
51
+ """Computes the precision@k for the specified values of k"""
52
+ single_input = not isinstance(topk, (tuple, list))
53
+ if single_input:
54
+ topk = (topk,)
55
+
56
+ maxk = max(topk)
57
+ batch_size = target.size(0)
58
+
59
+ _, pred = output.topk(maxk, 1, True, True)
60
+ pred = pred.t()
61
+ correct = pred.eq(target.view(1, -1).expand_as(pred))
62
+
63
+ res = []
64
+ for k in topk:
65
+ correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)[0]
66
+ res.append(correct_k * 100.0 / batch_size)
67
+
68
+ if single_input:
69
+ return res[0]
70
+
71
+ return res
external/AR/ltr/admin/tensorboard.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from collections import OrderedDict
3
+ try:
4
+ from torch.utils.tensorboard import SummaryWriter
5
+ except:
6
+ print('WARNING: You are using tensorboardX instead sis you have a too old pytorch version.')
7
+ from tensorboardX import SummaryWriter
8
+
9
+
10
+ class TensorboardWriter:
11
+ def __init__(self, directory, loader_names):
12
+ self.directory = directory
13
+ self.writer = OrderedDict({name: SummaryWriter(os.path.join(self.directory, name)) for name in loader_names})
14
+
15
+ def write_info(self, module_name, script_name, description):
16
+ tb_info_writer = SummaryWriter(os.path.join(self.directory, 'info'))
17
+ tb_info_writer.add_text('Modulet_name', module_name)
18
+ tb_info_writer.add_text('Script_name', script_name)
19
+ tb_info_writer.add_text('Description', description)
20
+ tb_info_writer.close()
21
+
22
+ def write_epoch(self, stats: OrderedDict, epoch: int, ind=-1):
23
+ for loader_name, loader_stats in stats.items():
24
+ if loader_stats is None:
25
+ continue
26
+ for var_name, val in loader_stats.items():
27
+ if hasattr(val, 'history') and getattr(val, 'has_new_data', True):
28
+ self.writer[loader_name].add_scalar(var_name, val.history[ind], epoch)
external/AR/ltr/data/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .loader import LTRLoader
external/AR/ltr/data/bounding_box_utils.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+
4
+ def rect_to_rel(bb, sz_norm=None):
5
+ """Convert standard rectangular parametrization of the bounding box [x, y, w, h]
6
+ to relative parametrization [cx/sw, cy/sh, log(w), log(h)], where [cx, cy] is the center coordinate.
7
+ args:
8
+ bb - N x 4 tensor of boxes.
9
+ sz_norm - [N] x 2 tensor of value of [sw, sh] (optional). sw=w and sh=h if not given.
10
+ """
11
+
12
+ c = bb[...,:2] + 0.5 * bb[...,2:]
13
+ if sz_norm is None:
14
+ c_rel = c / bb[...,2:]
15
+ else:
16
+ c_rel = c / sz_norm
17
+ sz_rel = torch.log(bb[...,2:])
18
+ return torch.cat((c_rel, sz_rel), dim=-1)
19
+
20
+
21
+ def rel_to_rect(bb, sz_norm=None):
22
+ """Inverts the effect of rect_to_rel. See above."""
23
+
24
+ sz = torch.exp(bb[...,2:])
25
+ if sz_norm is None:
26
+ c = bb[...,:2] * sz
27
+ else:
28
+ c = bb[...,:2] * sz_norm
29
+ tl = c - 0.5 * sz
30
+ return torch.cat((tl, sz), dim=-1)
31
+
32
+
33
+ def masks_to_bboxes(mask, fmt='c'):
34
+
35
+ """ Convert a mask tensor to one or more bounding boxes.
36
+ Note: This function is a bit new, make sure it does what it says. /Andreas
37
+ :param mask: Tensor of masks, shape = (..., H, W)
38
+ :param fmt: bbox layout. 'c' => "center + size" or (x_center, y_center, width, height)
39
+ 't' => "top left + size" or (x_left, y_top, width, height)
40
+ 'v' => "vertices" or (x_left, y_top, x_right, y_bottom)
41
+ :return: tensor containing a batch of bounding boxes, shape = (..., 4)
42
+ """
43
+ batch_shape = mask.shape[:-2]
44
+ mask = mask.reshape((-1, *mask.shape[-2:]))
45
+ bboxes = []
46
+
47
+ for m in mask:
48
+ mx = m.sum(dim=-2).nonzero()
49
+ my = m.sum(dim=-1).nonzero()
50
+ bb = [mx.min(), my.min(), mx.max(), my.max()] if (len(mx) > 0 and len(my) > 0) else [0, 0, 0, 0]
51
+ bboxes.append(bb)
52
+
53
+ bboxes = torch.tensor(bboxes, dtype=torch.float32, device=mask.device)
54
+ bboxes = bboxes.reshape(batch_shape + (4,))
55
+
56
+ if fmt == 'v':
57
+ return bboxes
58
+
59
+ x1 = bboxes[..., :2]
60
+ s = bboxes[..., 2:] - x1 + 1
61
+
62
+ if fmt == 'c':
63
+ return torch.cat((x1 + 0.5 * s, s), dim=-1)
64
+ elif fmt == 't':
65
+ return torch.cat((x1, s), dim=-1)
66
+
67
+ raise ValueError("Undefined bounding box layout '%s'" % fmt)
68
+
69
+
70
+ def masks_to_bboxes_multi(mask, ids, fmt='c'):
71
+ assert mask.dim() == 2
72
+ bboxes = []
73
+
74
+ for id in ids:
75
+ mx = (mask == id).sum(dim=-2).nonzero()
76
+ my = (mask == id).float().sum(dim=-1).nonzero()
77
+ bb = [mx.min(), my.min(), mx.max(), my.max()] if (len(mx) > 0 and len(my) > 0) else [0, 0, 0, 0]
78
+
79
+ bb = torch.tensor(bb, dtype=torch.float32, device=mask.device)
80
+
81
+ x1 = bb[:2]
82
+ s = bb[2:] - x1 + 1
83
+
84
+ if fmt == 'v':
85
+ pass
86
+ elif fmt == 'c':
87
+ bb = torch.cat((x1 + 0.5 * s, s), dim=-1)
88
+ elif fmt == 't':
89
+ bb = torch.cat((x1, s), dim=-1)
90
+ else:
91
+ raise ValueError("Undefined bounding box layout '%s'" % fmt)
92
+ bboxes.append(bb)
93
+
94
+ return bboxes
external/AR/ltr/data/image_loader.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import jpeg4py
2
+ import cv2 as cv
3
+ from PIL import Image
4
+ import numpy as np
5
+
6
+ davis_palette = np.repeat(np.expand_dims(np.arange(0,256), 1), 3, 1).astype(np.uint8)
7
+ davis_palette[:22, :] = [[0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0],
8
+ [0, 0, 128], [128, 0, 128], [0, 128, 128], [128, 128, 128],
9
+ [64, 0, 0], [191, 0, 0], [64, 128, 0], [191, 128, 0],
10
+ [64, 0, 128], [191, 0, 128], [64, 128, 128], [191, 128, 128],
11
+ [0, 64, 0], [128, 64, 0], [0, 191, 0], [128, 191, 0],
12
+ [0, 64, 128], [128, 64, 128]]
13
+
14
+
15
+ def default_image_loader(path):
16
+ """The default image loader, reads the image from the given path. It first tries to use the jpeg4py_loader,
17
+ but reverts to the opencv_loader if the former is not available."""
18
+ if default_image_loader.use_jpeg4py is None:
19
+ # Try using jpeg4py
20
+ im = jpeg4py_loader(path)
21
+ if im is None:
22
+ default_image_loader.use_jpeg4py = False
23
+ print('Using opencv_loader instead.')
24
+ else:
25
+ default_image_loader.use_jpeg4py = True
26
+ return im
27
+ if default_image_loader.use_jpeg4py:
28
+ return jpeg4py_loader(path)
29
+ return opencv_loader(path)
30
+
31
+ default_image_loader.use_jpeg4py = None
32
+
33
+
34
+ def jpeg4py_loader(path):
35
+ """ Image reading using jpeg4py https://github.com/ajkxyz/jpeg4py"""
36
+ try:
37
+ return jpeg4py.JPEG(path).decode()
38
+ except Exception as e:
39
+ print('ERROR: Could not read image "{}"'.format(path))
40
+ print(e)
41
+ return None
42
+
43
+
44
+ def opencv_loader(path):
45
+ """ Read image using opencv's imread function and returns it in rgb format"""
46
+ try:
47
+ im = cv.imread(path, cv.IMREAD_COLOR)
48
+
49
+ # convert to rgb and return
50
+ return cv.cvtColor(im, cv.COLOR_BGR2RGB)
51
+ except Exception as e:
52
+ print('ERROR: Could not read image "{}"'.format(path))
53
+ print(e)
54
+ return None
55
+
56
+
57
+ def jpeg4py_loader_w_failsafe(path):
58
+ """ Image reading using jpeg4py https://github.com/ajkxyz/jpeg4py"""
59
+ try:
60
+ return jpeg4py.JPEG(path).decode()
61
+ except:
62
+ try:
63
+ im = cv.imread(path, cv.IMREAD_COLOR)
64
+
65
+ # convert to rgb and return
66
+ return cv.cvtColor(im, cv.COLOR_BGR2RGB)
67
+ except Exception as e:
68
+ print('ERROR: Could not read image "{}"'.format(path))
69
+ print(e)
70
+ return None
71
+
72
+
73
+ def opencv_seg_loader(path):
74
+ """ Read segmentation annotation using opencv's imread function"""
75
+ try:
76
+ return cv.imread(path)
77
+ except Exception as e:
78
+ print('ERROR: Could not read image "{}"'.format(path))
79
+ print(e)
80
+ return None
81
+
82
+
83
+ def imread_indexed(filename):
84
+ """ Load indexed image with given filename. Used to read segmentation annotations."""
85
+
86
+ im = Image.open(filename)
87
+
88
+ annotation = np.atleast_3d(im)[...,0]
89
+ return annotation
90
+
91
+
92
+ def imwrite_indexed(filename, array, color_palette=None):
93
+ """ Save indexed image as png. Used to save segmentation annotation."""
94
+
95
+ if color_palette is None:
96
+ color_palette = davis_palette
97
+
98
+ if np.atleast_3d(array).shape[2] != 1:
99
+ raise Exception("Saving indexed PNGs requires 2D array.")
100
+
101
+ im = Image.fromarray(array)
102
+ im.putpalette(color_palette.ravel())
103
+ im.save(filename, format='PNG')
external/AR/ltr/data/loader.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.utils.data.dataloader
3
+ import importlib
4
+ import collections
5
+ from torch._six import string_classes, int_classes
6
+ from pytracking import TensorDict, TensorList
7
+
8
+
9
+ def _check_use_shared_memory():
10
+ if hasattr(torch.utils.data.dataloader, '_use_shared_memory'):
11
+ return getattr(torch.utils.data.dataloader, '_use_shared_memory')
12
+ collate_lib = importlib.import_module('torch.utils.data._utils.collate')
13
+ if hasattr(collate_lib, '_use_shared_memory'):
14
+ return getattr(collate_lib, '_use_shared_memory')
15
+ return torch.utils.data.get_worker_info() is not None
16
+
17
+
18
+ def ltr_collate(batch):
19
+ """Puts each data field into a tensor with outer dimension batch size"""
20
+
21
+ error_msg = "batch must contain tensors, numbers, dicts or lists; found {}"
22
+ elem_type = type(batch[0])
23
+ if isinstance(batch[0], torch.Tensor):
24
+ out = None
25
+ if _check_use_shared_memory():
26
+ # If we're in a background process, concatenate directly into a
27
+ # shared memory tensor to avoid an extra copy
28
+ numel = sum([x.numel() for x in batch])
29
+ storage = batch[0].storage()._new_shared(numel)
30
+ out = batch[0].new(storage)
31
+ return torch.stack(batch, 0, out=out)
32
+ # if batch[0].dim() < 4:
33
+ # return torch.stack(batch, 0, out=out)
34
+ # return torch.cat(batch, 0, out=out)
35
+ elif elem_type.__module__ == 'numpy' and elem_type.__name__ != 'str_' \
36
+ and elem_type.__name__ != 'string_':
37
+ elem = batch[0]
38
+ if elem_type.__name__ == 'ndarray':
39
+ # array of string classes and object
40
+ if torch.utils.data.dataloader.re.search('[SaUO]', elem.dtype.str) is not None:
41
+ raise TypeError(error_msg.format(elem.dtype))
42
+
43
+ return torch.stack([torch.from_numpy(b) for b in batch], 0)
44
+ if elem.shape == (): # scalars
45
+ py_type = float if elem.dtype.name.startswith('float') else int
46
+ return torch.utils.data.dataloader.numpy_type_map[elem.dtype.name](list(map(py_type, batch)))
47
+ elif isinstance(batch[0], int_classes):
48
+ return torch.LongTensor(batch)
49
+ elif isinstance(batch[0], float):
50
+ return torch.DoubleTensor(batch)
51
+ elif isinstance(batch[0], string_classes):
52
+ return batch
53
+ elif isinstance(batch[0], TensorDict):
54
+ return TensorDict({key: ltr_collate([d[key] for d in batch]) for key in batch[0]})
55
+ elif isinstance(batch[0], collections.Mapping):
56
+ return {key: ltr_collate([d[key] for d in batch]) for key in batch[0]}
57
+ elif isinstance(batch[0], TensorList):
58
+ transposed = zip(*batch)
59
+ return TensorList([ltr_collate(samples) for samples in transposed])
60
+ elif isinstance(batch[0], collections.Sequence):
61
+ transposed = zip(*batch)
62
+ return [ltr_collate(samples) for samples in transposed]
63
+ elif batch[0] is None:
64
+ return batch
65
+
66
+ raise TypeError((error_msg.format(type(batch[0]))))
67
+
68
+
69
+ def ltr_collate_stack1(batch):
70
+ """Puts each data field into a tensor. The tensors are stacked at dim=1 to form the batch"""
71
+
72
+ error_msg = "batch must contain tensors, numbers, dicts or lists; found {}"
73
+ elem_type = type(batch[0])
74
+ if isinstance(batch[0], torch.Tensor):
75
+ out = None
76
+ if _check_use_shared_memory():
77
+ # If we're in a background process, concatenate directly into a
78
+ # shared memory tensor to avoid an extra copy
79
+ numel = sum([x.numel() for x in batch])
80
+ storage = batch[0].storage()._new_shared(numel)
81
+ out = batch[0].new(storage)
82
+ return torch.stack(batch, 1, out=out)
83
+ # if batch[0].dim() < 4:
84
+ # return torch.stack(batch, 0, out=out)
85
+ # return torch.cat(batch, 0, out=out)
86
+ elif elem_type.__module__ == 'numpy' and elem_type.__name__ != 'str_' \
87
+ and elem_type.__name__ != 'string_':
88
+ elem = batch[0]
89
+ if elem_type.__name__ == 'ndarray':
90
+ # array of string classes and object
91
+ if torch.utils.data.dataloader.re.search('[SaUO]', elem.dtype.str) is not None:
92
+ raise TypeError(error_msg.format(elem.dtype))
93
+
94
+ return torch.stack([torch.from_numpy(b) for b in batch], 1)
95
+ if elem.shape == (): # scalars
96
+ py_type = float if elem.dtype.name.startswith('float') else int
97
+ return torch.utils.data.dataloader.numpy_type_map[elem.dtype.name](list(map(py_type, batch)))
98
+ elif isinstance(batch[0], int_classes):
99
+ return torch.LongTensor(batch)
100
+ elif isinstance(batch[0], float):
101
+ return torch.DoubleTensor(batch)
102
+ elif isinstance(batch[0], string_classes):
103
+ return batch
104
+ elif isinstance(batch[0], TensorDict):
105
+ return TensorDict({key: ltr_collate_stack1([d[key] for d in batch]) for key in batch[0]})
106
+ elif isinstance(batch[0], collections.Mapping):
107
+ return {key: ltr_collate_stack1([d[key] for d in batch]) for key in batch[0]}
108
+ elif isinstance(batch[0], TensorList):
109
+ transposed = zip(*batch)
110
+ return TensorList([ltr_collate_stack1(samples) for samples in transposed])
111
+ elif isinstance(batch[0], collections.Sequence):
112
+ transposed = zip(*batch)
113
+ return [ltr_collate_stack1(samples) for samples in transposed]
114
+ elif batch[0] is None:
115
+ return batch
116
+
117
+ raise TypeError((error_msg.format(type(batch[0]))))
118
+
119
+
120
+ class LTRLoader(torch.utils.data.dataloader.DataLoader):
121
+ """
122
+ Data loader. Combines a dataset and a sampler, and provides
123
+ single- or multi-process iterators over the dataset.
124
+
125
+ Note: The only difference with default pytorch DataLoader is that an additional option stack_dim is available to
126
+ select along which dimension the data should be stacked to form a batch.
127
+
128
+ Arguments:
129
+ dataset (Dataset): dataset from which to load the data.
130
+ batch_size (int, optional): how many samples per batch to load
131
+ (default: 1).
132
+ shuffle (bool, optional): set to ``True`` to have the data reshuffled
133
+ at every epoch (default: False).
134
+ sampler (Sampler, optional): defines the strategy to draw samples from
135
+ the dataset. If specified, ``shuffle`` must be False.
136
+ batch_sampler (Sampler, optional): like sampler, but returns a batch of
137
+ indices at a time. Mutually exclusive with batch_size, shuffle,
138
+ sampler, and drop_last.
139
+ num_workers (int, optional): how many subprocesses to use for data
140
+ loading. 0 means that the data will be loaded in the main process.
141
+ (default: 0)
142
+ collate_fn (callable, optional): merges a list of samples to form a mini-batch.
143
+ stack_dim (int): Dimension along which to stack to form the batch. (default: 0)
144
+ pin_memory (bool, optional): If ``True``, the data loader will copy tensors
145
+ into CUDA pinned memory before returning them.
146
+ drop_last (bool, optional): set to ``True`` to drop the last incomplete batch,
147
+ if the dataset size is not divisible by the batch size. If ``False`` and
148
+ the size of dataset is not divisible by the batch size, then the last batch
149
+ will be smaller. (default: False)
150
+ timeout (numeric, optional): if positive, the timeout value for collecting a batch
151
+ from workers. Should always be non-negative. (default: 0)
152
+ worker_init_fn (callable, optional): If not None, this will be called on each
153
+ worker subprocess with the worker id (an int in ``[0, num_workers - 1]``) as
154
+ input, after seeding and before data loading. (default: None)
155
+
156
+ .. note:: By default, each worker will have its PyTorch seed set to
157
+ ``base_seed + worker_id``, where ``base_seed`` is a long generated
158
+ by main process using its RNG. However, seeds for other libraies
159
+ may be duplicated upon initializing workers (w.g., NumPy), causing
160
+ each worker to return identical random numbers. (See
161
+ :ref:`dataloader-workers-random-seed` section in FAQ.) You may
162
+ use ``torch.initial_seed()`` to access the PyTorch seed for each
163
+ worker in :attr:`worker_init_fn`, and use it to set other seeds
164
+ before data loading.
165
+
166
+ .. warning:: If ``spawn`` start method is used, :attr:`worker_init_fn` cannot be an
167
+ unpicklable object, e.g., a lambda function.
168
+ """
169
+
170
+ __initialized = False
171
+
172
+ def __init__(self, name, dataset, training=True, batch_size=1, shuffle=False, sampler=None, batch_sampler=None,
173
+ num_workers=0, epoch_interval=1, collate_fn=None, stack_dim=0, pin_memory=False, drop_last=False,
174
+ timeout=0, worker_init_fn=None):
175
+ if collate_fn is None:
176
+ if stack_dim == 0:
177
+ collate_fn = ltr_collate
178
+ elif stack_dim == 1:
179
+ collate_fn = ltr_collate_stack1
180
+ else:
181
+ raise ValueError('Stack dim no supported. Must be 0 or 1.')
182
+
183
+ super(LTRLoader, self).__init__(dataset, batch_size, shuffle, sampler, batch_sampler,
184
+ num_workers, collate_fn, pin_memory, drop_last,
185
+ timeout, worker_init_fn)
186
+
187
+ self.name = name
188
+ self.training = training
189
+ self.epoch_interval = epoch_interval
190
+ self.stack_dim = stack_dim
external/AR/ltr/data/processing.py ADDED
@@ -0,0 +1,662 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torchvision.transforms as transforms
3
+ from pytracking import TensorDict
4
+ import ltr.data.processing_utils as prutils
5
+
6
+
7
+ def stack_tensors(x):
8
+ if isinstance(x, (list, tuple)) and isinstance(x[0], torch.Tensor):
9
+ return torch.stack(x)
10
+ return x
11
+
12
+
13
+ class BaseProcessing:
14
+ """ Base class for Processing. Processing class is used to process the data returned by a dataset, before passing it
15
+ through the network. For example, it can be used to crop a search region around the object, apply various data
16
+ augmentations, etc."""
17
+ def __init__(self, transform=transforms.ToTensor(), train_transform=None, test_transform=None, joint_transform=None):
18
+ """
19
+ args:
20
+ transform - The set of transformations to be applied on the images. Used only if train_transform or
21
+ test_transform is None.
22
+ train_transform - The set of transformations to be applied on the train images. If None, the 'transform'
23
+ argument is used instead.
24
+ test_transform - The set of transformations to be applied on the test images. If None, the 'transform'
25
+ argument is used instead.
26
+ joint_transform - The set of transformations to be applied 'jointly' on the train and test images. For
27
+ example, it can be used to convert both test and train images to grayscale.
28
+ """
29
+ self.transform = {'train': transform if train_transform is None else train_transform,
30
+ 'test': transform if test_transform is None else test_transform,
31
+ 'joint': joint_transform}
32
+
33
+ def __call__(self, data: TensorDict):
34
+ raise NotImplementedError
35
+
36
+
37
+ class ATOMProcessing(BaseProcessing):
38
+ """ The processing class used for training ATOM. The images are processed in the following way.
39
+ First, the target bounding box is jittered by adding some noise. Next, a square region (called search region )
40
+ centered at the jittered target center, and of area search_area_factor^2 times the area of the jittered box is
41
+ cropped from the image. The reason for jittering the target box is to avoid learning the bias that the target is
42
+ always at the center of the search region. The search region is then resized to a fixed size given by the
43
+ argument output_sz. A set of proposals are then generated for the test images by jittering the ground truth box.
44
+
45
+ """
46
+
47
+ def __init__(self, search_area_factor, output_sz, center_jitter_factor, scale_jitter_factor, proposal_params,
48
+ mode='pair', *args, **kwargs):
49
+ """
50
+ args:
51
+ search_area_factor - The size of the search region relative to the target size.
52
+ output_sz - An integer, denoting the size to which the search region is resized. The search region is always
53
+ square.
54
+ center_jitter_factor - A dict containing the amount of jittering to be applied to the target center before
55
+ extracting the search region. See _get_jittered_box for how the jittering is done.
56
+ scale_jitter_factor - A dict containing the amount of jittering to be applied to the target size before
57
+ extracting the search region. See _get_jittered_box for how the jittering is done.
58
+ proposal_params - Arguments for the proposal generation process. See _generate_proposals for details.
59
+ mode - Either 'pair' or 'sequence'. If mode='sequence', then output has an extra dimension for frames
60
+ """
61
+ super().__init__(*args, **kwargs)
62
+ self.search_area_factor = search_area_factor
63
+ self.output_sz = output_sz
64
+ self.center_jitter_factor = center_jitter_factor
65
+ self.scale_jitter_factor = scale_jitter_factor
66
+ self.proposal_params = proposal_params
67
+ self.mode = mode
68
+
69
+ def _get_jittered_box(self, box, mode):
70
+ """ Jitter the input box
71
+ args:
72
+ box - input bounding box
73
+ mode - string 'train' or 'test' indicating train or test data
74
+
75
+ returns:
76
+ torch.Tensor - jittered box
77
+ """
78
+
79
+ jittered_size = box[2:4] * torch.exp(torch.randn(2) * self.scale_jitter_factor[mode])
80
+ max_offset = (jittered_size.prod().sqrt() * torch.tensor(self.center_jitter_factor[mode]).float())
81
+ jittered_center = box[0:2] + 0.5 * box[2:4] + max_offset * (torch.rand(2) - 0.5)
82
+
83
+ return torch.cat((jittered_center - 0.5 * jittered_size, jittered_size), dim=0)
84
+
85
+ def _generate_proposals(self, box):
86
+ """ Generates proposals by adding noise to the input box
87
+ args:
88
+ box - input box
89
+
90
+ returns:
91
+ torch.Tensor - Array of shape (num_proposals, 4) containing proposals
92
+ torch.Tensor - Array of shape (num_proposals,) containing IoU overlap of each proposal with the input box. The
93
+ IoU is mapped to [-1, 1]
94
+ """
95
+ # Generate proposals
96
+ num_proposals = self.proposal_params['boxes_per_frame']
97
+ proposal_method = self.proposal_params.get('proposal_method', 'default')
98
+
99
+ if proposal_method == 'default':
100
+ proposals = torch.zeros((num_proposals, 4))
101
+ gt_iou = torch.zeros(num_proposals)
102
+ for i in range(num_proposals):
103
+ proposals[i, :], gt_iou[i] = prutils.perturb_box(box, min_iou=self.proposal_params['min_iou'],
104
+ sigma_factor=self.proposal_params['sigma_factor'])
105
+ elif proposal_method == 'gmm':
106
+ proposals, _, _ = prutils.sample_box_gmm(box, self.proposal_params['proposal_sigma'],
107
+ num_samples=num_proposals)
108
+ gt_iou = prutils.iou(box.view(1,4), proposals.view(-1,4))
109
+
110
+ # Map to [-1, 1]
111
+ gt_iou = gt_iou * 2 - 1
112
+ return proposals, gt_iou
113
+
114
+ def __call__(self, data: TensorDict):
115
+ """
116
+ args:
117
+ data - The input data, should contain the following fields:
118
+ 'train_images', test_images', 'train_anno', 'test_anno'
119
+ returns:
120
+ TensorDict - output data block with following fields:
121
+ 'train_images', 'test_images', 'train_anno', 'test_anno', 'test_proposals', 'proposal_iou'
122
+ """
123
+ # Apply joint transforms
124
+ if self.transform['joint'] is not None:
125
+ data['train_images'], data['train_anno'] = self.transform['joint'](image=data['train_images'], bbox=data['train_anno'])
126
+ data['test_images'], data['test_anno'] = self.transform['joint'](image=data['test_images'], bbox=data['test_anno'], new_roll=False)
127
+
128
+ for s in ['train', 'test']:
129
+ assert self.mode == 'sequence' or len(data[s + '_images']) == 1, \
130
+ "In pair mode, num train/test frames must be 1"
131
+
132
+ # Add a uniform noise to the center pos
133
+ jittered_anno = [self._get_jittered_box(a, s) for a in data[s + '_anno']]
134
+
135
+ # Crop image region centered at jittered_anno box
136
+ crops, boxes = prutils.jittered_center_crop(data[s + '_images'], jittered_anno, data[s + '_anno'],
137
+ self.search_area_factor, self.output_sz)
138
+
139
+ # Apply transforms
140
+ data[s + '_images'], data[s + '_anno'] = self.transform[s](image=crops, bbox=boxes, joint=False)
141
+
142
+ # Generate proposals
143
+ frame2_proposals, gt_iou = zip(*[self._generate_proposals(a) for a in data['test_anno']])
144
+
145
+ data['test_proposals'] = list(frame2_proposals)
146
+ data['proposal_iou'] = list(gt_iou)
147
+
148
+ # Prepare output
149
+ if self.mode == 'sequence':
150
+ data = data.apply(stack_tensors)
151
+ else:
152
+ data = data.apply(lambda x: x[0] if isinstance(x, list) else x)
153
+
154
+ return data
155
+
156
+
157
+ class KLBBregProcessing(BaseProcessing):
158
+ """ Based on ATOMProcessing. It supports training ATOM using the Maximum Likelihood or KL-divergence based learning
159
+ introduced in [https://arxiv.org/abs/1909.12297] and in PrDiMP [https://arxiv.org/abs/2003.12565].
160
+ """
161
+
162
+ def __init__(self, search_area_factor, output_sz, center_jitter_factor, scale_jitter_factor, proposal_params,
163
+ mode='pair', *args, **kwargs):
164
+ """
165
+ args:
166
+ search_area_factor - The size of the search region relative to the target size.
167
+ output_sz - An integer, denoting the size to which the search region is resized. The search region is always
168
+ square.
169
+ center_jitter_factor - A dict containing the amount of jittering to be applied to the target center before
170
+ extracting the search region. See _get_jittered_box for how the jittering is done.
171
+ scale_jitter_factor - A dict containing the amount of jittering to be applied to the target size before
172
+ extracting the search region. See _get_jittered_box for how the jittering is done.
173
+ proposal_params - Arguments for the proposal generation process. See _generate_proposals for details.
174
+ mode - Either 'pair' or 'sequence'. If mode='sequence', then output has an extra dimension for frames
175
+ """
176
+ super().__init__(*args, **kwargs)
177
+ self.search_area_factor = search_area_factor
178
+ self.output_sz = output_sz
179
+ self.center_jitter_factor = center_jitter_factor
180
+ self.scale_jitter_factor = scale_jitter_factor
181
+ self.proposal_params = proposal_params
182
+ self.mode = mode
183
+
184
+ def _get_jittered_box(self, box, mode):
185
+ """ Jitter the input box
186
+ args:
187
+ box - input bounding box
188
+ mode - string 'train' or 'test' indicating train or test data
189
+
190
+ returns:
191
+ torch.Tensor - jittered box
192
+ """
193
+
194
+ jittered_size = box[2:4] * torch.exp(torch.randn(2) * self.scale_jitter_factor[mode])
195
+ max_offset = (jittered_size.prod().sqrt() * torch.tensor(self.center_jitter_factor[mode]).float())
196
+ jittered_center = box[0:2] + 0.5 * box[2:4] + max_offset * (torch.rand(2) - 0.5)
197
+
198
+ return torch.cat((jittered_center - 0.5 * jittered_size, jittered_size), dim=0)
199
+
200
+ def _generate_proposals(self, box):
201
+ """
202
+ """
203
+ # Generate proposals
204
+ proposals, proposal_density, gt_density = prutils.sample_box_gmm(box, self.proposal_params['proposal_sigma'],
205
+ gt_sigma=self.proposal_params['gt_sigma'],
206
+ num_samples=self.proposal_params[
207
+ 'boxes_per_frame'],
208
+ add_mean_box=self.proposal_params.get(
209
+ 'add_mean_box', False))
210
+
211
+ return proposals, proposal_density, gt_density
212
+
213
+ def __call__(self, data: TensorDict):
214
+ """
215
+ args:
216
+ data - The input data, should contain the following fields:
217
+ 'train_images', test_images', 'train_anno', 'test_anno'
218
+ returns:
219
+ TensorDict - output data block with following fields:
220
+ 'train_images', 'test_images', 'train_anno', 'test_anno', 'test_proposals', 'proposal_density', 'gt_density'
221
+ """
222
+ # Apply joint transforms
223
+ if self.transform['joint'] is not None:
224
+ data['train_images'], data['train_anno'] = self.transform['joint'](image=data['train_images'], bbox=data['train_anno'])
225
+ data['test_images'], data['test_anno'] = self.transform['joint'](image=data['test_images'], bbox=data['test_anno'], new_roll=False)
226
+
227
+ for s in ['train', 'test']:
228
+ assert self.mode == 'sequence' or len(data[s + '_images']) == 1, \
229
+ "In pair mode, num train/test frames must be 1"
230
+
231
+ # Add a uniform noise to the center pos
232
+ jittered_anno = [self._get_jittered_box(a, s) for a in data[s + '_anno']]
233
+
234
+ # Crop image region centered at jittered_anno box
235
+ crops, boxes, _ = prutils.jittered_center_crop(data[s + '_images'], jittered_anno, data[s + '_anno'],
236
+ self.search_area_factor, self.output_sz)
237
+
238
+ # Apply transforms
239
+ data[s + '_images'], data[s + '_anno'] = self.transform[s](image=crops, bbox=boxes, joint=False)
240
+
241
+ # Generate proposals
242
+ proposals, proposal_density, gt_density = zip(*[self._generate_proposals(a) for a in data['test_anno']])
243
+
244
+ data['test_proposals'] = proposals
245
+ data['proposal_density'] = proposal_density
246
+ data['gt_density'] = gt_density
247
+
248
+ # Prepare output
249
+ if self.mode == 'sequence':
250
+ data = data.apply(stack_tensors)
251
+ else:
252
+ data = data.apply(lambda x: x[0] if isinstance(x, list) else x)
253
+
254
+ return data
255
+
256
+
257
+ class ATOMwKLProcessing(BaseProcessing):
258
+ """Same as ATOMProcessing but using the GMM-based sampling of proposal boxes used in KLBBregProcessing."""
259
+ def __init__(self, search_area_factor, output_sz, center_jitter_factor, scale_jitter_factor, proposal_params,
260
+ mode='pair', *args, **kwargs):
261
+ super().__init__(*args, **kwargs)
262
+ self.search_area_factor = search_area_factor
263
+ self.output_sz = output_sz
264
+ self.center_jitter_factor = center_jitter_factor
265
+ self.scale_jitter_factor = scale_jitter_factor
266
+ self.proposal_params = proposal_params
267
+ self.mode = mode
268
+
269
+ def _get_jittered_box(self, box, mode):
270
+ """ Jitter the input box
271
+ args:
272
+ box - input bounding box
273
+ mode - string 'train' or 'test' indicating train or test data
274
+
275
+ returns:
276
+ torch.Tensor - jittered box
277
+ """
278
+
279
+ jittered_size = box[2:4] * torch.exp(torch.randn(2) * self.scale_jitter_factor[mode])
280
+ max_offset = (jittered_size.prod().sqrt() * torch.tensor(self.center_jitter_factor[mode]).float())
281
+ jittered_center = box[0:2] + 0.5 * box[2:4] + max_offset * (torch.rand(2) - 0.5)
282
+
283
+ return torch.cat((jittered_center - 0.5 * jittered_size, jittered_size), dim=0)
284
+
285
+ def _generate_proposals(self, box):
286
+ """
287
+ """
288
+ # Generate proposals
289
+ proposals, proposal_density, gt_density = prutils.sample_box_gmm(box, self.proposal_params['proposal_sigma'],
290
+ self.proposal_params['gt_sigma'],
291
+ self.proposal_params['boxes_per_frame'])
292
+
293
+ iou = prutils.iou_gen(proposals, box.view(1, 4))
294
+ return proposals, proposal_density, gt_density, iou
295
+
296
+ def __call__(self, data: TensorDict):
297
+ # Apply joint transforms
298
+ if self.transform['joint'] is not None:
299
+ data['train_images'], data['train_anno'] = self.transform['joint'](image=data['train_images'], bbox=data['train_anno'])
300
+ data['test_images'], data['test_anno'] = self.transform['joint'](image=data['test_images'], bbox=data['test_anno'], new_roll=False)
301
+
302
+ for s in ['train', 'test']:
303
+ assert self.mode == 'sequence' or len(data[s + '_images']) == 1, \
304
+ "In pair mode, num train/test frames must be 1"
305
+
306
+ # Add a uniform noise to the center pos
307
+ jittered_anno = [self._get_jittered_box(a, s) for a in data[s + '_anno']]
308
+
309
+ # Crop image region centered at jittered_anno box
310
+ crops, boxes = prutils.jittered_center_crop(data[s + '_images'], jittered_anno, data[s + '_anno'],
311
+ self.search_area_factor, self.output_sz)
312
+
313
+ # Apply transforms
314
+ data[s + '_images'], data[s + '_anno'] = self.transform[s](image=crops, bbox=boxes, joint=False)
315
+
316
+ # Generate proposals
317
+ proposals, proposal_density, gt_density, proposal_iou = zip(
318
+ *[self._generate_proposals(a) for a in data['test_anno']])
319
+
320
+ data['test_proposals'] = proposals
321
+ data['proposal_density'] = proposal_density
322
+ data['gt_density'] = gt_density
323
+ data['proposal_iou'] = proposal_iou
324
+ # Prepare output
325
+ if self.mode == 'sequence':
326
+ data = data.apply(stack_tensors)
327
+ else:
328
+ data = data.apply(lambda x: x[0] if isinstance(x, list) else x)
329
+
330
+ return data
331
+
332
+
333
+
334
+ class DiMPProcessing(BaseProcessing):
335
+ """ The processing class used for training DiMP. The images are processed in the following way.
336
+ First, the target bounding box is jittered by adding some noise. Next, a square region (called search region )
337
+ centered at the jittered target center, and of area search_area_factor^2 times the area of the jittered box is
338
+ cropped from the image. The reason for jittering the target box is to avoid learning the bias that the target is
339
+ always at the center of the search region. The search region is then resized to a fixed size given by the
340
+ argument output_sz. A Gaussian label centered at the target is generated for each image. These label functions are
341
+ used for computing the loss of the predicted classification model on the test images. A set of proposals are
342
+ also generated for the test images by jittering the ground truth box. These proposals are used to train the
343
+ bounding box estimating branch.
344
+
345
+ """
346
+
347
+ def __init__(self, search_area_factor, output_sz, center_jitter_factor, scale_jitter_factor, crop_type='replicate',
348
+ max_scale_change=None, mode='pair', proposal_params=None, label_function_params=None, *args, **kwargs):
349
+ """
350
+ args:
351
+ search_area_factor - The size of the search region relative to the target size.
352
+ output_sz - An integer, denoting the size to which the search region is resized. The search region is always
353
+ square.
354
+ center_jitter_factor - A dict containing the amount of jittering to be applied to the target center before
355
+ extracting the search region. See _get_jittered_box for how the jittering is done.
356
+ scale_jitter_factor - A dict containing the amount of jittering to be applied to the target size before
357
+ extracting the search region. See _get_jittered_box for how the jittering is done.
358
+ crop_type - If 'replicate', the boundary pixels are replicated in case the search region crop goes out of image.
359
+ If 'inside', the search region crop is shifted/shrunk to fit completely inside the image.
360
+ If 'inside_major', the search region crop is shifted/shrunk to fit completely inside one axis of the image.
361
+ max_scale_change - Maximum allowed scale change when performing the crop (only applicable for 'inside' and 'inside_major')
362
+ mode - Either 'pair' or 'sequence'. If mode='sequence', then output has an extra dimension for frames
363
+ proposal_params - Arguments for the proposal generation process. See _generate_proposals for details.
364
+ label_function_params - Arguments for the label generation process. See _generate_label_function for details.
365
+ """
366
+ super().__init__(*args, **kwargs)
367
+ self.search_area_factor = search_area_factor
368
+ self.output_sz = output_sz
369
+ self.center_jitter_factor = center_jitter_factor
370
+ self.scale_jitter_factor = scale_jitter_factor
371
+ self.crop_type = crop_type
372
+ self.mode = mode
373
+ self.max_scale_change = max_scale_change
374
+
375
+ self.proposal_params = proposal_params
376
+ self.label_function_params = label_function_params
377
+
378
+ def _get_jittered_box(self, box, mode):
379
+ """ Jitter the input box
380
+ args:
381
+ box - input bounding box
382
+ mode - string 'train' or 'test' indicating train or test data
383
+
384
+ returns:
385
+ torch.Tensor - jittered box
386
+ """
387
+
388
+ jittered_size = box[2:4] * torch.exp(torch.randn(2) * self.scale_jitter_factor[mode])
389
+ max_offset = (jittered_size.prod().sqrt() * torch.tensor(self.center_jitter_factor[mode]).float())
390
+ jittered_center = box[0:2] + 0.5 * box[2:4] + max_offset * (torch.rand(2) - 0.5)
391
+
392
+ return torch.cat((jittered_center - 0.5 * jittered_size, jittered_size), dim=0)
393
+
394
+ def _generate_proposals(self, box):
395
+ """ Generates proposals by adding noise to the input box
396
+ args:
397
+ box - input box
398
+
399
+ returns:
400
+ torch.Tensor - Array of shape (num_proposals, 4) containing proposals
401
+ torch.Tensor - Array of shape (num_proposals,) containing IoU overlap of each proposal with the input box. The
402
+ IoU is mapped to [-1, 1]
403
+ """
404
+ # Generate proposals
405
+ num_proposals = self.proposal_params['boxes_per_frame']
406
+ proposal_method = self.proposal_params.get('proposal_method', 'default')
407
+
408
+ if proposal_method == 'default':
409
+ proposals = torch.zeros((num_proposals, 4))
410
+ gt_iou = torch.zeros(num_proposals)
411
+
412
+ for i in range(num_proposals):
413
+ proposals[i, :], gt_iou[i] = prutils.perturb_box(box, min_iou=self.proposal_params['min_iou'],
414
+ sigma_factor=self.proposal_params['sigma_factor'])
415
+ elif proposal_method == 'gmm':
416
+ proposals, _, _ = prutils.sample_box_gmm(box, self.proposal_params['proposal_sigma'],
417
+ num_samples=num_proposals)
418
+ gt_iou = prutils.iou(box.view(1, 4), proposals.view(-1, 4))
419
+ else:
420
+ raise ValueError('Unknown proposal method.')
421
+
422
+ # Map to [-1, 1]
423
+ gt_iou = gt_iou * 2 - 1
424
+ return proposals, gt_iou
425
+
426
+ def _generate_label_function(self, target_bb):
427
+ """ Generates the gaussian label function centered at target_bb
428
+ args:
429
+ target_bb - target bounding box (num_images, 4)
430
+
431
+ returns:
432
+ torch.Tensor - Tensor of shape (num_images, label_sz, label_sz) containing the label for each sample
433
+ """
434
+
435
+ gauss_label = prutils.gaussian_label_function(target_bb.view(-1, 4), self.label_function_params['sigma_factor'],
436
+ self.label_function_params['kernel_sz'],
437
+ self.label_function_params['feature_sz'], self.output_sz,
438
+ end_pad_if_even=self.label_function_params.get('end_pad_if_even', True))
439
+
440
+ return gauss_label
441
+
442
+ def __call__(self, data: TensorDict):
443
+ """
444
+ args:
445
+ data - The input data, should contain the following fields:
446
+ 'train_images', test_images', 'train_anno', 'test_anno'
447
+ returns:
448
+ TensorDict - output data block with following fields:
449
+ 'train_images', 'test_images', 'train_anno', 'test_anno', 'test_proposals', 'proposal_iou',
450
+ 'test_label' (optional), 'train_label' (optional), 'test_label_density' (optional), 'train_label_density' (optional)
451
+ """
452
+
453
+ if self.transform['joint'] is not None:
454
+ data['train_images'], data['train_anno'] = self.transform['joint'](image=data['train_images'], bbox=data['train_anno'])
455
+ data['test_images'], data['test_anno'] = self.transform['joint'](image=data['test_images'], bbox=data['test_anno'], new_roll=False)
456
+
457
+ for s in ['train', 'test']:
458
+ assert self.mode == 'sequence' or len(data[s + '_images']) == 1, \
459
+ "In pair mode, num train/test frames must be 1"
460
+
461
+ # Add a uniform noise to the center pos
462
+ jittered_anno = [self._get_jittered_box(a, s) for a in data[s + '_anno']]
463
+
464
+ crops, boxes = prutils.target_image_crop(data[s + '_images'], jittered_anno, data[s + '_anno'],
465
+ self.search_area_factor, self.output_sz, mode=self.crop_type,
466
+ max_scale_change=self.max_scale_change)
467
+
468
+ data[s + '_images'], data[s + '_anno'] = self.transform[s](image=crops, bbox=boxes, joint=False)
469
+
470
+ # Generate proposals
471
+ if self.proposal_params:
472
+ frame2_proposals, gt_iou = zip(*[self._generate_proposals(a) for a in data['test_anno']])
473
+
474
+ data['test_proposals'] = list(frame2_proposals)
475
+ data['proposal_iou'] = list(gt_iou)
476
+
477
+ # Prepare output
478
+ if self.mode == 'sequence':
479
+ data = data.apply(stack_tensors)
480
+ else:
481
+ data = data.apply(lambda x: x[0] if isinstance(x, list) else x)
482
+
483
+ # Generate label functions
484
+ if self.label_function_params is not None:
485
+ data['train_label'] = self._generate_label_function(data['train_anno'])
486
+ data['test_label'] = self._generate_label_function(data['test_anno'])
487
+
488
+ return data
489
+
490
+
491
+ class KLDiMPProcessing(BaseProcessing):
492
+ """ The processing class used for training PrDiMP that additionally supports the probabilistic classifier and
493
+ bounding box regressor. See DiMPProcessing for details.
494
+ """
495
+
496
+ def __init__(self, search_area_factor, output_sz, center_jitter_factor, scale_jitter_factor, crop_type='replicate',
497
+ max_scale_change=None, mode='pair', proposal_params=None,
498
+ label_function_params=None, label_density_params=None, *args, **kwargs):
499
+ """
500
+ args:
501
+ search_area_factor - The size of the search region relative to the target size.
502
+ output_sz - An integer, denoting the size to which the search region is resized. The search region is always
503
+ square.
504
+ center_jitter_factor - A dict containing the amount of jittering to be applied to the target center before
505
+ extracting the search region. See _get_jittered_box for how the jittering is done.
506
+ scale_jitter_factor - A dict containing the amount of jittering to be applied to the target size before
507
+ extracting the search region. See _get_jittered_box for how the jittering is done.
508
+ crop_type - If 'replicate', the boundary pixels are replicated in case the search region crop goes out of image.
509
+ If 'inside', the search region crop is shifted/shrunk to fit completely inside the image.
510
+ If 'inside_major', the search region crop is shifted/shrunk to fit completely inside one axis of the image.
511
+ max_scale_change - Maximum allowed scale change when performing the crop (only applicable for 'inside' and 'inside_major')
512
+ mode - Either 'pair' or 'sequence'. If mode='sequence', then output has an extra dimension for frames
513
+ proposal_params - Arguments for the proposal generation process. See _generate_proposals for details.
514
+ label_function_params - Arguments for the label generation process. See _generate_label_function for details.
515
+ label_density_params - Arguments for the label density generation process. See _generate_label_function for details.
516
+ """
517
+ super().__init__(*args, **kwargs)
518
+ self.search_area_factor = search_area_factor
519
+ self.output_sz = output_sz
520
+ self.center_jitter_factor = center_jitter_factor
521
+ self.scale_jitter_factor = scale_jitter_factor
522
+ self.crop_type = crop_type
523
+ self.mode = mode
524
+ self.max_scale_change = max_scale_change
525
+
526
+ self.proposal_params = proposal_params
527
+ self.label_function_params = label_function_params
528
+ self.label_density_params = label_density_params
529
+
530
+ def _get_jittered_box(self, box, mode):
531
+ """ Jitter the input box
532
+ args:
533
+ box - input bounding box
534
+ mode - string 'train' or 'test' indicating train or test data
535
+
536
+ returns:
537
+ torch.Tensor - jittered box
538
+ """
539
+
540
+ jittered_size = box[2:4] * torch.exp(torch.randn(2) * self.scale_jitter_factor[mode])
541
+ max_offset = (jittered_size.prod().sqrt() * torch.tensor(self.center_jitter_factor[mode]).float())
542
+ jittered_center = box[0:2] + 0.5 * box[2:4] + max_offset * (torch.rand(2) - 0.5)
543
+
544
+ return torch.cat((jittered_center - 0.5 * jittered_size, jittered_size), dim=0)
545
+
546
+ def _generate_proposals(self, box):
547
+ """ Generate proposal sample boxes from a GMM proposal distribution and compute their ground-truth density.
548
+ This is used for ML and KL based regression learning of the bounding box regressor.
549
+ args:
550
+ box - input bounding box
551
+ """
552
+ # Generate proposals
553
+ proposals, proposal_density, gt_density = prutils.sample_box_gmm(box, self.proposal_params['proposal_sigma'],
554
+ gt_sigma=self.proposal_params['gt_sigma'],
555
+ num_samples=self.proposal_params['boxes_per_frame'],
556
+ add_mean_box=self.proposal_params.get('add_mean_box', False))
557
+
558
+ return proposals, proposal_density, gt_density
559
+
560
+ def _generate_label_function(self, target_bb):
561
+ """ Generates the gaussian label function centered at target_bb
562
+ args:
563
+ target_bb - target bounding box (num_images, 4)
564
+
565
+ returns:
566
+ torch.Tensor - Tensor of shape (num_images, label_sz, label_sz) containing the label for each sample
567
+ """
568
+
569
+ gauss_label = prutils.gaussian_label_function(target_bb.view(-1, 4), self.label_function_params['sigma_factor'],
570
+ self.label_function_params['kernel_sz'],
571
+ self.label_function_params['feature_sz'], self.output_sz,
572
+ end_pad_if_even=self.label_function_params.get('end_pad_if_even', True))
573
+
574
+ return gauss_label
575
+
576
+ def _generate_label_density(self, target_bb):
577
+ """ Generates the gaussian label density centered at target_bb
578
+ args:
579
+ target_bb - target bounding box (num_images, 4)
580
+
581
+ returns:
582
+ torch.Tensor - Tensor of shape (num_images, label_sz, label_sz) containing the label for each sample
583
+ """
584
+
585
+ feat_sz = self.label_density_params['feature_sz'] * self.label_density_params.get('interp_factor', 1)
586
+ gauss_label = prutils.gaussian_label_function(target_bb.view(-1, 4), self.label_density_params['sigma_factor'],
587
+ self.label_density_params['kernel_sz'],
588
+ feat_sz, self.output_sz,
589
+ end_pad_if_even=self.label_density_params.get('end_pad_if_even', True),
590
+ density=True,
591
+ uni_bias=self.label_density_params.get('uni_weight', 0.0))
592
+
593
+ gauss_label *= (gauss_label > self.label_density_params.get('threshold', 0.0)).float()
594
+
595
+ if self.label_density_params.get('normalize', False):
596
+ g_sum = gauss_label.sum(dim=(-2,-1))
597
+ valid = g_sum>0.01
598
+ gauss_label[valid, :, :] /= g_sum[valid].view(-1, 1, 1)
599
+ gauss_label[~valid, :, :] = 1.0 / (gauss_label.shape[-2] * gauss_label.shape[-1])
600
+
601
+ gauss_label *= 1.0 - self.label_density_params.get('shrink', 0.0)
602
+
603
+ return gauss_label
604
+
605
+ def __call__(self, data: TensorDict):
606
+ """
607
+ args:
608
+ data - The input data, should contain the following fields:
609
+ 'train_images', test_images', 'train_anno', 'test_anno'
610
+ returns:
611
+ TensorDict - output data block with following fields:
612
+ 'train_images', 'test_images', 'train_anno', 'test_anno', 'test_proposals', 'proposal_density', 'gt_density',
613
+ 'test_label' (optional), 'train_label' (optional), 'test_label_density' (optional), 'train_label_density' (optional)
614
+ """
615
+
616
+ if self.transform['joint'] is not None:
617
+ data['train_images'], data['train_anno'] = self.transform['joint'](image=data['train_images'], bbox=data['train_anno'])
618
+ data['test_images'], data['test_anno'] = self.transform['joint'](image=data['test_images'], bbox=data['test_anno'], new_roll=False)
619
+
620
+ for s in ['train', 'test']:
621
+ assert self.mode == 'sequence' or len(data[s + '_images']) == 1, \
622
+ "In pair mode, num train/test frames must be 1"
623
+
624
+ # Add a uniform noise to the center pos
625
+ jittered_anno = [self._get_jittered_box(a, s) for a in data[s + '_anno']]
626
+
627
+ crops, boxes = prutils.target_image_crop(data[s + '_images'], jittered_anno, data[s + '_anno'],
628
+ self.search_area_factor, self.output_sz, mode=self.crop_type,
629
+ max_scale_change=self.max_scale_change)
630
+
631
+ data[s + '_images'], data[s + '_anno'] = self.transform[s](image=crops, bbox=boxes, joint=False)
632
+
633
+ # Generate proposals
634
+ proposals, proposal_density, gt_density = zip(*[self._generate_proposals(a) for a in data['test_anno']])
635
+
636
+ data['test_proposals'] = proposals
637
+ data['proposal_density'] = proposal_density
638
+ data['gt_density'] = gt_density
639
+
640
+ for s in ['train', 'test']:
641
+ is_distractor = data.get('is_distractor_{}_frame'.format(s), None)
642
+ if is_distractor is not None:
643
+ for is_dist, box in zip(is_distractor, data[s+'_anno']):
644
+ if is_dist:
645
+ box[0] = 99999999.9
646
+ box[1] = 99999999.9
647
+
648
+ # Prepare output
649
+ if self.mode == 'sequence':
650
+ data = data.apply(stack_tensors)
651
+ else:
652
+ data = data.apply(lambda x: x[0] if isinstance(x, list) else x)
653
+
654
+ # Generate label functions
655
+ if self.label_function_params is not None:
656
+ data['train_label'] = self._generate_label_function(data['train_anno'])
657
+ data['test_label'] = self._generate_label_function(data['test_anno'])
658
+ if self.label_density_params is not None:
659
+ data['train_label_density'] = self._generate_label_density(data['train_anno'])
660
+ data['test_label_density'] = self._generate_label_density(data['test_anno'])
661
+
662
+ return data
external/AR/ltr/data/processing_utils.py ADDED
@@ -0,0 +1,627 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import math
3
+ import cv2 as cv
4
+ import random
5
+ import torch.nn.functional as F
6
+ from .bounding_box_utils import rect_to_rel, rel_to_rect
7
+
8
+
9
+ def sample_target(im, target_bb, search_area_factor, output_sz=None, mask=None):
10
+ """ Extracts a square crop centered at target_bb box, of area search_area_factor^2 times target_bb area
11
+
12
+ args:
13
+ im - cv image
14
+ target_bb - target box [x, y, w, h]
15
+ search_area_factor - Ratio of crop size to target size
16
+ output_sz - (float) Size to which the extracted crop is resized (always square). If None, no resizing is done.
17
+
18
+ returns:
19
+ cv image - extracted crop
20
+ float - the factor by which the crop has been resized to make the crop size equal output_size
21
+ """
22
+ x, y, w, h = target_bb.tolist()
23
+
24
+ # Crop image
25
+ crop_sz = math.ceil(math.sqrt(w * h) * search_area_factor)
26
+
27
+ if crop_sz < 1:
28
+ raise Exception('Too small bounding box.')
29
+
30
+ x1 = round(x + 0.5 * w - crop_sz * 0.5)
31
+ x2 = x1 + crop_sz
32
+
33
+ y1 = round(y + 0.5 * h - crop_sz * 0.5)
34
+ y2 = y1 + crop_sz
35
+
36
+ x1_pad = max(0, -x1)
37
+ x2_pad = max(x2 - im.shape[1] + 1, 0)
38
+
39
+ y1_pad = max(0, -y1)
40
+ y2_pad = max(y2 - im.shape[0] + 1, 0)
41
+
42
+ # Crop target
43
+ im_crop = im[y1 + y1_pad:y2 - y2_pad, x1 + x1_pad:x2 - x2_pad, :]
44
+ if mask is not None:
45
+ mask_crop = mask[y1 + y1_pad:y2 - y2_pad, x1 + x1_pad:x2 - x2_pad]
46
+
47
+ # Pad
48
+ im_crop_padded = cv.copyMakeBorder(im_crop, y1_pad, y2_pad, x1_pad, x2_pad, cv.BORDER_REPLICATE)
49
+ if mask is not None:
50
+ mask_crop_padded = F.pad(mask_crop, pad=(x1_pad, x2_pad, y1_pad, y2_pad), mode='constant', value=0)
51
+
52
+ if output_sz is not None:
53
+ resize_factor = output_sz / crop_sz
54
+ im_crop_padded = cv.resize(im_crop_padded, (output_sz, output_sz))
55
+
56
+ if mask is None:
57
+ return im_crop_padded, resize_factor
58
+ mask_crop_padded = \
59
+ F.interpolate(mask_crop_padded[None, None], (output_sz, output_sz), mode='bilinear', align_corners=False)[0, 0]
60
+ return im_crop_padded, resize_factor, mask_crop_padded
61
+
62
+ else:
63
+ if mask is None:
64
+ return im_crop_padded, 1.0
65
+ return im_crop_padded, 1.0, mask_crop_padded
66
+
67
+
68
+ def transform_image_to_crop(box_in: torch.Tensor, box_extract: torch.Tensor, resize_factor: float,
69
+ crop_sz: torch.Tensor) -> torch.Tensor:
70
+ """ Transform the box co-ordinates from the original image co-ordinates to the co-ordinates of the cropped image
71
+ args:
72
+ box_in - the box for which the co-ordinates are to be transformed
73
+ box_extract - the box about which the image crop has been extracted.
74
+ resize_factor - the ratio between the original image scale and the scale of the image crop
75
+ crop_sz - size of the cropped image
76
+
77
+ returns:
78
+ torch.Tensor - transformed co-ordinates of box_in
79
+ """
80
+ box_extract_center = box_extract[0:2] + 0.5 * box_extract[2:4]
81
+
82
+ box_in_center = box_in[0:2] + 0.5 * box_in[2:4]
83
+
84
+ box_out_center = (crop_sz - 1) / 2 + (box_in_center - box_extract_center) * resize_factor
85
+ box_out_wh = box_in[2:4] * resize_factor
86
+
87
+ box_out = torch.cat((box_out_center - 0.5 * box_out_wh, box_out_wh))
88
+ return box_out
89
+
90
+
91
+ def jittered_center_crop(frames, box_extract, box_gt, search_area_factor, output_sz, masks=None):
92
+ """ For each frame in frames, extracts a square crop centered at box_extract, of area search_area_factor^2
93
+ times box_extract area. The extracted crops are then resized to output_sz. Further, the co-ordinates of the box
94
+ box_gt are transformed to the image crop co-ordinates
95
+
96
+ args:
97
+ frames - list of frames
98
+ box_extract - list of boxes of same length as frames. The crops are extracted using anno_extract
99
+ box_gt - list of boxes of same length as frames. The co-ordinates of these boxes are transformed from
100
+ image co-ordinates to the crop co-ordinates
101
+ search_area_factor - The area of the extracted crop is search_area_factor^2 times box_extract area
102
+ output_sz - The size to which the extracted crops are resized
103
+
104
+ returns:
105
+ list - list of image crops
106
+ list - box_gt location in the crop co-ordinates
107
+ """
108
+
109
+ if masks is None:
110
+ crops_resize_factors = [sample_target(f, a, search_area_factor, output_sz)
111
+ for f, a in zip(frames, box_extract)]
112
+ frames_crop, resize_factors = zip(*crops_resize_factors)
113
+ masks_crop = None
114
+ else:
115
+ crops_resize_factors = [sample_target(f, a, search_area_factor, output_sz, m)
116
+ for f, a, m in zip(frames, box_extract, masks)]
117
+ frames_crop, resize_factors, masks_crop = zip(*crops_resize_factors)
118
+
119
+ crop_sz = torch.Tensor([output_sz, output_sz])
120
+
121
+ # find the bb location in the crop
122
+ box_crop = [transform_image_to_crop(a_gt, a_ex, rf, crop_sz)
123
+ for a_gt, a_ex, rf in zip(box_gt, box_extract, resize_factors)]
124
+
125
+ return frames_crop, box_crop, masks_crop
126
+
127
+
128
+ def sample_target_adaptive(im, target_bb, search_area_factor, output_sz, mode: str = 'replicate',
129
+ max_scale_change=None, mask=None):
130
+ """ Extracts a crop centered at target_bb box, of area search_area_factor^2. If the crop area contains regions
131
+ outside the image, it is shifted so that the it is inside the image. Further, if the crop area exceeds the image
132
+ size, a smaller crop which fits the image is returned instead.
133
+
134
+ args:
135
+ im - Input numpy image to crop.
136
+ target_bb - target box [x, y, w, h]
137
+ search_area_factor - Ratio of crop size to target size
138
+ output_sz - (float) Size to which the extracted crop is resized (always square). If None, no resizing is done.
139
+ mode - If 'replicate', the boundary pixels are replicated in case the search region crop goes out of image.
140
+ If 'inside', the search region crop is shifted/shrunk to fit completely inside the image.
141
+ If 'inside_major', the search region crop is shifted/shrunk to fit completely inside one axis of the image.
142
+ max_scale_change - Maximum allowed scale change when performing the crop (only applicable for 'inside' and 'inside_major')
143
+ mask - Optional mask to apply the same crop.
144
+
145
+ returns:
146
+ numpy image - Extracted crop.
147
+ torch.Tensor - A bounding box denoting the cropped region in the image.
148
+ numpy mask - Cropped mask returned only if mask is not None.
149
+ """
150
+
151
+ if max_scale_change is None:
152
+ max_scale_change = float('inf')
153
+ if isinstance(output_sz, (float, int)):
154
+ output_sz = (output_sz, output_sz)
155
+ output_sz = torch.Tensor(output_sz)
156
+
157
+ im_h = im.shape[0]
158
+ im_w = im.shape[1]
159
+
160
+ bbx, bby, bbw, bbh = target_bb.tolist()
161
+
162
+ # Crop image
163
+ crop_sz_x, crop_sz_y = (output_sz * (
164
+ target_bb[2:].prod() / output_sz.prod()).sqrt() * search_area_factor).ceil().long().tolist()
165
+
166
+ # Get new sample size if forced inside the image
167
+ if mode == 'inside' or mode == 'inside_major':
168
+ # Calculate rescaling factor if outside the image
169
+ rescale_factor = [crop_sz_x / im_w, crop_sz_y / im_h]
170
+ if mode == 'inside':
171
+ rescale_factor = max(rescale_factor)
172
+ elif mode == 'inside_major':
173
+ rescale_factor = min(rescale_factor)
174
+ rescale_factor = min(max(1, rescale_factor), max_scale_change)
175
+
176
+ crop_sz_x = math.floor(crop_sz_x / rescale_factor)
177
+ crop_sz_y = math.floor(crop_sz_y / rescale_factor)
178
+
179
+ if crop_sz_x < 1 or crop_sz_y < 1:
180
+ raise Exception('Too small bounding box.')
181
+
182
+ x1 = round(bbx + 0.5 * bbw - crop_sz_x * 0.5)
183
+ x2 = x1 + crop_sz_x
184
+
185
+ y1 = round(bby + 0.5 * bbh - crop_sz_y * 0.5)
186
+ y2 = y1 + crop_sz_y
187
+
188
+ # Move box inside image
189
+ shift_x = max(0, -x1) + min(0, im_w - x2)
190
+ x1 += shift_x
191
+ x2 += shift_x
192
+
193
+ shift_y = max(0, -y1) + min(0, im_h - y2)
194
+ y1 += shift_y
195
+ y2 += shift_y
196
+
197
+ out_x = (max(0, -x1) + max(0, x2 - im_w)) // 2
198
+ out_y = (max(0, -y1) + max(0, y2 - im_h)) // 2
199
+ shift_x = (-x1 - out_x) * (out_x > 0)
200
+ shift_y = (-y1 - out_y) * (out_y > 0)
201
+
202
+ x1 += shift_x
203
+ x2 += shift_x
204
+ y1 += shift_y
205
+ y2 += shift_y
206
+
207
+ x1_pad = max(0, -x1)
208
+ x2_pad = max(x2 - im.shape[1] + 1, 0)
209
+
210
+ y1_pad = max(0, -y1)
211
+ y2_pad = max(y2 - im.shape[0] + 1, 0)
212
+
213
+ # Crop target
214
+ im_crop = im[y1 + y1_pad:y2 - y2_pad, x1 + x1_pad:x2 - x2_pad, :]
215
+
216
+ if mask is not None:
217
+ mask_crop = mask[y1 + y1_pad:y2 - y2_pad, x1 + x1_pad:x2 - x2_pad]
218
+
219
+ # Pad
220
+ im_crop_padded = cv.copyMakeBorder(im_crop, y1_pad, y2_pad, x1_pad, x2_pad, cv.BORDER_REPLICATE)
221
+
222
+ if mask is not None:
223
+ mask_crop_padded = F.pad(mask_crop, pad=(x1_pad, x2_pad, y1_pad, y2_pad), mode='constant', value=0)
224
+
225
+ # Resize image
226
+ im_out = cv.resize(im_crop_padded, tuple(output_sz.long().tolist()))
227
+
228
+ if mask is not None:
229
+ mask_out = \
230
+ F.interpolate(mask_crop_padded[None, None], tuple(output_sz.flip(0).long().tolist()), mode='nearest')[0, 0]
231
+
232
+ crop_box = torch.Tensor([x1, y1, x2 - x1, y2 - y1])
233
+
234
+ if mask is None:
235
+ return im_out, crop_box
236
+ else:
237
+ return im_out, crop_box, mask_out
238
+
239
+
240
+ def crop_and_resize(im, box, crop_bb, output_sz, mask=None):
241
+ if isinstance(output_sz, (float, int)):
242
+ output_sz = (output_sz, output_sz)
243
+
244
+ im_h = im.shape[0]
245
+ im_w = im.shape[1]
246
+
247
+ if crop_bb[2] < 1 or crop_bb[3] < 1:
248
+ raise Exception('Too small bounding box.')
249
+
250
+ x1 = crop_bb[0]
251
+ x2 = crop_bb[0] + crop_bb[2]
252
+
253
+ y1 = crop_bb[1]
254
+ y2 = crop_bb[1] + crop_bb[3]
255
+
256
+ x1_pad = max(0, -x1)
257
+ x2_pad = max(x2 - im.shape[1] + 1, 0)
258
+
259
+ y1_pad = max(0, -y1)
260
+ y2_pad = max(y2 - im.shape[0] + 1, 0)
261
+
262
+ # Crop target
263
+ im_crop = im[y1 + y1_pad:y2 - y2_pad, x1 + x1_pad:x2 - x2_pad, :]
264
+
265
+ if mask is not None:
266
+ mask_crop = mask[y1 + y1_pad:y2 - y2_pad, x1 + x1_pad:x2 - x2_pad]
267
+
268
+ # Pad
269
+ im_crop_padded = cv.copyMakeBorder(im_crop, y1_pad, y2_pad, x1_pad, x2_pad, cv.BORDER_REPLICATE)
270
+
271
+ if mask is not None:
272
+ mask_crop_padded = F.pad(mask_crop, pad=(x1_pad, x2_pad, y1_pad, y2_pad), mode='constant', value=0)
273
+
274
+ # Resize image
275
+ im_out = cv.resize(im_crop_padded, output_sz)
276
+
277
+ if mask is not None:
278
+ mask_out = F.interpolate(mask_crop_padded[None, None], (output_sz[1], output_sz[0]), mode='nearest')[0, 0]
279
+
280
+ rescale_factor = output_sz[0] / crop_bb[2]
281
+
282
+ # Hack
283
+ if box is not None:
284
+ box_crop = box.clone()
285
+ box_crop[0] -= crop_bb[0]
286
+ box_crop[1] -= crop_bb[1]
287
+
288
+ box_crop *= rescale_factor
289
+ else:
290
+ box_crop = None
291
+
292
+ if mask is None:
293
+ return im_out, box_crop
294
+ else:
295
+ return im_out, box_crop, mask_out
296
+
297
+
298
+ def transform_box_to_crop(box: torch.Tensor, crop_box: torch.Tensor, crop_sz: torch.Tensor) -> torch.Tensor:
299
+ """ Transform the box co-ordinates from the original image co-ordinates to the co-ordinates of the cropped image
300
+ args:
301
+ box - the box for which the co-ordinates are to be transformed
302
+ crop_box - bounding box defining the crop in the original image
303
+ crop_sz - size of the cropped image
304
+
305
+ returns:
306
+ torch.Tensor - transformed co-ordinates of box_in
307
+ """
308
+
309
+ box_out = box.clone()
310
+ box_out[:2] -= crop_box[:2]
311
+
312
+ scale_factor = crop_sz / crop_box[2:]
313
+
314
+ box_out[:2] *= scale_factor
315
+ box_out[2:] *= scale_factor
316
+ return box_out
317
+
318
+
319
+ def target_image_crop(frames, box_extract, box_gt, search_area_factor, output_sz, mode: str = 'replicate',
320
+ max_scale_change=None, masks=None):
321
+ """ For each frame in frames, extracts a square crop centered at box_extract, of area search_area_factor^2
322
+ times box_extract area. If the crop area contains regions outside the image, it is shifted / shrunk so that it
323
+ completely fits inside the image. The extracted crops are then resized to output_sz. Further, the co-ordinates of
324
+ the box box_gt are transformed to the image crop co-ordinates
325
+
326
+ args:
327
+ frames - list of frames
328
+ box_extract - list of boxes of same length as frames. The crops are extracted using anno_extract
329
+ box_gt - list of boxes of same length as frames. The co-ordinates of these boxes are transformed from
330
+ image co-ordinates to the crop co-ordinates
331
+ search_area_factor - The area of the extracted crop is search_area_factor^2 times box_extract area
332
+ output_sz - The size to which the extracted crops are resized
333
+ mode - If 'replicate', the boundary pixels are replicated in case the search region crop goes out of image.
334
+ If 'inside', the search region crop is shifted/shrunk to fit completely inside the image.
335
+ If 'inside_major', the search region crop is shifted/shrunk to fit completely inside one axis of the image.
336
+ max_scale_change - Maximum allowed scale change when performing the crop (only applicable for 'inside' and 'inside_major')
337
+ masks - Optional masks to apply the same crop.
338
+
339
+ returns:
340
+ list - list of image crops
341
+ list - box_gt location in the crop co-ordinates
342
+ """
343
+
344
+ if isinstance(output_sz, (float, int)):
345
+ output_sz = (output_sz, output_sz)
346
+
347
+ if masks is None:
348
+ frame_crops_boxes = [sample_target_adaptive(f, a, search_area_factor, output_sz, mode, max_scale_change)
349
+ for f, a in zip(frames, box_extract)]
350
+
351
+ frames_crop, crop_boxes = zip(*frame_crops_boxes)
352
+ else:
353
+ frame_crops_boxes_masks = [
354
+ sample_target_adaptive(f, a, search_area_factor, output_sz, mode, max_scale_change, mask=m)
355
+ for f, a, m in zip(frames, box_extract, masks)]
356
+
357
+ frames_crop, crop_boxes, masks_crop = zip(*frame_crops_boxes_masks)
358
+
359
+ crop_sz = torch.Tensor(output_sz)
360
+
361
+ # find the bb location in the crop
362
+ box_crop = [transform_box_to_crop(bb_gt, crop_bb, crop_sz)
363
+ for bb_gt, crop_bb in zip(box_gt, crop_boxes)]
364
+
365
+ if masks is None:
366
+ return frames_crop, box_crop
367
+ else:
368
+ return frames_crop, box_crop, masks_crop
369
+
370
+
371
+ def iou(reference, proposals):
372
+ """Compute the IoU between a reference box with multiple proposal boxes.
373
+
374
+ args:
375
+ reference - Tensor of shape (1, 4).
376
+ proposals - Tensor of shape (num_proposals, 4)
377
+
378
+ returns:
379
+ torch.Tensor - Tensor of shape (num_proposals,) containing IoU of reference box with each proposal box.
380
+ """
381
+
382
+ # Intersection box
383
+ tl = torch.max(reference[:, :2], proposals[:, :2])
384
+ br = torch.min(reference[:, :2] + reference[:, 2:], proposals[:, :2] + proposals[:, 2:])
385
+ sz = (br - tl).clamp(0)
386
+
387
+ # Area
388
+ intersection = sz.prod(dim=1)
389
+ union = reference[:, 2:].prod(dim=1) + proposals[:, 2:].prod(dim=1) - intersection
390
+
391
+ return intersection / union
392
+
393
+
394
+ def rand_uniform(a, b, shape=1):
395
+ """ sample numbers uniformly between a and b.
396
+ args:
397
+ a - lower bound
398
+ b - upper bound
399
+ shape - shape of the output tensor
400
+
401
+ returns:
402
+ torch.Tensor - tensor of shape=shape
403
+ """
404
+ return (b - a) * torch.rand(shape) + a
405
+
406
+
407
+ def perturb_box(box, min_iou=0.5, sigma_factor=0.1):
408
+ """ Perturb the input box by adding gaussian noise to the co-ordinates
409
+
410
+ args:
411
+ box - input box
412
+ min_iou - minimum IoU overlap between input box and the perturbed box
413
+ sigma_factor - amount of perturbation, relative to the box size. Can be either a single element, or a list of
414
+ sigma_factors, in which case one of them will be uniformly sampled. Further, each of the
415
+ sigma_factor element can be either a float, or a tensor
416
+ of shape (4,) specifying the sigma_factor per co-ordinate
417
+
418
+ returns:
419
+ torch.Tensor - the perturbed box
420
+ """
421
+
422
+ if isinstance(sigma_factor, list):
423
+ # If list, sample one sigma_factor as current sigma factor
424
+ c_sigma_factor = random.choice(sigma_factor)
425
+ else:
426
+ c_sigma_factor = sigma_factor
427
+
428
+ if not isinstance(c_sigma_factor, torch.Tensor):
429
+ c_sigma_factor = c_sigma_factor * torch.ones(4)
430
+
431
+ perturb_factor = torch.sqrt(box[2] * box[3]) * c_sigma_factor
432
+
433
+ # multiple tries to ensure that the perturbed box has iou > min_iou with the input box
434
+ for i_ in range(100):
435
+ c_x = box[0] + 0.5 * box[2]
436
+ c_y = box[1] + 0.5 * box[3]
437
+ c_x_per = random.gauss(c_x, perturb_factor[0])
438
+ c_y_per = random.gauss(c_y, perturb_factor[1])
439
+
440
+ w_per = random.gauss(box[2], perturb_factor[2])
441
+ h_per = random.gauss(box[3], perturb_factor[3])
442
+
443
+ if w_per <= 1:
444
+ w_per = box[2] * rand_uniform(0.15, 0.5)
445
+
446
+ if h_per <= 1:
447
+ h_per = box[3] * rand_uniform(0.15, 0.5)
448
+
449
+ box_per = torch.Tensor([c_x_per - 0.5 * w_per, c_y_per - 0.5 * h_per, w_per, h_per]).round()
450
+
451
+ if box_per[2] <= 1:
452
+ box_per[2] = box[2] * rand_uniform(0.15, 0.5)
453
+
454
+ if box_per[3] <= 1:
455
+ box_per[3] = box[3] * rand_uniform(0.15, 0.5)
456
+
457
+ box_iou = iou(box.view(1, 4), box_per.view(1, 4))
458
+
459
+ # if there is sufficient overlap, return
460
+ if box_iou > min_iou:
461
+ return box_per, box_iou
462
+
463
+ # else reduce the perturb factor
464
+ perturb_factor *= 0.9
465
+
466
+ return box_per, box_iou
467
+
468
+
469
+ def gauss_1d(sz, sigma, center, end_pad=0, density=False):
470
+ k = torch.arange(-(sz - 1) / 2, (sz + 1) / 2 + end_pad).reshape(1, -1)
471
+ gauss = torch.exp(-1.0 / (2 * sigma ** 2) * (k - center.reshape(-1, 1)) ** 2)
472
+ if density:
473
+ gauss /= math.sqrt(2 * math.pi) * sigma
474
+ return gauss
475
+
476
+
477
+ def gauss_2d(sz, sigma, center, end_pad=(0, 0), density=False):
478
+ if isinstance(sigma, (float, int)):
479
+ sigma = (sigma, sigma)
480
+ return gauss_1d(sz[0].item(), sigma[0], center[:, 0], end_pad[0], density).reshape(center.shape[0], 1, -1) * \
481
+ gauss_1d(sz[1].item(), sigma[1], center[:, 1], end_pad[1], density).reshape(center.shape[0], -1, 1)
482
+
483
+
484
+ def gaussian_label_function(target_bb, sigma_factor, kernel_sz, feat_sz, image_sz, end_pad_if_even=True, density=False,
485
+ uni_bias=0):
486
+ """Construct Gaussian label function."""
487
+
488
+ if isinstance(kernel_sz, (float, int)):
489
+ kernel_sz = (kernel_sz, kernel_sz)
490
+ if isinstance(feat_sz, (float, int)):
491
+ feat_sz = (feat_sz, feat_sz)
492
+ if isinstance(image_sz, (float, int)):
493
+ image_sz = (image_sz, image_sz)
494
+
495
+ image_sz = torch.Tensor(image_sz)
496
+ feat_sz = torch.Tensor(feat_sz)
497
+
498
+ target_center = target_bb[:, 0:2] + 0.5 * target_bb[:, 2:4]
499
+ target_center_norm = (target_center - image_sz / 2) / image_sz
500
+
501
+ center = feat_sz * target_center_norm + 0.5 * \
502
+ torch.Tensor([(kernel_sz[0] + 1) % 2, (kernel_sz[1] + 1) % 2])
503
+
504
+ sigma = sigma_factor * feat_sz.prod().sqrt().item()
505
+
506
+ if end_pad_if_even:
507
+ end_pad = (int(kernel_sz[0] % 2 == 0), int(kernel_sz[1] % 2 == 0))
508
+ else:
509
+ end_pad = (0, 0)
510
+
511
+ gauss_label = gauss_2d(feat_sz, sigma, center, end_pad, density=density)
512
+ if density:
513
+ sz = (feat_sz + torch.Tensor(end_pad)).prod()
514
+ label = (1.0 - uni_bias) * gauss_label + uni_bias / sz
515
+ else:
516
+ label = gauss_label + uni_bias
517
+ return label
518
+
519
+
520
+ def gauss_density_centered(x, std):
521
+ """Evaluate the probability density of a Gaussian centered at zero.
522
+ args:
523
+ x - Samples.
524
+ std - List of standard deviations
525
+ """
526
+ return torch.exp(-0.5 * (x / std) ** 2) / (math.sqrt(2 * math.pi) * std)
527
+
528
+
529
+ def gmm_density_centered(x, std):
530
+ """Evaluate the probability density of a GMM centered at zero.
531
+ args:
532
+ x - Samples. Assumes dim=-1 is the component dimension and dim=-2 is feature dimension. Rest are sample dimension.
533
+ std - Tensor of standard deviations
534
+ """
535
+ if x.dim() == std.dim() - 1:
536
+ x = x.unsqueeze(-1)
537
+ elif not (x.dim() == std.dim() and x.shape[-1] == 1):
538
+ raise ValueError('Last dimension must be the gmm stds.')
539
+ return gauss_density_centered(x, std).prod(-2).mean(-1)
540
+
541
+
542
+ def sample_gmm_centered(std, num_samples=1):
543
+ """Sample from a GMM distribution centered at zero:
544
+ args:
545
+ std - Tensor of standard deviations
546
+ num_samples - number of samples
547
+ """
548
+ num_components = std.shape[-1]
549
+ num_dims = std.numel() // num_components
550
+
551
+ std = std.view(1, num_dims, num_components)
552
+
553
+ # Sample component ids
554
+ k = torch.randint(num_components, (num_samples,), dtype=torch.int64)
555
+ std_samp = std[0, :, k].t()
556
+
557
+ # Sample
558
+ x_centered = std_samp * torch.randn(num_samples, num_dims)
559
+ prob_dens = gmm_density_centered(x_centered, std)
560
+
561
+ return x_centered, prob_dens
562
+
563
+
564
+ def sample_gmm(mean, std, num_samples=1):
565
+ """Sample from a GMM distribution:
566
+ args:
567
+ mean - a single mean vector
568
+ std - Tensor of standard deviations
569
+ num_samples - number of samples
570
+ """
571
+ num_dims = mean.numel()
572
+ num_components = std.shape[-1]
573
+
574
+ mean = mean.view(1, num_dims)
575
+ std = std.view(1, -1, num_components)
576
+
577
+ # Sample component ids
578
+ k = torch.randint(num_components, (num_samples,), dtype=torch.int64)
579
+ std_samp = std[0, :, k].t()
580
+
581
+ # Sample
582
+ x_centered = std_samp * torch.randn(num_samples, num_dims)
583
+ x = x_centered + mean
584
+ prob_dens = gmm_density_centered(x_centered, std)
585
+
586
+ return x, prob_dens
587
+
588
+
589
+ def sample_box_gmm(mean_box, proposal_sigma, gt_sigma=None, num_samples=1, add_mean_box=False):
590
+ """Sample boxes from a Gaussian mixture model.
591
+ args:
592
+ mean_box - Center (or mean) bounding box
593
+ proposal_sigma - List of standard deviations for each Gaussian
594
+ gt_sigma - Standard deviation of the ground truth distribution
595
+ num_samples - Number of sampled boxes
596
+ add_mean_box - Also add mean box as first element
597
+
598
+ returns:
599
+ proposals, proposal density and ground truth density for all samples
600
+ """
601
+ center_std = torch.Tensor([s[0] for s in proposal_sigma])
602
+ sz_std = torch.Tensor([s[1] for s in proposal_sigma])
603
+ std = torch.stack([center_std, center_std, sz_std, sz_std])
604
+
605
+ mean_box = mean_box.view(1, 4)
606
+ sz_norm = mean_box[:, 2:].clone()
607
+
608
+ # Sample boxes
609
+ proposals_rel_centered, proposal_density = sample_gmm_centered(std, num_samples)
610
+
611
+ # Add mean and map back
612
+ mean_box_rel = rect_to_rel(mean_box, sz_norm)
613
+ proposals_rel = proposals_rel_centered + mean_box_rel
614
+ proposals = rel_to_rect(proposals_rel, sz_norm)
615
+
616
+ if gt_sigma is None or gt_sigma[0] == 0 and gt_sigma[1] == 0:
617
+ gt_density = torch.zeros_like(proposal_density)
618
+ else:
619
+ std_gt = torch.Tensor([gt_sigma[0], gt_sigma[0], gt_sigma[1], gt_sigma[1]]).view(1, 4)
620
+ gt_density = gauss_density_centered(proposals_rel_centered, std_gt).prod(-1)
621
+
622
+ if add_mean_box:
623
+ proposals = torch.cat((mean_box, proposals))
624
+ proposal_density = torch.cat((torch.Tensor([-1]), proposal_density))
625
+ gt_density = torch.cat((torch.Tensor([1]), gt_density))
626
+
627
+ return proposals, proposal_density, gt_density
external/AR/ltr/data/processing_utils_SE.py ADDED
@@ -0,0 +1,450 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import math
3
+ import cv2 as cv
4
+ import random
5
+
6
+ import numpy as np
7
+
8
+ def stack_tensors(x):
9
+ if isinstance(x, list) and isinstance(x[0], torch.Tensor):
10
+ return torch.stack(x)
11
+ return x
12
+
13
+
14
+ '''Added on 2019.12.23'''
15
+ def sample_target_SE(im, target_bb, search_area_factor, output_sz=None, mode=cv.BORDER_REPLICATE):
16
+ """ Extracts a crop centered at target_bb box, of size search_area_factor times target_bb(Both height and width)
17
+
18
+ args:
19
+ im - cv image
20
+ target_bb - target box [x, y, w, h]
21
+ search_area_factor - Ratio of crop size to target size
22
+ output_sz - (float) Size to which the extracted crop is resized (always square). If None, no resizing is done.
23
+
24
+ returns:
25
+ cv image - extracted crop
26
+ float - the factor by which the crop has been resized to make the crop size equal output_size
27
+ """
28
+
29
+ x, y, w, h = target_bb.tolist()
30
+
31
+ # Crop image
32
+ ws = math.ceil(search_area_factor * w)
33
+ hs = math.ceil(search_area_factor * h)
34
+
35
+ if ws < 1 or hs < 1:
36
+ raise Exception('Too small bounding box.')
37
+
38
+ x1 = round(x + 0.5*w - ws*0.5)
39
+ x2 = x1 + ws
40
+
41
+ y1 = round(y + 0.5 * h - hs * 0.5)
42
+ y2 = y1 + hs
43
+
44
+ x1_pad = max(0, -x1)
45
+ x2_pad = max(x2-im.shape[1]+1, 0)
46
+
47
+ y1_pad = max(0, -y1)
48
+ y2_pad = max(y2-im.shape[0]+1, 0)
49
+
50
+ # Crop target
51
+ im_crop = im[y1+y1_pad:y2-y2_pad, x1+x1_pad:x2-x2_pad, :]
52
+
53
+ # Pad
54
+ im_crop_padded = cv.copyMakeBorder(im_crop, y1_pad, y2_pad, x1_pad, x2_pad, mode)
55
+
56
+ if output_sz is not None:
57
+ w_rsz_f = output_sz / ws
58
+ h_rsz_f = output_sz / hs
59
+ im_crop_padded_rsz = cv.resize(im_crop_padded, (output_sz, output_sz))
60
+ if len(im_crop_padded_rsz.shape)==2:
61
+ im_crop_padded_rsz = im_crop_padded_rsz[...,np.newaxis]
62
+ return im_crop_padded_rsz, h_rsz_f, w_rsz_f
63
+ else:
64
+ return im_crop_padded, 1.0, 1.0
65
+ '''把mask映射到原图上'''
66
+ def map_mask_back(im, target_bb, search_area_factor, mask, mode=cv.BORDER_REPLICATE):
67
+ """ Extracts a crop centered at target_bb box, of size search_area_factor times target_bb(Both height and width)
68
+
69
+ args:
70
+ im - cv image
71
+ target_bb - target box [x, y, w, h]
72
+ search_area_factor - Ratio of crop size to target size
73
+ output_sz - (float) Size to which the extracted crop is resized (always square). If None, no resizing is done.
74
+
75
+ returns:
76
+ cv image - extracted crop
77
+ float - the factor by which the crop has been resized to make the crop size equal output_size
78
+ """
79
+ H,W = (im.shape[0],im.shape[1])
80
+ base = np.zeros((H,W))
81
+ x, y, w, h = target_bb.tolist()
82
+
83
+ # Crop image
84
+ ws = math.ceil(search_area_factor * w)
85
+ hs = math.ceil(search_area_factor * h)
86
+
87
+ if ws < 1 or hs < 1:
88
+ raise Exception('Too small bounding box.')
89
+
90
+ x1 = round(x + 0.5*w - ws*0.5)
91
+ x2 = x1 + ws
92
+
93
+ y1 = round(y + 0.5 * h - hs * 0.5)
94
+ y2 = y1 + hs
95
+
96
+ x1_pad = max(0, -x1)
97
+ x2_pad = max(x2-im.shape[1]+1, 0)
98
+
99
+ y1_pad = max(0, -y1)
100
+ y2_pad = max(y2-im.shape[0]+1, 0)
101
+
102
+ '''pad base'''
103
+ base_padded = cv.copyMakeBorder(base, y1_pad, y2_pad, x1_pad, x2_pad, mode)
104
+ '''Resize mask'''
105
+ mask_rsz = cv.resize(mask,(ws,hs))
106
+ '''fill region with mask'''
107
+ base_padded[y1+y1_pad:y2+y1_pad, x1+x1_pad:x2+x1_pad] = mask_rsz.copy()
108
+ '''crop base_padded to get final mask'''
109
+ final_mask = base_padded[y1_pad:y1_pad+H,x1_pad:x1_pad+W]
110
+ assert (final_mask.shape == (H,W))
111
+ return final_mask
112
+
113
+ '''Added on 2019.12.23'''
114
+ def transform_image_to_crop_SE(box_in: torch.Tensor, box_extract: torch.Tensor, resize_factor_h: float, resize_factor_w: float,
115
+ crop_sz: torch.Tensor) -> torch.Tensor:
116
+ """ Transform the box co-ordinates from the original image co-ordinates to the co-ordinates of the cropped image
117
+ args:
118
+ box_in - the box for which the co-ordinates are to be transformed
119
+ box_extract - the box about which the image crop has been extracted.
120
+ resize_factor - the ratio between the original image scale and the scale of the image crop
121
+ crop_sz - size of the cropped image
122
+
123
+ returns:
124
+ torch.Tensor - transformed co-ordinates of box_in
125
+ """
126
+ box_extract_center = box_extract[0:2] + 0.5*box_extract[2:4]
127
+
128
+ box_in_center = box_in[0:2] + 0.5*box_in[2:4]
129
+
130
+ box_out_xc = (crop_sz[0] -1)/2 + (box_in_center[0] - box_extract_center[0])*resize_factor_w
131
+ box_out_yc = (crop_sz[0] -1)/2 + (box_in_center[1] - box_extract_center[1])*resize_factor_h
132
+ box_out_w = box_in[2] * resize_factor_w
133
+ box_out_h = box_in[3] * resize_factor_h
134
+
135
+ '''2019.12.28 为了避免出现(x1,y1)小于0,或者(x2,y2)大于256的情况,这里我对它们加上了一些限制'''
136
+ max_sz = crop_sz[0].item()
137
+ box_out_x1 = torch.clamp(box_out_xc - 0.5 * box_out_w,0,max_sz)
138
+ box_out_y1 = torch.clamp(box_out_yc - 0.5 * box_out_h,0,max_sz)
139
+ box_out_x2 = torch.clamp(box_out_xc + 0.5 * box_out_w,0,max_sz)
140
+ box_out_y2 = torch.clamp(box_out_yc + 0.5 * box_out_h,0,max_sz)
141
+ box_out_w_new = box_out_x2 - box_out_x1
142
+ box_out_h_new = box_out_y2 - box_out_y1
143
+ box_out = torch.stack((box_out_x1, box_out_y1, box_out_w_new, box_out_h_new))
144
+ return box_out
145
+
146
+ def centered_crop(frames, anno, area_factor, output_sz):
147
+ crops_resize_factors = [sample_target(f, a, area_factor, output_sz)
148
+ for f, a in zip(frames, anno)]
149
+
150
+ frames_crop, resize_factors = zip(*crops_resize_factors)
151
+
152
+ crop_sz = torch.Tensor([output_sz, output_sz])
153
+
154
+ # find the bb location in the crop
155
+ anno_crop = [transform_image_to_crop(a, a, rf, crop_sz)
156
+ for a, rf in zip(anno, resize_factors)]
157
+
158
+ return frames_crop, anno_crop
159
+
160
+ '''Added by Bin Yan 2019.12.23,
161
+ changed on 2020.1.4(add a new args: "get_bbox_coord")'''
162
+ def jittered_center_crop_SE(frames, box_extract, box_gt, search_area_factor, output_sz, get_bbox_coord=True, mode=cv.BORDER_REPLICATE):
163
+ """
164
+ Crop a patch centered at box_extract. The height and width of cropped region is search_area_factor times that of box_extract.
165
+ The extracted crops are then resized to output_sz. Further, the co-ordinates of the box box_gt are transformed to the image crop co-ordinates
166
+ args:
167
+ frames - list of frames
168
+ box_extract - list of boxes of same length as frames. The crops are extracted using anno_extract
169
+ box_gt - list of boxes of same length as frames. The co-ordinates of these boxes are transformed from
170
+ image co-ordinates to the crop co-ordinates
171
+ search_area_factor - The area of the extracted crop is search_area_factor^2 times box_extract area
172
+ output_sz - The size to which the extracted crops are resized
173
+
174
+ returns:
175
+ list - list of image crops
176
+ list - box_gt location in the crop co-ordinates
177
+ """
178
+ '''call function "sample_target_SE" and function "transform_image_to_crop_SE"'''
179
+ '''get cropped patch(fixed size)'''
180
+ crops_resize_factors = [sample_target_SE(f, a, search_area_factor, output_sz, mode=mode)
181
+ for f, a in zip(frames, box_extract)]
182
+
183
+ frames_crop, resize_factors_h, resize_factors_w = zip(*crops_resize_factors)
184
+ if get_bbox_coord:
185
+ crop_sz = torch.Tensor([output_sz, output_sz])
186
+
187
+ # find the bb location in the crop
188
+ '''get GT's cooridinate on the cropped patch'''
189
+ box_crop = [transform_image_to_crop_SE(a_gt, a_ex, h_rsf, w_rsf, crop_sz)
190
+ for a_gt, a_ex, h_rsf, w_rsf in zip(box_gt, box_extract, resize_factors_h, resize_factors_w)]
191
+
192
+ return frames_crop, box_crop
193
+ else:
194
+ return frames_crop
195
+
196
+ def sample_target_nopad(im, target_bb, search_area_factor, output_sz):
197
+ """ Extracts a crop centered at target_bb box, of area search_area_factor^2. If the crop area contains regions
198
+ outside the image, it is shifted so that the it is inside the image. Further, if the crop area exceeds the image
199
+ size, a smaller crop which fits the image is returned instead.
200
+
201
+ args:
202
+ im - cv image
203
+ target_bb - target box [x, y, w, h]
204
+ search_area_factor - Ratio of crop size to target size
205
+ output_sz - (float) Size to which the extracted crop is resized (always square). If None, no resizing is done.
206
+
207
+ returns:
208
+ cv image - extracted crop
209
+ torch.Tensor - a bounding box denoting the cropped region in the image.
210
+ """
211
+
212
+ if isinstance(output_sz, (float, int)):
213
+ output_sz = (output_sz, output_sz)
214
+ output_sz = torch.Tensor(output_sz)
215
+
216
+ im_h = im.shape[0]
217
+ im_w = im.shape[1]
218
+
219
+ bbx, bby, bbw, bbh = target_bb.tolist()
220
+
221
+ # Crop image
222
+ crop_sz_x, crop_sz_y = (output_sz * (target_bb[2:].prod()/output_sz.prod()).sqrt() * search_area_factor).ceil()
223
+
224
+ # Calculate rescaling factor if outside the image
225
+ rescale_factor = max(1, crop_sz_x/im_w, crop_sz_y/im_h)
226
+ crop_sz_x = math.floor(crop_sz_x / rescale_factor)
227
+ crop_sz_y = math.floor(crop_sz_y / rescale_factor)
228
+
229
+ if crop_sz_x < 1 or crop_sz_y < 1:
230
+ raise Exception('Too small bounding box.')
231
+
232
+ x1 = round(bbx + 0.5*bbw - crop_sz_x*0.5)
233
+ x2 = x1 + crop_sz_x
234
+
235
+ y1 = round(bby + 0.5*bbh - crop_sz_y*0.5)
236
+ y2 = y1 + crop_sz_y
237
+
238
+ # Move box inside image
239
+ shift_x = max(0, -x1) + min(0, im_w - x2)
240
+ x1 += shift_x
241
+ x2 += shift_x
242
+
243
+ shift_y = max(0, -y1) + min(0, im_h - y2)
244
+ y1 += shift_y
245
+ y2 += shift_y
246
+
247
+ # Crop and resize image
248
+ im_crop = im[y1:y2, x1:x2, :]
249
+ im_out = cv.resize(im_crop, tuple(output_sz.long().tolist()))
250
+
251
+ crop_box = torch.Tensor([x1, y1, x2-x1, y2-y1])
252
+ return im_out, crop_box
253
+
254
+
255
+ def transform_box_to_crop(box: torch.Tensor, crop_box: torch.Tensor, crop_sz: torch.Tensor) -> torch.Tensor:
256
+ """ Transform the box co-ordinates from the original image co-ordinates to the co-ordinates of the cropped image
257
+ args:
258
+ box - the box for which the co-ordinates are to be transformed
259
+ crop_box - bounding box defining the crop in the original image
260
+ crop_sz - size of the cropped image
261
+
262
+ returns:
263
+ torch.Tensor - transformed co-ordinates of box_in
264
+ """
265
+
266
+ box_out = box.clone()
267
+ box_out[:2] -= crop_box[:2]
268
+
269
+ scale_factor = crop_sz / crop_box[2:]
270
+
271
+ box_out[:2] *= scale_factor
272
+ box_out[2:] *= scale_factor
273
+ return box_out
274
+
275
+
276
+ def jittered_center_crop_nopad(frames, box_extract, box_gt, search_area_factor, output_sz):
277
+ """ For each frame in frames, extracts a square crop centered at box_extract, of area search_area_factor^2
278
+ times box_extract area. If the crop area contains regions outside the image, it is shifted / shrunk so that it
279
+ completely fits inside the image. The extracted crops are then resized to output_sz. Further, the co-ordinates of
280
+ the box box_gt are transformed to the image crop co-ordinates
281
+
282
+ args:
283
+ frames - list of frames
284
+ box_extract - list of boxes of same length as frames. The crops are extracted using anno_extract
285
+ box_gt - list of boxes of same length as frames. The co-ordinates of these boxes are transformed from
286
+ image co-ordinates to the crop co-ordinates
287
+ search_area_factor - The area of the extracted crop is search_area_factor^2 times box_extract area
288
+ output_sz - The size to which the extracted crops are resized
289
+
290
+ returns:
291
+ list - list of image crops
292
+ list - box_gt location in the crop co-ordinates
293
+ """
294
+
295
+ if isinstance(output_sz, (float, int)):
296
+ output_sz = (output_sz, output_sz)
297
+
298
+ frame_crops_boxes = [sample_target_nopad(f, a, search_area_factor, output_sz)
299
+ for f, a in zip(frames, box_extract)]
300
+
301
+ frames_crop, crop_boxes = zip(*frame_crops_boxes)
302
+
303
+ crop_sz = torch.Tensor(output_sz)
304
+
305
+ # find the bb location in the crop
306
+ box_crop = [transform_box_to_crop(bb_gt, crop_bb, crop_sz)
307
+ for bb_gt, crop_bb in zip(box_gt, crop_boxes)]
308
+
309
+ return frames_crop, box_crop
310
+
311
+
312
+ def iou(reference, proposals):
313
+ """Compute the IoU between a reference box with multiple proposal boxes.
314
+
315
+ args:
316
+ reference - Tensor of shape (1, 4).
317
+ proposals - Tensor of shape (num_proposals, 4)
318
+
319
+ returns:
320
+ torch.Tensor - Tensor of shape (num_proposals,) containing IoU of reference box with each proposal box.
321
+ """
322
+
323
+ # Intersection box
324
+ tl = torch.max(reference[:,:2], proposals[:,:2])
325
+ br = torch.min(reference[:,:2] + reference[:,2:], proposals[:,:2] + proposals[:,2:])
326
+ sz = (br - tl).clamp(0)
327
+
328
+ # Area
329
+ intersection = sz.prod(dim=1)
330
+ union = reference[:,2:].prod(dim=1) + proposals[:,2:].prod(dim=1) - intersection
331
+
332
+ return intersection / union
333
+
334
+
335
+ def rand_uniform(a, b, shape=1):
336
+ """ sample numbers uniformly between a and b.
337
+ args:
338
+ a - lower bound
339
+ b - upper bound
340
+ shape - shape of the output tensor
341
+
342
+ returns:
343
+ torch.Tensor - tensor of shape=shape
344
+ """
345
+ return (b - a) * torch.rand(shape) + a
346
+
347
+
348
+ def perturb_box(box, min_iou=0.5, sigma_factor=0.1):
349
+ """ Perturb the input box by adding gaussian noise to the co-ordinates
350
+
351
+ args:
352
+ box - input box
353
+ min_iou - minimum IoU overlap between input box and the perturbed box
354
+ sigma_factor - amount of perturbation, relative to the box size. Can be either a single element, or a list of
355
+ sigma_factors, in which case one of them will be uniformly sampled. Further, each of the
356
+ sigma_factor element can be either a float, or a tensor
357
+ of shape (4,) specifying the sigma_factor per co-ordinate
358
+
359
+ returns:
360
+ torch.Tensor - the perturbed box
361
+ """
362
+
363
+ if isinstance(sigma_factor, list):
364
+ # If list, sample one sigma_factor as current sigma factor
365
+ c_sigma_factor = random.choice(sigma_factor)
366
+ else:
367
+ c_sigma_factor = sigma_factor
368
+
369
+ if not isinstance(c_sigma_factor, torch.Tensor):
370
+ c_sigma_factor = c_sigma_factor * torch.ones(4)
371
+
372
+ perturb_factor = torch.sqrt(box[2]*box[3])*c_sigma_factor
373
+
374
+ # multiple tries to ensure that the perturbed box has iou > min_iou with the input box
375
+ for i_ in range(100):
376
+ c_x = box[0] + 0.5*box[2]
377
+ c_y = box[1] + 0.5 * box[3]
378
+ c_x_per = random.gauss(c_x, perturb_factor[0])
379
+ c_y_per = random.gauss(c_y, perturb_factor[1])
380
+
381
+ w_per = random.gauss(box[2], perturb_factor[2])
382
+ h_per = random.gauss(box[3], perturb_factor[3])
383
+
384
+ if w_per <= 1:
385
+ w_per = box[2]*rand_uniform(0.15, 0.5)
386
+
387
+ if h_per <= 1:
388
+ h_per = box[3]*rand_uniform(0.15, 0.5)
389
+
390
+ box_per = torch.Tensor([c_x_per - 0.5*w_per, c_y_per - 0.5*h_per, w_per, h_per]).round()
391
+
392
+ if box_per[2] <= 1:
393
+ box_per[2] = box[2]*rand_uniform(0.15, 0.5)
394
+
395
+ if box_per[3] <= 1:
396
+ box_per[3] = box[3]*rand_uniform(0.15, 0.5)
397
+
398
+ box_iou = iou(box.view(1, 4), box_per.view(1, 4))
399
+
400
+ # if there is sufficient overlap, return
401
+ if box_iou > min_iou:
402
+ return box_per, box_iou
403
+
404
+ # else reduce the perturb factor
405
+ perturb_factor *= 0.9
406
+
407
+ return box_per, box_iou
408
+
409
+
410
+ def gauss_1d(sz, sigma, center, end_pad=0):
411
+ k = torch.arange(-(sz-1)/2, (sz+1)/2 + end_pad).reshape(1, -1)
412
+ return torch.exp(-1.0/(2*sigma**2) * (k - center.reshape(-1, 1))**2)
413
+
414
+
415
+ def gauss_2d(sz, sigma, center, end_pad=(0, 0)):
416
+ if isinstance(sigma, (float, int)):
417
+ sigma = (sigma, sigma)
418
+ return gauss_1d(sz[0].item(), sigma[0], center[:, 0], end_pad[0]).reshape(center.shape[0], 1, -1) * \
419
+ gauss_1d(sz[1].item(), sigma[1], center[:, 1], end_pad[1]).reshape(center.shape[0], -1, 1)
420
+
421
+
422
+ def gaussian_label_function(target_bb, sigma_factor, kernel_sz, feat_sz, image_sz, end_pad_if_even=True):
423
+ """Construct Gaussian label function."""
424
+
425
+ if isinstance(kernel_sz, (float, int)):
426
+ kernel_sz = (kernel_sz, kernel_sz)
427
+ if isinstance(feat_sz, (float, int)):
428
+ feat_sz = (feat_sz, feat_sz)
429
+ if isinstance(image_sz, (float, int)):
430
+ image_sz = (image_sz, image_sz)
431
+
432
+ image_sz = torch.Tensor(image_sz)
433
+ feat_sz = torch.Tensor(feat_sz)
434
+
435
+ target_center = target_bb[:, 0:2] + 0.5 * target_bb[:, 2:4]
436
+ target_center_norm = (target_center - image_sz / 2) / image_sz
437
+
438
+ center = feat_sz * target_center_norm + 0.5 * \
439
+ torch.Tensor([(kernel_sz[0] + 1) % 2, (kernel_sz[1] + 1) % 2])
440
+
441
+ sigma = sigma_factor * feat_sz.prod().sqrt().item()
442
+
443
+ if end_pad_if_even:
444
+ end_pad = (int(kernel_sz[0]%2 == 0), int(kernel_sz[1]%2 == 0))
445
+ else:
446
+ end_pad = (0, 0)
447
+
448
+ gauss_label = gauss_2d(feat_sz, sigma, center, end_pad)
449
+ return gauss_label
450
+
external/AR/ltr/data/sampler.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ import torch.utils.data
3
+ from pytracking import TensorDict
4
+
5
+
6
+ def no_processing(data):
7
+ return data
8
+
9
+
10
+ class TrackingSampler(torch.utils.data.Dataset):
11
+ """ Class responsible for sampling frames from training sequences to form batches. Each training sample is a
12
+ tuple consisting of i) a set of train frames, used to learn the DiMP classification model and obtain the
13
+ modulation vector for IoU-Net, and ii) a set of test frames on which target classification loss for the predicted
14
+ DiMP model, and the IoU prediction loss for the IoU-Net is calculated.
15
+
16
+ The sampling is done in the following ways. First a dataset is selected at random. Next, a sequence is selected
17
+ from that dataset. A base frame is then sampled randomly from the sequence. Next, a set of 'train frames' and
18
+ 'test frames' are sampled from the sequence from the range [base_frame_id - max_gap, base_frame_id] and
19
+ (base_frame_id, base_frame_id + max_gap] respectively. Only the frames in which the target is visible are sampled.
20
+ If enough visible frames are not found, the 'max_gap' is increased gradually till enough frames are found.
21
+
22
+ The sampled frames are then passed through the input 'processing' function for the necessary processing-
23
+ """
24
+
25
+ def __init__(self, datasets, p_datasets, samples_per_epoch, max_gap,
26
+ num_test_frames, num_train_frames=1, processing=no_processing, frame_sample_mode='causal'):
27
+ """
28
+ args:
29
+ datasets - List of datasets to be used for training
30
+ p_datasets - List containing the probabilities by which each dataset will be sampled
31
+ samples_per_epoch - Number of training samples per epoch
32
+ max_gap - Maximum gap, in frame numbers, between the train frames and the test frames.
33
+ num_test_frames - Number of test frames to sample.
34
+ num_train_frames - Number of train frames to sample.
35
+ processing - An instance of Processing class which performs the necessary processing of the data.
36
+ frame_sample_mode - Either 'causal' or 'interval'. If 'causal', then the test frames are sampled in a causally,
37
+ otherwise randomly within the interval.
38
+ """
39
+ self.datasets = datasets
40
+
41
+ # If p not provided, sample uniformly from all videos
42
+ if p_datasets is None:
43
+ p_datasets = [len(d) for d in self.datasets]
44
+
45
+ # Normalize
46
+ p_total = sum(p_datasets)
47
+ self.p_datasets = [x / p_total for x in p_datasets]
48
+
49
+ self.samples_per_epoch = samples_per_epoch
50
+ self.max_gap = max_gap
51
+ self.num_test_frames = num_test_frames
52
+ self.num_train_frames = num_train_frames
53
+ self.processing = processing
54
+ self.frame_sample_mode = frame_sample_mode
55
+
56
+ def __len__(self):
57
+ return self.samples_per_epoch
58
+
59
+ def _sample_visible_ids(self, visible, num_ids=1, min_id=None, max_id=None):
60
+ """ Samples num_ids frames between min_id and max_id for which target is visible
61
+
62
+ args:
63
+ visible - 1d Tensor indicating whether target is visible for each frame
64
+ num_ids - number of frames to be samples
65
+ min_id - Minimum allowed frame number
66
+ max_id - Maximum allowed frame number
67
+
68
+ returns:
69
+ list - List of sampled frame numbers. None if not sufficient visible frames could be found.
70
+ """
71
+ if num_ids == 0:
72
+ return []
73
+ if min_id is None or min_id < 0:
74
+ min_id = 0
75
+ if max_id is None or max_id > len(visible):
76
+ max_id = len(visible)
77
+
78
+ valid_ids = [i for i in range(min_id, max_id) if visible[i]]
79
+
80
+ # No visible ids
81
+ if len(valid_ids) == 0:
82
+ return None
83
+
84
+ return random.choices(valid_ids, k=num_ids)
85
+
86
+ def __getitem__(self, index):
87
+ """
88
+ args:
89
+ index (int): Index (Ignored since we sample randomly)
90
+
91
+ returns:
92
+ TensorDict - dict containing all the data blocks
93
+ """
94
+
95
+ # Select a dataset
96
+ dataset = random.choices(self.datasets, self.p_datasets)[0]
97
+ is_video_dataset = dataset.is_video_sequence()
98
+
99
+ # Sample a sequence with enough visible frames
100
+ enough_visible_frames = False
101
+ while not enough_visible_frames:
102
+ # Sample a sequence
103
+ seq_id = random.randint(0, dataset.get_num_sequences() - 1)
104
+
105
+ # Sample frames
106
+ seq_info_dict = dataset.get_sequence_info(seq_id)
107
+ visible = seq_info_dict['visible']
108
+
109
+ enough_visible_frames = visible.type(torch.int64).sum().item() > 2 * (
110
+ self.num_test_frames + self.num_train_frames) and len(visible) >= 20
111
+
112
+ enough_visible_frames = enough_visible_frames or not is_video_dataset
113
+
114
+ if is_video_dataset:
115
+ train_frame_ids = None
116
+ test_frame_ids = None
117
+ gap_increase = 0
118
+
119
+ if self.frame_sample_mode == 'interval':
120
+ # Sample frame numbers within interval defined by the first frame
121
+ while test_frame_ids is None:
122
+ base_frame_id = self._sample_visible_ids(visible, num_ids=1)
123
+ extra_train_frame_ids = self._sample_visible_ids(visible, num_ids=self.num_train_frames - 1,
124
+ min_id=base_frame_id[
125
+ 0] - self.max_gap - gap_increase,
126
+ max_id=base_frame_id[
127
+ 0] + self.max_gap + gap_increase)
128
+ if extra_train_frame_ids is None:
129
+ gap_increase += 5
130
+ continue
131
+ train_frame_ids = base_frame_id + extra_train_frame_ids
132
+ test_frame_ids = self._sample_visible_ids(visible, num_ids=self.num_test_frames,
133
+ min_id=train_frame_ids[0] - self.max_gap - gap_increase,
134
+ max_id=train_frame_ids[0] + self.max_gap + gap_increase)
135
+ gap_increase += 5 # Increase gap until a frame is found
136
+
137
+ elif self.frame_sample_mode == 'causal':
138
+ # Sample test and train frames in a causal manner, i.e. test_frame_ids > train_frame_ids
139
+ while test_frame_ids is None:
140
+ base_frame_id = self._sample_visible_ids(visible, num_ids=1, min_id=self.num_train_frames - 1,
141
+ max_id=len(visible) - self.num_test_frames)
142
+ prev_frame_ids = self._sample_visible_ids(visible, num_ids=self.num_train_frames - 1,
143
+ min_id=base_frame_id[0] - self.max_gap - gap_increase,
144
+ max_id=base_frame_id[0])
145
+ if prev_frame_ids is None:
146
+ gap_increase += 5
147
+ continue
148
+ train_frame_ids = base_frame_id + prev_frame_ids
149
+ test_frame_ids = self._sample_visible_ids(visible, min_id=train_frame_ids[0] + 1,
150
+ max_id=train_frame_ids[0] + self.max_gap + gap_increase,
151
+ num_ids=self.num_test_frames)
152
+ # Increase gap until a frame is found
153
+ gap_increase += 5
154
+ else:
155
+ # In case of image dataset, just repeat the image to generate synthetic video
156
+ train_frame_ids = [1] * self.num_train_frames
157
+ test_frame_ids = [1] * self.num_test_frames
158
+
159
+ train_frames, train_anno, meta_obj_train = dataset.get_frames(seq_id, train_frame_ids, seq_info_dict)
160
+ test_frames, test_anno, meta_obj_test = dataset.get_frames(seq_id, test_frame_ids, seq_info_dict)
161
+
162
+ data = TensorDict({'train_images': train_frames,
163
+ 'train_anno': train_anno['bbox'],
164
+ 'test_images': test_frames,
165
+ 'test_anno': test_anno['bbox'],
166
+ 'dataset': dataset.get_name(),
167
+ 'test_class': meta_obj_test.get('object_class_name')})
168
+
169
+ return self.processing(data)
170
+
171
+
172
+ class DiMPSampler(TrackingSampler):
173
+ """ See TrackingSampler."""
174
+
175
+ def __init__(self, datasets, p_datasets, samples_per_epoch, max_gap,
176
+ num_test_frames, num_train_frames=1, processing=no_processing, frame_sample_mode='causal'):
177
+ super().__init__(datasets=datasets, p_datasets=p_datasets, samples_per_epoch=samples_per_epoch, max_gap=max_gap,
178
+ num_test_frames=num_test_frames, num_train_frames=num_train_frames, processing=processing,
179
+ frame_sample_mode=frame_sample_mode)
180
+
181
+
182
+ class ATOMSampler(TrackingSampler):
183
+ """ See TrackingSampler."""
184
+
185
+ def __init__(self, datasets, p_datasets, samples_per_epoch, max_gap,
186
+ num_test_frames=1, num_train_frames=1, processing=no_processing, frame_sample_mode='interval'):
187
+ super().__init__(datasets=datasets, p_datasets=p_datasets, samples_per_epoch=samples_per_epoch, max_gap=max_gap,
188
+ num_test_frames=num_test_frames, num_train_frames=num_train_frames, processing=processing,
189
+ frame_sample_mode=frame_sample_mode)
external/AR/ltr/data/transforms.py ADDED
@@ -0,0 +1,440 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ import numpy as np
3
+ import math
4
+ import cv2 as cv
5
+ import torch
6
+ import torch.nn.functional as F
7
+ import torchvision.transforms.functional as tvisf
8
+
9
+
10
+ class Transform:
11
+ """A set of transformations, used for e.g. data augmentation.
12
+ Args of constructor:
13
+ transforms: An arbitrary number of transformations, derived from the TransformBase class.
14
+ They are applied in the order they are given.
15
+
16
+ The Transform object can jointly transform images, bounding boxes and segmentation masks.
17
+ This is done by calling the object with the following key-word arguments (all are optional).
18
+
19
+ The following arguments are inputs to be transformed. They are either supplied as a single instance, or a list of instances.
20
+ image - Image
21
+ coords - 2xN dimensional Tensor of 2D image coordinates [y, x]
22
+ bbox - Bounding box on the form [x, y, w, h]
23
+ mask - Segmentation mask with discrete classes
24
+
25
+ The following parameters can be supplied with calling the transform object:
26
+ joint [Bool] - If True then transform all images/coords/bbox/mask in the list jointly using the same transformation.
27
+ Otherwise each tuple (images, coords, bbox, mask) will be transformed independently using
28
+ different random rolls. Default: True.
29
+ new_roll [Bool] - If False, then no new random roll is performed, and the saved result from the previous roll
30
+ is used instead. Default: True.
31
+
32
+ Check the DiMPProcessing class for examples.
33
+ """
34
+
35
+ def __init__(self, *transforms):
36
+ if len(transforms) == 1 and isinstance(transforms[0], (list, tuple)):
37
+ transforms = transforms[0]
38
+ self.transforms = transforms
39
+ self._valid_inputs = ['image', 'coords', 'bbox', 'mask']
40
+ self._valid_args = ['joint', 'new_roll']
41
+ self._valid_all = self._valid_inputs + self._valid_args
42
+
43
+ def __call__(self, **inputs):
44
+ var_names = [k for k in inputs.keys() if k in self._valid_inputs]
45
+ for v in inputs.keys():
46
+ if v not in self._valid_all:
47
+ raise ValueError('Incorrect input \"{}\" to transform. Only supports inputs {} and arguments {}.'.format(v, self._valid_inputs, self._valid_args))
48
+
49
+ joint_mode = inputs.get('joint', True)
50
+ new_roll = inputs.get('new_roll', True)
51
+
52
+ if not joint_mode:
53
+ out = zip(*[self(**inp) for inp in self._split_inputs(inputs)])
54
+ return tuple(list(o) for o in out)
55
+
56
+ out = {k: v for k, v in inputs.items() if k in self._valid_inputs}
57
+
58
+ for t in self.transforms:
59
+ out = t(**out, joint=joint_mode, new_roll=new_roll)
60
+ if len(var_names) == 1:
61
+ return out[var_names[0]]
62
+ # Make sure order is correct
63
+ return tuple(out[v] for v in var_names)
64
+
65
+ def _split_inputs(self, inputs):
66
+ var_names = [k for k in inputs.keys() if k in self._valid_inputs]
67
+ split_inputs = [{k: v for k, v in zip(var_names, vals)} for vals in zip(*[inputs[vn] for vn in var_names])]
68
+ for arg_name, arg_val in filter(lambda it: it[0]!='joint' and it[0] in self._valid_args, inputs.items()):
69
+ if isinstance(arg_val, list):
70
+ for inp, av in zip(split_inputs, arg_val):
71
+ inp[arg_name] = av
72
+ else:
73
+ for inp in split_inputs:
74
+ inp[arg_name] = arg_val
75
+ return split_inputs
76
+
77
+ def __repr__(self):
78
+ format_string = self.__class__.__name__ + '('
79
+ for t in self.transforms:
80
+ format_string += '\n'
81
+ format_string += ' {0}'.format(t)
82
+ format_string += '\n)'
83
+ return format_string
84
+
85
+
86
+ class TransformBase:
87
+ """Base class for transformation objects. See the Transform class for details."""
88
+ def __init__(self):
89
+ self._valid_inputs = ['image', 'coords', 'bbox', 'mask']
90
+ self._valid_args = ['new_roll']
91
+ self._valid_all = self._valid_inputs + self._valid_args
92
+ self._rand_params = None
93
+
94
+ def __call__(self, **inputs):
95
+ # Split input
96
+ input_vars = {k: v for k, v in inputs.items() if k in self._valid_inputs}
97
+ input_args = {k: v for k, v in inputs.items() if k in self._valid_args}
98
+
99
+ # Roll random parameters for the transform
100
+ if input_args.get('new_roll', True):
101
+ rand_params = self.roll()
102
+ if rand_params is None:
103
+ rand_params = ()
104
+ elif not isinstance(rand_params, tuple):
105
+ rand_params = (rand_params,)
106
+ self._rand_params = rand_params
107
+
108
+ outputs = dict()
109
+ for var_name, var in input_vars.items():
110
+ if var is not None:
111
+ transform_func = getattr(self, 'transform_' + var_name)
112
+ if var_name in ['coords', 'bbox']:
113
+ params = (self._get_image_size(input_vars),) + self._rand_params
114
+ else:
115
+ params = self._rand_params
116
+ if isinstance(var, (list, tuple)):
117
+ outputs[var_name] = [transform_func(x, *params) for x in var]
118
+ else:
119
+ outputs[var_name] = transform_func(var, *params)
120
+ return outputs
121
+
122
+ def _get_image_size(self, inputs):
123
+ im = None
124
+ for var_name in ['image', 'mask']:
125
+ if inputs.get(var_name) is not None:
126
+ im = inputs[var_name]
127
+ break
128
+ if im is None:
129
+ return None
130
+ if isinstance(im, (list, tuple)):
131
+ im = im[0]
132
+ if isinstance(im, np.ndarray):
133
+ return im.shape[:2]
134
+ if torch.is_tensor(im):
135
+ return (im.shape[-2], im.shape[-1])
136
+ raise Exception('Unknown image type')
137
+
138
+ def roll(self):
139
+ return None
140
+
141
+ def transform_image(self, image, *rand_params):
142
+ """Must be deterministic"""
143
+ return image
144
+
145
+ def transform_coords(self, coords, image_shape, *rand_params):
146
+ """Must be deterministic"""
147
+ return coords
148
+
149
+ def transform_bbox(self, bbox, image_shape, *rand_params):
150
+ """Assumes [x, y, w, h]"""
151
+ # Check if not overloaded
152
+ if self.transform_coords.__code__ == TransformBase.transform_coords.__code__:
153
+ return bbox
154
+
155
+ coord = bbox.clone().view(-1,2).t().flip(0)
156
+
157
+ x1 = coord[1, 0]
158
+ x2 = coord[1, 0] + coord[1, 1]
159
+
160
+ y1 = coord[0, 0]
161
+ y2 = coord[0, 0] + coord[0, 1]
162
+
163
+ coord_all = torch.tensor([[y1, y1, y2, y2], [x1, x2, x2, x1]])
164
+
165
+ coord_transf = self.transform_coords(coord_all, image_shape, *rand_params).flip(0)
166
+ tl = torch.min(coord_transf, dim=1)[0]
167
+ sz = torch.max(coord_transf, dim=1)[0] - tl
168
+ bbox_out = torch.cat((tl, sz), dim=-1).reshape(bbox.shape)
169
+ return bbox_out
170
+
171
+ def transform_mask(self, mask, *rand_params):
172
+ """Must be deterministic"""
173
+ return mask
174
+
175
+
176
+ class ToTensor(TransformBase):
177
+ """Convert to a Tensor"""
178
+
179
+ def transform_image(self, image):
180
+ # handle numpy array
181
+ if image.ndim == 2:
182
+ image = image[:, :, None]
183
+
184
+ image = torch.from_numpy(image.transpose((2, 0, 1)))
185
+ # backward compatibility
186
+ if isinstance(image, torch.ByteTensor):
187
+ return image.float().div(255)
188
+ else:
189
+ return image
190
+
191
+ def transfrom_mask(self, mask):
192
+ if isinstance(mask, np.ndarray):
193
+ return torch.from_numpy(mask)
194
+
195
+
196
+
197
+ class ToTensorAndJitter(TransformBase):
198
+ """Convert to a Tensor and jitter brightness"""
199
+ def __init__(self, brightness_jitter=0.0, normalize=True):
200
+ super().__init__()
201
+ self.brightness_jitter = brightness_jitter
202
+ self.normalize = normalize
203
+
204
+ def roll(self):
205
+ return np.random.uniform(max(0, 1 - self.brightness_jitter), 1 + self.brightness_jitter)
206
+
207
+ def transform_image(self, image, brightness_factor):
208
+ # handle numpy array
209
+ image = torch.from_numpy(image.transpose((2, 0, 1)))
210
+
211
+ # backward compatibility
212
+ if self.normalize:
213
+ return image.float().mul(brightness_factor/255.0).clamp(0.0, 1.0)
214
+ else:
215
+ return image.float().mul(brightness_factor).clamp(0.0, 255.0)
216
+
217
+ def transform_mask(self, mask, brightness_factor):
218
+ if isinstance(mask, np.ndarray):
219
+ return torch.from_numpy(mask)
220
+ else:
221
+ return mask
222
+
223
+
224
+ class Normalize(TransformBase):
225
+ """Normalize image"""
226
+ def __init__(self, mean, std, inplace=False):
227
+ super().__init__()
228
+ self.mean = mean
229
+ self.std = std
230
+ self.inplace = inplace
231
+
232
+ def transform_image(self, image):
233
+ return tvisf.normalize(image, self.mean, self.std, self.inplace)
234
+
235
+
236
+ class ToGrayscale(TransformBase):
237
+ """Converts image to grayscale with probability"""
238
+ def __init__(self, probability = 0.5):
239
+ super().__init__()
240
+ self.probability = probability
241
+ self.color_weights = np.array([0.2989, 0.5870, 0.1140], dtype=np.float32)
242
+
243
+ def roll(self):
244
+ return random.random() < self.probability
245
+
246
+ def transform_image(self, image, do_grayscale):
247
+ if do_grayscale:
248
+ if torch.is_tensor(image):
249
+ raise NotImplementedError('Implement torch variant.')
250
+ img_gray = cv.cvtColor(image, cv.COLOR_RGB2GRAY)
251
+ return np.stack([img_gray, img_gray, img_gray], axis=2)
252
+ # return np.repeat(np.sum(img * self.color_weights, axis=2, keepdims=True).astype(np.uint8), 3, axis=2)
253
+ return image
254
+
255
+
256
+ class ToBGR(TransformBase):
257
+ """Converts image to BGR"""
258
+ def transform_image(self, image):
259
+ if torch.is_tensor(image):
260
+ raise NotImplementedError('Implement torch variant.')
261
+ img_bgr = cv.cvtColor(image, cv.COLOR_RGB2BGR)
262
+ return img_bgr
263
+
264
+
265
+ class RandomHorizontalFlip(TransformBase):
266
+ """Horizontally flip image randomly with a probability p."""
267
+ def __init__(self, probability = 0.5):
268
+ super().__init__()
269
+ self.probability = probability
270
+
271
+ def roll(self):
272
+ return random.random() < self.probability
273
+
274
+ def transform_image(self, image, do_flip):
275
+ if do_flip:
276
+ if torch.is_tensor(image):
277
+ return image.flip((2,))
278
+ return np.fliplr(image).copy()
279
+ return image
280
+
281
+ def transform_coords(self, coords, image_shape, do_flip):
282
+ if do_flip:
283
+ coords = coords.clone()
284
+ coords[1,:] = (image_shape[1] - 1) - coords[1,:]
285
+ return coords
286
+
287
+ def transform_mask(self, mask, do_flip):
288
+ if do_flip:
289
+ if torch.is_tensor(mask):
290
+ return mask.flip((-1,))
291
+ return np.fliplr(mask).copy()
292
+ return mask
293
+
294
+
295
+ class Blur(TransformBase):
296
+ """ Blur the image by applying a gaussian kernel with given sigma"""
297
+ def __init__(self, sigma):
298
+ super().__init__()
299
+ if isinstance(sigma, (float, int)):
300
+ sigma = (sigma, sigma)
301
+ self.sigma = sigma
302
+ self.filter_size = [math.ceil(2*s) for s in self.sigma]
303
+ x_coord = [torch.arange(-sz, sz+1, dtype=torch.float32) for sz in self.filter_size]
304
+ self.filter = [torch.exp(-(x**2)/(2*s**2)) for x, s in zip(x_coord, self.sigma)]
305
+ self.filter[0] = self.filter[0].view(1,1,-1,1) / self.filter[0].sum()
306
+ self.filter[1] = self.filter[1].view(1,1,1,-1) / self.filter[1].sum()
307
+
308
+ def transform_image(self, image):
309
+ if torch.is_tensor(image):
310
+ sz = image.shape[2:]
311
+ im1 = F.conv2d(image.view(-1, 1, sz[0], sz[1]), self.filter[0], padding=(self.filter_size[0], 0))
312
+ return F.conv2d(im1, self.filter[1], padding=(0,self.filter_size[1])).view(-1,sz[0],sz[1])
313
+ else:
314
+ raise NotImplementedError
315
+
316
+
317
+ class RandomBlur(TransformBase):
318
+ """ Blur the image, with a given probability, by applying a gaussian kernel with given sigma"""
319
+ def __init__(self, sigma, probability=0.1):
320
+ super().__init__()
321
+ self.probability = probability
322
+
323
+ if isinstance(sigma, (float, int)):
324
+ sigma = (sigma, sigma)
325
+ self.sigma = sigma
326
+ self.filter_size = [math.ceil(2*s) for s in self.sigma]
327
+ x_coord = [torch.arange(-sz, sz+1, dtype=torch.float32) for sz in self.filter_size]
328
+ self.filter = [torch.exp(-(x**2)/(2*s**2)) for x, s in zip(x_coord, self.sigma)]
329
+ self.filter[0] = self.filter[0].view(1,1,-1,1) / self.filter[0].sum()
330
+ self.filter[1] = self.filter[1].view(1,1,1,-1) / self.filter[1].sum()
331
+
332
+ def roll(self):
333
+ return random.random() < self.probability
334
+
335
+ def transform(self, image, do_blur=None):
336
+ if do_blur is None:
337
+ do_blur = False
338
+
339
+ if do_blur:
340
+ if torch.is_tensor(image):
341
+ sz = image.shape[1:]
342
+ im1 = F.conv2d(image.view(-1, 1, sz[0], sz[1]), self.filter[0], padding=(self.filter_size[0], 0))
343
+ return F.conv2d(im1, self.filter[1], padding=(0,self.filter_size[1])).view(-1,sz[0],sz[1])
344
+ else:
345
+ raise NotImplementedError
346
+ else:
347
+ return image
348
+
349
+
350
+ class RandomAffine(TransformBase):
351
+ """Apply random affine transformation."""
352
+ def __init__(self, p_flip=0.0, max_rotation=0.0, max_shear=0.0, max_scale=0.0, max_ar_factor=0.0,
353
+ border_mode='constant', pad_amount=0):
354
+ super().__init__()
355
+ self.p_flip = p_flip
356
+ self.max_rotation = max_rotation
357
+ self.max_shear = max_shear
358
+ self.max_scale = max_scale
359
+ self.max_ar_factor = max_ar_factor
360
+
361
+ if border_mode == 'constant':
362
+ self.border_flag = cv.BORDER_CONSTANT
363
+ elif border_mode == 'replicate':
364
+ self.border_flag == cv.BORDER_REPLICATE
365
+ else:
366
+ raise Exception
367
+
368
+ self.pad_amount = pad_amount
369
+
370
+ def roll(self):
371
+ do_flip = random.random() < self.p_flip
372
+ theta = random.uniform(-self.max_rotation, self.max_rotation)
373
+
374
+ shear_x = random.uniform(-self.max_shear, self.max_shear)
375
+ shear_y = random.uniform(-self.max_shear, self.max_shear)
376
+
377
+ ar_factor = np.exp(random.uniform(-self.max_ar_factor, self.max_ar_factor))
378
+ scale_factor = np.exp(random.uniform(-self.max_scale, self.max_scale))
379
+
380
+ return do_flip, theta, (shear_x, shear_y), (scale_factor, scale_factor * ar_factor)
381
+
382
+ def _construct_t_mat(self, image_shape, do_flip, theta, shear_values, scale_factors):
383
+ im_h, im_w = image_shape
384
+ t_mat = np.identity(3)
385
+
386
+ if do_flip:
387
+ if do_flip:
388
+ t_mat[0, 0] = -1.0
389
+ t_mat[0, 2] = im_w
390
+
391
+ t_rot = cv.getRotationMatrix2D((im_w * 0.5, im_h * 0.5), theta, 1.0)
392
+ t_rot = np.concatenate((t_rot, np.array([0.0, 0.0, 1.0]).reshape(1, 3)))
393
+
394
+ t_shear = np.array([[1.0, shear_values[0], -shear_values[0] * 0.5 * im_w],
395
+ [shear_values[1], 1.0, -shear_values[1] * 0.5 * im_h],
396
+ [0.0, 0.0, 1.0]])
397
+
398
+ t_scale = np.array([[scale_factors[0], 0.0, (1.0 - scale_factors[0]) * 0.5 * im_w],
399
+ [0.0, scale_factors[1], (1.0 - scale_factors[1]) * 0.5 * im_h],
400
+ [0.0, 0.0, 1.0]])
401
+
402
+ t_mat = t_scale @ t_rot @ t_shear @ t_mat
403
+
404
+ t_mat[0, 2] += self.pad_amount
405
+ t_mat[1, 2] += self.pad_amount
406
+
407
+ t_mat = t_mat[:2, :]
408
+
409
+ return t_mat
410
+
411
+ def transform_image(self, image, do_flip, theta, shear_values, scale_factors):
412
+ if torch.is_tensor(image):
413
+ raise Exception('Only supported for numpy input')
414
+
415
+ t_mat = self._construct_t_mat(image.shape[:2], do_flip, theta, shear_values, scale_factors)
416
+ output_sz = (image.shape[1] + 2*self.pad_amount, image.shape[0] + 2*self.pad_amount)
417
+ image_t = cv.warpAffine(image, t_mat, output_sz, flags=cv.INTER_LINEAR,
418
+ borderMode=self.border_flag)
419
+
420
+ return image_t
421
+
422
+ def transform_coords(self, coords, image_shape, do_flip, theta, shear_values, scale_factors):
423
+ t_mat = self._construct_t_mat(image_shape, do_flip, theta, shear_values, scale_factors)
424
+
425
+ t_mat_tensor = torch.from_numpy(t_mat).float()
426
+
427
+ coords_xy1 = torch.stack((coords[1, :], coords[0, :], torch.ones_like(coords[1, :])))
428
+
429
+ coords_xy_t = torch.mm(t_mat_tensor, coords_xy1)
430
+
431
+ return coords_xy_t[[1, 0], :]
432
+
433
+ def transform_mask(self, mask, do_flip, theta, shear_values, scale_factors):
434
+ t_mat = self._construct_t_mat(mask.shape[:2], do_flip, theta, shear_values, scale_factors)
435
+ output_sz = (mask.shape[1] + 2*self.pad_amount, mask.shape[0] + 2*self.pad_amount)
436
+
437
+ mask_t = cv.warpAffine(mask.numpy(), t_mat, output_sz, flags=cv.INTER_NEAREST,
438
+ borderMode=self.border_flag)
439
+
440
+ return torch.from_numpy(mask_t)
external/AR/ltr/dataset/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .lasot import Lasot
2
+ from .got10k import Got10k
3
+ from .tracking_net import TrackingNet
4
+ from .imagenetvid import ImagenetVID
5
+ from .coco import MSCOCO
6
+ from .coco_seq import MSCOCOSeq
7
+ from .youtubevos import YouTubeVOS
8
+ from .davis import Davis
9
+ from .lvis import LVIS
10
+ from .ecssd import ECSSD
11
+ from .msra10k import MSRA10k
12
+ from .hku_is import HKUIS
13
+ from .sbd import SBD
14
+ from .synthetic_video import SyntheticVideo
15
+ from .synthetic_video_blend import SyntheticVideoBlend
external/AR/ltr/dataset/base_image_dataset.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.utils.data
2
+ from ltr.data.image_loader import jpeg4py_loader
3
+
4
+
5
+ class BaseImageDataset(torch.utils.data.Dataset):
6
+ """ Base class for image datasets """
7
+
8
+ def __init__(self, name, root, image_loader=jpeg4py_loader):
9
+ """
10
+ args:
11
+ root - The root path to the dataset
12
+ image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)
13
+ is used by default.
14
+ """
15
+ self.name = name
16
+ self.root = root
17
+ self.image_loader = image_loader
18
+
19
+ self.image_list = [] # Contains the list of sequences.
20
+ self.class_list = []
21
+
22
+ def __len__(self):
23
+ """ Returns size of the dataset
24
+ returns:
25
+ int - number of samples in the dataset
26
+ """
27
+ return self.get_num_images()
28
+
29
+ def __getitem__(self, index):
30
+ """ Not to be used! Check get_frames() instead.
31
+ """
32
+ return None
33
+
34
+ def get_name(self):
35
+ """ Name of the dataset
36
+
37
+ returns:
38
+ string - Name of the dataset
39
+ """
40
+ raise NotImplementedError
41
+
42
+ def get_num_images(self):
43
+ """ Number of sequences in a dataset
44
+
45
+ returns:
46
+ int - number of sequences in the dataset."""
47
+ return len(self.image_list)
48
+
49
+ def has_class_info(self):
50
+ return False
51
+
52
+ def get_class_name(self, image_id):
53
+ return None
54
+
55
+ def get_num_classes(self):
56
+ return len(self.class_list)
57
+
58
+ def get_class_list(self):
59
+ return self.class_list
60
+
61
+ def get_images_in_class(self, class_name):
62
+ raise NotImplementedError
63
+
64
+ def has_segmentation_info(self):
65
+ return False
66
+
67
+ def get_image_info(self, seq_id):
68
+ """ Returns information about a particular image,
69
+
70
+ args:
71
+ seq_id - index of the image
72
+
73
+ returns:
74
+ Dict
75
+ """
76
+ raise NotImplementedError
77
+
78
+ def get_image(self, image_id, anno=None):
79
+ """ Get a image
80
+
81
+ args:
82
+ image_id - index of image
83
+ anno(None) - The annotation for the sequence (see get_sequence_info). If None, they will be loaded.
84
+
85
+ returns:
86
+ image -
87
+ anno -
88
+ dict - A dict containing meta information about the sequence, e.g. class of the target object.
89
+
90
+ """
91
+ raise NotImplementedError
92
+
external/AR/ltr/dataset/base_video_dataset.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.utils.data
2
+ from ltr.data.image_loader import jpeg4py_loader
3
+
4
+
5
+ class BaseVideoDataset(torch.utils.data.Dataset):
6
+ """ Base class for video datasets """
7
+
8
+ def __init__(self, name, root, image_loader=jpeg4py_loader):
9
+ """
10
+ args:
11
+ root - The root path to the dataset
12
+ image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)
13
+ is used by default.
14
+ """
15
+ self.name = name
16
+ self.root = root
17
+ self.image_loader = image_loader
18
+
19
+ self.sequence_list = [] # Contains the list of sequences.
20
+ self.class_list = []
21
+
22
+ def __len__(self):
23
+ """ Returns size of the dataset
24
+ returns:
25
+ int - number of samples in the dataset
26
+ """
27
+ return self.get_num_sequences()
28
+
29
+ def __getitem__(self, index):
30
+ """ Not to be used! Check get_frames() instead.
31
+ """
32
+ return None
33
+
34
+ def is_video_sequence(self):
35
+ """ Returns whether the dataset is a video dataset or an image dataset
36
+
37
+ returns:
38
+ bool - True if a video dataset
39
+ """
40
+ return True
41
+
42
+ def is_synthetic_video_dataset(self):
43
+ """ Returns whether the dataset contains real videos or synthetic
44
+
45
+ returns:
46
+ bool - True if a video dataset
47
+ """
48
+ return False
49
+
50
+ def get_name(self):
51
+ """ Name of the dataset
52
+
53
+ returns:
54
+ string - Name of the dataset
55
+ """
56
+ raise NotImplementedError
57
+
58
+ def get_num_sequences(self):
59
+ """ Number of sequences in a dataset
60
+
61
+ returns:
62
+ int - number of sequences in the dataset."""
63
+ return len(self.sequence_list)
64
+
65
+ def has_class_info(self):
66
+ return False
67
+
68
+ def has_occlusion_info(self):
69
+ return False
70
+
71
+ def get_num_classes(self):
72
+ return len(self.class_list)
73
+
74
+ def get_class_list(self):
75
+ return self.class_list
76
+
77
+ def get_sequences_in_class(self, class_name):
78
+ raise NotImplementedError
79
+
80
+ def has_segmentation_info(self):
81
+ return False
82
+
83
+ def get_sequence_info(self, seq_id):
84
+ """ Returns information about a particular sequences,
85
+
86
+ args:
87
+ seq_id - index of the sequence
88
+
89
+ returns:
90
+ Dict
91
+ """
92
+ raise NotImplementedError
93
+
94
+ def get_frames(self, seq_id, frame_ids, anno=None):
95
+ """ Get a set of frames from a particular sequence
96
+
97
+ args:
98
+ seq_id - index of sequence
99
+ frame_ids - a list of frame numbers
100
+ anno(None) - The annotation for the sequence (see get_sequence_info). If None, they will be loaded.
101
+
102
+ returns:
103
+ list - List of frames corresponding to frame_ids
104
+ list - List of dicts for each frame
105
+ dict - A dict containing meta information about the sequence, e.g. class of the target object.
106
+
107
+ """
108
+ raise NotImplementedError
109
+
external/AR/ltr/dataset/coco.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from .base_image_dataset import BaseImageDataset
3
+ from ltr.data.image_loader import jpeg4py_loader
4
+ import torch
5
+ from pycocotools.coco import COCO
6
+ import random
7
+ from collections import OrderedDict
8
+ from ltr.admin.environment import env_settings
9
+
10
+
11
+ class MSCOCO(BaseImageDataset):
12
+ """ The COCO object detection dataset.
13
+
14
+ Publication:
15
+ Microsoft COCO: Common Objects in Context.
16
+ Tsung-Yi Lin, Michael Maire, Serge J. Belongie, Lubomir D. Bourdev, Ross B. Girshick, James Hays, Pietro Perona,
17
+ Deva Ramanan, Piotr Dollar and C. Lawrence Zitnick
18
+ ECCV, 2014
19
+ https://arxiv.org/pdf/1405.0312.pdf
20
+
21
+ Download the images along with annotations from http://cocodataset.org/#download. The root folder should be
22
+ organized as follows.
23
+ - coco_root
24
+ - annotations
25
+ - instances_train2014.json
26
+ - instances_train2017.json
27
+ - images
28
+ - train2014
29
+ - train2017
30
+
31
+ Note: You also have to install the coco pythonAPI from https://github.com/cocodataset/cocoapi.
32
+ """
33
+
34
+ def __init__(self, root=None, image_loader=jpeg4py_loader, data_fraction=None, min_area=None,
35
+ split="train", version="2014"):
36
+ """
37
+ args:
38
+ root - path to coco root folder
39
+ image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)
40
+ is used by default.
41
+ data_fraction - Fraction of dataset to be used. The complete dataset is used by default
42
+ min_area - Objects with area less than min_area are filtered out. Default is 0.0
43
+ split - 'train' or 'val'.
44
+ version - version of coco dataset (2014 or 2017)
45
+ """
46
+
47
+ root = env_settings().coco_dir if root is None else root
48
+ super().__init__('COCO', root, image_loader)
49
+
50
+ self.img_pth = os.path.join(root, 'images/{}{}/'.format(split, version))
51
+ self.anno_path = os.path.join(root, 'annotations/instances_{}{}.json'.format(split, version))
52
+
53
+ self.coco_set = COCO(self.anno_path)
54
+
55
+ self.cats = self.coco_set.cats
56
+
57
+ self.class_list = self.get_class_list() # the parent class thing would happen in the sampler
58
+
59
+ self.image_list = self._get_image_list(min_area=min_area)
60
+
61
+ if data_fraction is not None:
62
+ self.image_list = random.sample(self.image_list, int(len(self.image_list) * data_fraction))
63
+ self.im_per_class = self._build_im_per_class()
64
+
65
+ def _get_image_list(self, min_area=None):
66
+ ann_list = list(self.coco_set.anns.keys())
67
+ image_list = [a for a in ann_list if self.coco_set.anns[a]['iscrowd'] == 0]
68
+
69
+ if min_area is not None:
70
+ image_list = [a for a in image_list if self.coco_set.anns[a]['area'] > min_area]
71
+
72
+ return image_list
73
+
74
+ def get_num_classes(self):
75
+ return len(self.class_list)
76
+
77
+ def get_name(self):
78
+ return 'coco'
79
+
80
+ def has_class_info(self):
81
+ return True
82
+
83
+ def has_segmentation_info(self):
84
+ return True
85
+
86
+ def get_class_list(self):
87
+ class_list = []
88
+ for cat_id in self.cats.keys():
89
+ class_list.append(self.cats[cat_id]['name'])
90
+ return class_list
91
+
92
+ def _build_im_per_class(self):
93
+ im_per_class = {}
94
+ for i, im in enumerate(self.image_list):
95
+ class_name = self.cats[self.coco_set.anns[im]['category_id']]['name']
96
+ if class_name not in im_per_class:
97
+ im_per_class[class_name] = [i]
98
+ else:
99
+ im_per_class[class_name].append(i)
100
+
101
+ return im_per_class
102
+
103
+ def get_images_in_class(self, class_name):
104
+ return self.im_per_class[class_name]
105
+
106
+ def get_image_info(self, im_id):
107
+ anno = self._get_anno(im_id)
108
+
109
+ bbox = torch.Tensor(anno['bbox']).view(4,)
110
+
111
+ mask = torch.Tensor(self.coco_set.annToMask(anno))
112
+
113
+ valid = (bbox[2] > 0) & (bbox[3] > 0)
114
+ visible = valid.clone().byte()
115
+
116
+ return {'bbox': bbox, 'mask': mask, 'valid': valid, 'visible': visible}
117
+
118
+ def _get_anno(self, im_id):
119
+ anno = self.coco_set.anns[self.image_list[im_id]]
120
+
121
+ return anno
122
+
123
+ def _get_image(self, im_id):
124
+ path = self.coco_set.loadImgs([self.coco_set.anns[self.image_list[im_id]]['image_id']])[0]['file_name']
125
+ img = self.image_loader(os.path.join(self.img_pth, path))
126
+ return img
127
+
128
+ def get_meta_info(self, im_id):
129
+ try:
130
+ cat_dict_current = self.cats[self.coco_set.anns[self.image_list[im_id]]['category_id']]
131
+ object_meta = OrderedDict({'object_class_name': cat_dict_current['name'],
132
+ 'motion_class': None,
133
+ 'major_class': cat_dict_current['supercategory'],
134
+ 'root_class': None,
135
+ 'motion_adverb': None})
136
+ except:
137
+ object_meta = OrderedDict({'object_class_name': None,
138
+ 'motion_class': None,
139
+ 'major_class': None,
140
+ 'root_class': None,
141
+ 'motion_adverb': None})
142
+ return object_meta
143
+
144
+ def get_class_name(self, im_id):
145
+ cat_dict_current = self.cats[self.coco_set.anns[self.image_list[im_id]]['category_id']]
146
+ return cat_dict_current['name']
147
+
148
+ def get_image(self, image_id, anno=None):
149
+ frame = self._get_image(image_id)
150
+
151
+ if anno is None:
152
+ anno = self.get_image_info(image_id)
153
+
154
+ object_meta = self.get_meta_info(image_id)
155
+
156
+ return frame, anno, object_meta
external/AR/ltr/dataset/coco_seq.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from .base_video_dataset import BaseVideoDataset
3
+ from ltr.data.image_loader import jpeg4py_loader
4
+ import torch
5
+ import random
6
+ from pycocotools.coco import COCO
7
+ from collections import OrderedDict
8
+ from ltr.admin.environment import env_settings
9
+
10
+
11
+ class MSCOCOSeq(BaseVideoDataset):
12
+ """ The COCO dataset. COCO is an image dataset. Thus, we treat each image as a sequence of length 1.
13
+
14
+ Publication:
15
+ Microsoft COCO: Common Objects in Context.
16
+ Tsung-Yi Lin, Michael Maire, Serge J. Belongie, Lubomir D. Bourdev, Ross B. Girshick, James Hays, Pietro Perona,
17
+ Deva Ramanan, Piotr Dollar and C. Lawrence Zitnick
18
+ ECCV, 2014
19
+ https://arxiv.org/pdf/1405.0312.pdf
20
+
21
+ Download the images along with annotations from http://cocodataset.org/#download. The root folder should be
22
+ organized as follows.
23
+ - coco_root
24
+ - annotations
25
+ - instances_train2014.json
26
+ - instances_train2017.json
27
+ - images
28
+ - train2014
29
+ - train2017
30
+
31
+ Note: You also have to install the coco pythonAPI from https://github.com/cocodataset/cocoapi.
32
+ """
33
+
34
+ def __init__(self, root=None, image_loader=jpeg4py_loader, data_fraction=None, split="train", version="2014"):
35
+ """
36
+ args:
37
+ root - path to the coco dataset.
38
+ image_loader (default_image_loader) - The function to read the images. If installed,
39
+ jpeg4py (https://github.com/ajkxyz/jpeg4py) is used by default. Else,
40
+ opencv's imread is used.
41
+ data_fraction (None) - Fraction of images to be used. The images are selected randomly. If None, all the
42
+ images will be used
43
+ split - 'train' or 'val'.
44
+ version - version of coco dataset (2014 or 2017)
45
+ """
46
+ root = env_settings().coco_dir if root is None else root
47
+ super().__init__('COCO', root, image_loader)
48
+
49
+ self.img_pth = os.path.join(root, 'images/{}{}/'.format(split, version))
50
+ self.anno_path = os.path.join(root, 'annotations/instances_{}{}.json'.format(split, version))
51
+
52
+ # Load the COCO set.
53
+ self.coco_set = COCO(self.anno_path)
54
+
55
+ self.cats = self.coco_set.cats
56
+
57
+ self.class_list = self.get_class_list()
58
+
59
+ self.sequence_list = self._get_sequence_list()
60
+
61
+ if data_fraction is not None:
62
+ self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list)*data_fraction))
63
+ self.seq_per_class = self._build_seq_per_class()
64
+
65
+ def _get_sequence_list(self):
66
+ ann_list = list(self.coco_set.anns.keys())
67
+ seq_list = [a for a in ann_list if self.coco_set.anns[a]['iscrowd'] == 0]
68
+
69
+ return seq_list
70
+
71
+ def is_video_sequence(self):
72
+ return False
73
+
74
+ def get_num_classes(self):
75
+ return len(self.class_list)
76
+
77
+ def get_name(self):
78
+ return 'coco'
79
+
80
+ def has_class_info(self):
81
+ return True
82
+
83
+ def get_class_list(self):
84
+ class_list = []
85
+ for cat_id in self.cats.keys():
86
+ class_list.append(self.cats[cat_id]['name'])
87
+ return class_list
88
+
89
+ def has_segmentation_info(self):
90
+ return True
91
+
92
+ def get_num_sequences(self):
93
+ return len(self.sequence_list)
94
+
95
+ def _build_seq_per_class(self):
96
+ seq_per_class = {}
97
+ for i, seq in enumerate(self.sequence_list):
98
+ class_name = self.cats[self.coco_set.anns[seq]['category_id']]['name']
99
+ if class_name not in seq_per_class:
100
+ seq_per_class[class_name] = [i]
101
+ else:
102
+ seq_per_class[class_name].append(i)
103
+
104
+ return seq_per_class
105
+
106
+ def get_sequences_in_class(self, class_name):
107
+ return self.seq_per_class[class_name]
108
+
109
+ def get_sequence_info(self, seq_id):
110
+ anno = self._get_anno(seq_id)
111
+
112
+ bbox = torch.Tensor(anno['bbox']).view(1, 4)
113
+
114
+ mask = torch.Tensor(self.coco_set.annToMask(anno)).unsqueeze(dim=0)
115
+
116
+ valid = (bbox[:, 2] > 0) & (bbox[:, 3] > 0)
117
+ visible = valid.clone().byte()
118
+
119
+ return {'bbox': bbox, 'mask': mask, 'valid': valid, 'visible': visible}
120
+
121
+ def _get_anno(self, seq_id):
122
+ anno = self.coco_set.anns[self.sequence_list[seq_id]]
123
+
124
+ return anno
125
+
126
+ def _get_frames(self, seq_id):
127
+ path = self.coco_set.loadImgs([self.coco_set.anns[self.sequence_list[seq_id]]['image_id']])[0]['file_name']
128
+ img = self.image_loader(os.path.join(self.img_pth, path))
129
+ return img
130
+
131
+ def get_meta_info(self, seq_id):
132
+ try:
133
+ cat_dict_current = self.cats[self.coco_set.anns[self.sequence_list[seq_id]]['category_id']]
134
+ object_meta = OrderedDict({'object_class_name': cat_dict_current['name'],
135
+ 'motion_class': None,
136
+ 'major_class': cat_dict_current['supercategory'],
137
+ 'root_class': None,
138
+ 'motion_adverb': None})
139
+ except:
140
+ object_meta = OrderedDict({'object_class_name': None,
141
+ 'motion_class': None,
142
+ 'major_class': None,
143
+ 'root_class': None,
144
+ 'motion_adverb': None})
145
+ return object_meta
146
+
147
+
148
+ def get_class_name(self, seq_id):
149
+ cat_dict_current = self.cats[self.coco_set.anns[self.sequence_list[seq_id]]['category_id']]
150
+ return cat_dict_current['name']
151
+
152
+ def get_frames(self, seq_id=None, frame_ids=None, anno=None):
153
+ # COCO is an image dataset. Thus we replicate the image denoted by seq_id len(frame_ids) times, and return a
154
+ # list containing these replicated images.
155
+ frame = self._get_frames(seq_id)
156
+
157
+ frame_list = [frame.copy() for _ in frame_ids]
158
+
159
+ if anno is None:
160
+ anno = self.get_sequence_info(seq_id)
161
+
162
+ anno_frames = {}
163
+ for key, value in anno.items():
164
+ anno_frames[key] = [value[0, ...] for _ in frame_ids]
165
+
166
+ object_meta = self.get_meta_info(seq_id)
167
+
168
+ return frame_list, anno_frames, object_meta
external/AR/ltr/dataset/davis.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ from ltr.dataset.vos_base import VOSDatasetBase, VOSMeta
3
+ from pytracking.evaluation import Sequence
4
+ from ltr.admin.environment import env_settings
5
+ from ltr.data.image_loader import jpeg4py_loader
6
+
7
+
8
+ class Davis(VOSDatasetBase):
9
+ """ The Davis VOS dataset
10
+
11
+ Publication:
12
+ A Benchmark Dataset and Evaluation Methodology for Video Object Segmentation
13
+ F. Perazzi, J. Pont-Tuset, B. McWilliams, L. Van Gool, M. Gross, and A. Sorkine-Hornung
14
+ CVPR, 2016
15
+ http://www.cv-foundation.org/openaccess/content_cvpr_2016/papers/Perazzi_A_Benchmark_Dataset_CVPR_2016_paper.pdf
16
+
17
+ Download the dataset from https://davischallenge.org/davis2017/code.html
18
+ """
19
+ def __init__(self, root=None, sequences=None, version='2017', split='train', multiobj=True,
20
+ vis_threshold=10, image_loader=jpeg4py_loader):
21
+ """
22
+ args:
23
+ root - Dataset root path. If unset, it uses the path in your local.py config.
24
+ sequences - List of sequence names. Limit to a subset of sequences if not None.
25
+ version - '2016' or '2017
26
+ split - Any name in DAVIS/ImageSets/<year>
27
+ multiobj - Whether the dataset will return all objects in a sequence or multiple sequences with one object
28
+ in each.
29
+ vis_threshold - Minimum number of pixels required to consider a target object "visible".
30
+ image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)
31
+ is used by default.
32
+ """
33
+ if version == '2017':
34
+ if split in ['train', 'val']:
35
+ root = env_settings().davis_dir if root is None else root
36
+ elif split in ['test-dev']:
37
+ root = env_settings().davis_testdev_dir if root is None else root
38
+ else:
39
+ raise Exception('Unknown split {}'.format(split))
40
+ else:
41
+ root = env_settings().davis16_dir if root is None else root
42
+
43
+ super().__init__(name='DAVIS', root=Path(root), version=version, split=split, multiobj=multiobj,
44
+ vis_threshold=vis_threshold, image_loader=image_loader)
45
+
46
+ dset_path = self.root
47
+ self._jpeg_path = dset_path / 'JPEGImages' / '480p'
48
+ self._anno_path = dset_path / 'Annotations' / '480p'
49
+
50
+ meta_path = dset_path / "generated_meta.json"
51
+ if meta_path.exists():
52
+ self.gmeta = VOSMeta(filename=meta_path)
53
+ else:
54
+ self.gmeta = VOSMeta.generate('DAVIS', self._jpeg_path, self._anno_path)
55
+ self.gmeta.save(meta_path)
56
+
57
+ if sequences is None:
58
+ if self.split != 'all':
59
+ fname = dset_path / 'ImageSets' / self.version / (self.split + '.txt')
60
+ sequences = open(fname).read().splitlines()
61
+ else:
62
+ sequences = [p for p in sorted(self._jpeg_path.glob("*")) if p.is_dir()]
63
+
64
+ self.sequence_names = sequences
65
+ self._samples = []
66
+
67
+ for seq in sequences:
68
+ obj_ids = self.gmeta.get_obj_ids(seq)
69
+ if self.multiobj: # Multiple objects per sample
70
+ self._samples.append((seq, obj_ids))
71
+ else: # One object per sample
72
+ self._samples.extend([(seq, [obj_id]) for obj_id in obj_ids])
73
+
74
+ print("%s loaded." % self.get_name())
75
+
76
+ def _construct_sequence(self, sequence_info):
77
+
78
+ seq_name = sequence_info['sequence']
79
+ images, gt_labels, gt_bboxes = self.get_paths_and_bboxes(sequence_info)
80
+
81
+ return Sequence(name=seq_name, frames=images, dataset='DAVIS', ground_truth_rect=gt_bboxes,
82
+ ground_truth_seg=gt_labels, object_ids=sequence_info['object_ids'],
83
+ multiobj_mode=self.multiobj)
external/AR/ltr/dataset/ecssd.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from .base_image_dataset import BaseImageDataset
3
+ from ltr.data.image_loader import jpeg4py_loader, opencv_loader, imread_indexed
4
+ import torch
5
+ from collections import OrderedDict
6
+ from ltr.admin.environment import env_settings
7
+ from ltr.data.bounding_box_utils import masks_to_bboxes
8
+
9
+
10
+ class ECSSD(BaseImageDataset):
11
+ """
12
+ Extended Complex Scene Saliency Dataset (ECSSD)
13
+
14
+ Publication:
15
+ Hierarchical Image Saliency Detection on Extended CSSD
16
+ Jianping Shi, Qiong Yan, Li Xu, Jiaya Jia
17
+ TPAMI, 2016
18
+ https://arxiv.org/pdf/1408.5418.pdf
19
+
20
+ Download the dataset from http://www.cse.cuhk.edu.hk/leojia/projects/hsaliency/dataset.html
21
+ """
22
+ def __init__(self, root=None, image_loader=jpeg4py_loader, data_fraction=None, min_area=None):
23
+ """
24
+ args:
25
+ root - path to ECSSD root folder
26
+ image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)
27
+ is used by default.
28
+ data_fraction - Fraction of dataset to be used. The complete dataset is used by default
29
+ min_area - Objects with area less than min_area are filtered out. Default is 0.0
30
+ """
31
+ root = env_settings().ecssd_dir if root is None else root
32
+ super().__init__('ECSSD', root, image_loader)
33
+
34
+ self.image_list = self._load_dataset(min_area=min_area)
35
+
36
+ if data_fraction is not None:
37
+ raise NotImplementedError
38
+
39
+ def _load_dataset(self, min_area=None):
40
+ images = []
41
+
42
+ for i in range(1, 1001):
43
+ a = imread_indexed(os.path.join(self.root, 'ground_truth_mask', '{:04d}.png'.format(i)))
44
+
45
+ if min_area is None or (a > 0).sum() > min_area:
46
+ images.append(i)
47
+
48
+ return images
49
+
50
+ def get_name(self):
51
+ return 'ecssd'
52
+
53
+ def has_segmentation_info(self):
54
+ return True
55
+
56
+ def get_image_info(self, im_id):
57
+ mask = imread_indexed(os.path.join(self.root, 'ground_truth_mask', '{:04d}.png'.format(self.image_list[im_id])))
58
+
59
+ mask = torch.Tensor(mask == 255)
60
+ bbox = masks_to_bboxes(mask, fmt='t').view(4,)
61
+
62
+ valid = (bbox[2] > 0) & (bbox[3] > 0)
63
+ visible = valid.clone().byte()
64
+
65
+ return {'bbox': bbox, 'mask': mask, 'valid': valid, 'visible': visible}
66
+
67
+ def get_meta_info(self, im_id):
68
+ object_meta = OrderedDict({'object_class_name': None,
69
+ 'motion_class': None,
70
+ 'major_class': None,
71
+ 'root_class': None,
72
+ 'motion_adverb': None})
73
+
74
+ return object_meta
75
+
76
+ def get_image(self, image_id, anno=None):
77
+ frame = self.image_loader(os.path.join(self.root, 'images', '{:04d}.jpg'.format(self.image_list[image_id])))
78
+
79
+ if anno is None:
80
+ anno = self.get_image_info(image_id)
81
+
82
+ object_meta = self.get_meta_info(image_id)
83
+
84
+ return frame, anno, object_meta
external/AR/ltr/dataset/got10k.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import os.path
3
+ import numpy as np
4
+ import torch
5
+ import csv
6
+ import pandas
7
+ import random
8
+ from collections import OrderedDict
9
+ from .base_video_dataset import BaseVideoDataset
10
+ from ltr.data.image_loader import jpeg4py_loader
11
+ from ltr.admin.environment import env_settings
12
+
13
+
14
+ class Got10k(BaseVideoDataset):
15
+ """ GOT-10k dataset.
16
+
17
+ Publication:
18
+ GOT-10k: A Large High-Diversity Benchmark for Generic Object Tracking in the Wild
19
+ Lianghua Huang, Xin Zhao, and Kaiqi Huang
20
+ arXiv:1810.11981, 2018
21
+ https://arxiv.org/pdf/1810.11981.pdf
22
+
23
+ Download dataset from http://got-10k.aitestunion.com/downloads
24
+ """
25
+
26
+ def __init__(self, root=None, image_loader=jpeg4py_loader, split=None, seq_ids=None, data_fraction=None):
27
+ """
28
+ args:
29
+ root - path to the got-10k training data. Note: This should point to the 'train' folder inside GOT-10k
30
+ image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)
31
+ is used by default.
32
+ split - 'train' or 'val'. Note: The validation split here is a subset of the official got-10k train split,
33
+ not NOT the official got-10k validation split. To use the official validation split, provide that as
34
+ the root folder instead.
35
+ seq_ids - List containing the ids of the videos to be used for training. Note: Only one of 'split' or 'seq_ids'
36
+ options can be used at the same time.
37
+ data_fraction - Fraction of dataset to be used. The complete dataset is used by default
38
+ """
39
+ root = env_settings().got10k_dir if root is None else root
40
+ super().__init__('GOT10k', root, image_loader)
41
+
42
+ # all folders inside the root
43
+ self.sequence_list = self._get_sequence_list()
44
+
45
+ # seq_id is the index of the folder inside the got10k root path
46
+ if split is not None:
47
+ if seq_ids is not None:
48
+ raise ValueError('Cannot set both split_name and seq_ids.')
49
+ ltr_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')
50
+ if split == 'train':
51
+ file_path = os.path.join(ltr_path, 'data_specs', 'got10k_train_split.txt')
52
+ elif split == 'val':
53
+ file_path = os.path.join(ltr_path, 'data_specs', 'got10k_val_split.txt')
54
+ elif split == 'vottrain':
55
+ file_path = os.path.join(ltr_path, 'data_specs', 'got10k_vot_train_split.txt')
56
+ elif split == 'votval':
57
+ file_path = os.path.join(ltr_path, 'data_specs', 'got10k_vot_val_split.txt')
58
+ else:
59
+ raise ValueError('Unknown split name.')
60
+ seq_ids = pandas.read_csv(file_path, header=None, squeeze=True, dtype=np.int64).values.tolist()
61
+ elif seq_ids is None:
62
+ seq_ids = list(range(0, len(self.sequence_list)))
63
+
64
+ self.sequence_list = [self.sequence_list[i] for i in seq_ids]
65
+
66
+ if data_fraction is not None:
67
+ self.sequence_list = random.sample(self.sequence_list, int(len(self.sequence_list)*data_fraction))
68
+
69
+ self.sequence_meta_info = self._load_meta_info()
70
+ self.seq_per_class = self._build_seq_per_class()
71
+
72
+ self.class_list = list(self.seq_per_class.keys())
73
+ self.class_list.sort()
74
+
75
+ def get_name(self):
76
+ return 'got10k'
77
+
78
+ def has_class_info(self):
79
+ return True
80
+
81
+ def has_occlusion_info(self):
82
+ return True
83
+
84
+ def _load_meta_info(self):
85
+ sequence_meta_info = {s: self._read_meta(os.path.join(self.root, s)) for s in self.sequence_list}
86
+ return sequence_meta_info
87
+
88
+ def _read_meta(self, seq_path):
89
+ try:
90
+ with open(os.path.join(seq_path, 'meta_info.ini')) as f:
91
+ meta_info = f.readlines()
92
+ object_meta = OrderedDict({'object_class_name': meta_info[5].split(': ')[-1][:-1],
93
+ 'motion_class': meta_info[6].split(': ')[-1][:-1],
94
+ 'major_class': meta_info[7].split(': ')[-1][:-1],
95
+ 'root_class': meta_info[8].split(': ')[-1][:-1],
96
+ 'motion_adverb': meta_info[9].split(': ')[-1][:-1]})
97
+ except:
98
+ object_meta = OrderedDict({'object_class_name': None,
99
+ 'motion_class': None,
100
+ 'major_class': None,
101
+ 'root_class': None,
102
+ 'motion_adverb': None})
103
+ return object_meta
104
+
105
+ def _build_seq_per_class(self):
106
+ seq_per_class = {}
107
+
108
+ for i, s in enumerate(self.sequence_list):
109
+ object_class = self.sequence_meta_info[s]['object_class_name']
110
+ if object_class in seq_per_class:
111
+ seq_per_class[object_class].append(i)
112
+ else:
113
+ seq_per_class[object_class] = [i]
114
+
115
+ return seq_per_class
116
+
117
+ def get_sequences_in_class(self, class_name):
118
+ return self.seq_per_class[class_name]
119
+
120
+ def _get_sequence_list(self):
121
+ with open(os.path.join(self.root, 'list.txt')) as f:
122
+ dir_list = list(csv.reader(f))
123
+ dir_list = [dir_name[0] for dir_name in dir_list]
124
+ return dir_list
125
+
126
+ def _read_bb_anno(self, seq_path):
127
+ bb_anno_file = os.path.join(seq_path, "groundtruth.txt")
128
+ gt = pandas.read_csv(bb_anno_file, delimiter=',', header=None, dtype=np.float32, na_filter=False, low_memory=False).values
129
+ return torch.tensor(gt)
130
+
131
+ def _read_target_visible(self, seq_path):
132
+ # Read full occlusion and out_of_view
133
+ occlusion_file = os.path.join(seq_path, "absence.label")
134
+ cover_file = os.path.join(seq_path, "cover.label")
135
+
136
+ with open(occlusion_file, 'r', newline='') as f:
137
+ occlusion = torch.ByteTensor([int(v[0]) for v in csv.reader(f)])
138
+ with open(cover_file, 'r', newline='') as f:
139
+ cover = torch.ByteTensor([int(v[0]) for v in csv.reader(f)])
140
+
141
+ target_visible = ~occlusion & (cover>0).byte()
142
+
143
+ visible_ratio = cover.float() / 8
144
+ return target_visible, visible_ratio
145
+
146
+ def _get_sequence_path(self, seq_id):
147
+ return os.path.join(self.root, self.sequence_list[seq_id])
148
+
149
+ def get_sequence_info(self, seq_id):
150
+ seq_path = self._get_sequence_path(seq_id)
151
+ bbox = self._read_bb_anno(seq_path)
152
+
153
+ valid = (bbox[:, 2] > 0) & (bbox[:, 3] > 0)
154
+ visible, visible_ratio = self._read_target_visible(seq_path)
155
+ visible = visible & valid.byte()
156
+
157
+ return {'bbox': bbox, 'valid': valid, 'visible': visible, 'visible_ratio': visible_ratio}
158
+
159
+ def _get_frame_path(self, seq_path, frame_id):
160
+ return os.path.join(seq_path, '{:08}.jpg'.format(frame_id+1)) # frames start from 1
161
+
162
+ def _get_frame(self, seq_path, frame_id):
163
+ return self.image_loader(self._get_frame_path(seq_path, frame_id))
164
+
165
+ def get_class_name(self, seq_id):
166
+ obj_meta = self.sequence_meta_info[self.sequence_list[seq_id]]
167
+
168
+ return obj_meta['object_class_name']
169
+
170
+ def get_frames(self, seq_id, frame_ids, anno=None):
171
+ seq_path = self._get_sequence_path(seq_id)
172
+ obj_meta = self.sequence_meta_info[self.sequence_list[seq_id]]
173
+
174
+ frame_list = [self._get_frame(seq_path, f_id) for f_id in frame_ids]
175
+
176
+ if anno is None:
177
+ anno = self.get_sequence_info(seq_id)
178
+
179
+ anno_frames = {}
180
+ for key, value in anno.items():
181
+ anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]
182
+
183
+ return frame_list, anno_frames, obj_meta
external/AR/ltr/dataset/hku_is.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from .base_image_dataset import BaseImageDataset
3
+ from ltr.data.image_loader import jpeg4py_loader, opencv_loader, imread_indexed
4
+ import torch
5
+ from collections import OrderedDict
6
+ from ltr.admin.environment import env_settings
7
+ from ltr.data.bounding_box_utils import masks_to_bboxes
8
+
9
+
10
+ class HKUIS(BaseImageDataset):
11
+ """
12
+ HKU-IS salient object detection dataset
13
+
14
+ Publication:
15
+ Visual saliency based on multiscale deep features
16
+ Guanbin Li and Yizhou Yu
17
+ CVPR, 2015
18
+ https://arxiv.org/pdf/1503.08663.pdf
19
+
20
+ Dowload dataset from https://sites.google.com/site/ligb86/hkuis
21
+ """
22
+
23
+ def __init__(self, root=None, image_loader=jpeg4py_loader, data_fraction=None, min_area=None):
24
+ """
25
+ args:
26
+ root - path to HKU-IS root folder
27
+ image_loader (jpeg4py_loader) - The function to read the images. jpeg4py (https://github.com/ajkxyz/jpeg4py)
28
+ is used by default.
29
+ data_fraction - Fraction of dataset to be used. The complete dataset is used by default
30
+ min_area - Objects with area less than min_area are filtered out. Default is 0.0
31
+ """
32
+ root = env_settings().hkuis_dir if root is None else root
33
+ super().__init__('HKUIS', root, image_loader)
34
+
35
+ self.image_list, self.anno_list = self._load_dataset(min_area=min_area)
36
+
37
+ if data_fraction is not None:
38
+ raise NotImplementedError
39
+
40
+ def _load_dataset(self, min_area=None):
41
+ files_list = os.listdir(os.path.join(self.root, 'imgs'))
42
+ image_list = [f[:-4] for f in files_list]
43
+
44
+ images = []
45
+ annos = []
46
+
47
+ for f in image_list:
48
+ a = imread_indexed(os.path.join(self.root, 'gt', '{}.png'.format(f)))
49
+
50
+ if min_area is None or (a > 0).sum() > min_area:
51
+ im = opencv_loader(os.path.join(self.root, 'imgs', '{}.png'.format(f)))
52
+ images.append(im)
53
+ annos.append(a)
54
+
55
+ return images, annos
56
+
57
+ def get_name(self):
58
+ return 'hku-is'
59
+
60
+ def has_segmentation_info(self):
61
+ return True
62
+
63
+ def get_image_info(self, im_id):
64
+ mask = self.anno_list[im_id]
65
+ mask = torch.Tensor(mask == 255)
66
+ bbox = masks_to_bboxes(mask, fmt='t').view(4,)
67
+
68
+ valid = (bbox[2] > 0) & (bbox[3] > 0)
69
+ visible = valid.clone().byte()
70
+
71
+ return {'bbox': bbox, 'mask': mask, 'valid': valid, 'visible': visible}
72
+
73
+ def get_meta_info(self, im_id):
74
+ object_meta = OrderedDict({'object_class_name': None,
75
+ 'motion_class': None,
76
+ 'major_class': None,
77
+ 'root_class': None,
78
+ 'motion_adverb': None})
79
+
80
+ return object_meta
81
+
82
+ def get_image(self, image_id, anno=None):
83
+ frame = self.image_list[image_id]
84
+
85
+ if anno is None:
86
+ anno = self.get_image_info(image_id)
87
+
88
+ object_meta = self.get_meta_info(image_id)
89
+
90
+ return frame, anno, object_meta
external/AR/ltr/dataset/imagenetvid.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from .base_video_dataset import BaseVideoDataset
3
+ from ltr.data.image_loader import default_image_loader
4
+ import xml.etree.ElementTree as ET
5
+ import json
6
+ import torch
7
+ import random
8
+ from collections import OrderedDict
9
+ from ltr.admin.environment import env_settings
10
+
11
+
12
+ def get_target_to_image_ratio(seq):
13
+ anno = torch.Tensor(seq['anno'])
14
+ img_sz = torch.Tensor(seq['image_size'])
15
+ return (anno[0, 2:4].prod() / (img_sz.prod())).sqrt()
16
+
17
+
18
+ class ImagenetVID(BaseVideoDataset):
19
+ """ Imagenet VID dataset.
20
+
21
+ Publication:
22
+ ImageNet Large Scale Visual Recognition Challenge
23
+ Olga Russakovsky, Jia Deng, Hao Su, Jonathan Krause, Sanjeev Satheesh, Sean Ma, Zhiheng Huang, Andrej Karpathy,
24
+ Aditya Khosla, Michael Bernstein, Alexander C. Berg and Li Fei-Fei
25
+ IJCV, 2015
26
+ https://arxiv.org/pdf/1409.0575.pdf
27
+
28
+ Download the dataset from http://image-net.org/
29
+ """
30
+ def __init__(self, root=None, image_loader=default_image_loader, min_length=0, max_target_area=1):
31
+ """
32
+ args:
33
+ root - path to the imagenet vid dataset.
34
+ image_loader (default_image_loader) - The function to read the images. If installed,
35
+ jpeg4py (https://github.com/ajkxyz/jpeg4py) is used by default. Else,
36
+ opencv's imread is used.
37
+ min_length - Minimum allowed sequence length.
38
+ max_target_area - max allowed ratio between target area and image area. Can be used to filter out targets
39
+ which cover complete image.
40
+ """
41
+ root = env_settings().imagenet_dir if root is None else root
42
+ super().__init__(root, image_loader)
43
+
44
+ cache_file = os.path.join(root, 'cache.json')
45
+ if os.path.isfile(cache_file):
46
+ # If available, load the pre-processed cache file containing meta-info for each sequence
47
+ with open(cache_file, 'r') as f:
48
+ sequence_list_dict = json.load(f)
49
+
50
+ self.sequence_list = sequence_list_dict
51
+ else:
52
+ # Else process the imagenet annotations and generate the cache file
53
+ self.sequence_list = self._process_anno(root)
54
+
55
+ with open(cache_file, 'w') as f:
56
+ json.dump(self.sequence_list, f)
57
+
58
+ # Filter the sequences based on min_length and max_target_area in the first frame
59
+ self.sequence_list = [x for x in self.sequence_list if len(x['anno']) >= min_length and
60
+ get_target_to_image_ratio(x) < max_target_area]
61
+
62
+ def get_name(self):
63
+ return 'imagenetvid'
64
+
65
+ def get_num_sequences(self):
66
+ return len(self.sequence_list)
67
+
68
+ def get_sequence_info(self, seq_id):
69
+ bb_anno = torch.Tensor(self.sequence_list[seq_id]['anno'])
70
+ valid = (bb_anno[:, 2] > 0) & (bb_anno[:, 3] > 0)
71
+ visible = torch.ByteTensor(self.sequence_list[seq_id]['target_visible']) & valid.byte()
72
+ return {'bbox': bb_anno, 'valid': valid, 'visible': visible}
73
+
74
+ def _get_frame(self, sequence, frame_id):
75
+ set_name = 'ILSVRC2015_VID_train_{:04d}'.format(sequence['set_id'])
76
+ vid_name = 'ILSVRC2015_train_{:08d}'.format(sequence['vid_id'])
77
+ frame_number = frame_id + sequence['start_frame']
78
+
79
+ frame_path = os.path.join(self.root, 'Data', 'VID', 'train', set_name, vid_name,
80
+ '{:06d}.JPEG'.format(frame_number))
81
+ return self.image_loader(frame_path)
82
+
83
+ def get_frames(self, seq_id, frame_ids, anno=None):
84
+ sequence = self.sequence_list[seq_id]
85
+
86
+ frame_list = [self._get_frame(sequence, f) for f in frame_ids]
87
+
88
+ if anno is None:
89
+ anno = self.get_sequence_info(seq_id)
90
+
91
+ # Create anno dict
92
+ anno_frames = {}
93
+ for key, value in anno.items():
94
+ anno_frames[key] = [value[f_id, ...].clone() for f_id in frame_ids]
95
+
96
+ # added the class info to the meta info
97
+ object_meta = OrderedDict({'object_class': sequence['class_name'],
98
+ 'motion_class': None,
99
+ 'major_class': None,
100
+ 'root_class': None,
101
+ 'motion_adverb': None})
102
+
103
+ return frame_list, anno_frames, object_meta
104
+
105
+ def _process_anno(self, root):
106
+ # Builds individual tracklets
107
+ base_vid_anno_path = os.path.join(root, 'Annotations', 'VID', 'train')
108
+
109
+ all_sequences = []
110
+ for set in sorted(os.listdir(base_vid_anno_path)):
111
+ set_id = int(set.split('_')[-1])
112
+ for vid in sorted(os.listdir(os.path.join(base_vid_anno_path, set))):
113
+
114
+ vid_id = int(vid.split('_')[-1])
115
+ anno_files = sorted(os.listdir(os.path.join(base_vid_anno_path, set, vid)))
116
+
117
+ frame1_anno = ET.parse(os.path.join(base_vid_anno_path, set, vid, anno_files[0]))
118
+ image_size = [int(frame1_anno.find('size/width').text), int(frame1_anno.find('size/height').text)]
119
+
120
+ objects = [ET.ElementTree(file=os.path.join(base_vid_anno_path, set, vid, f)).findall('object')
121
+ for f in anno_files]
122
+
123
+ tracklets = {}
124
+
125
+ # Find all tracklets along with start frame
126
+ for f_id, all_targets in enumerate(objects):
127
+ for target in all_targets:
128
+ tracklet_id = target.find('trackid').text
129
+ if tracklet_id not in tracklets:
130
+ tracklets[tracklet_id] = f_id
131
+
132
+ for tracklet_id, tracklet_start in tracklets.items():
133
+ tracklet_anno = []
134
+ target_visible = []
135
+ class_name_id = None
136
+
137
+ for f_id in range(tracklet_start, len(objects)):
138
+ found = False
139
+ for target in objects[f_id]:
140
+ if target.find('trackid').text == tracklet_id:
141
+ if not class_name_id:
142
+ class_name_id = target.find('name').text
143
+ x1 = int(target.find('bndbox/xmin').text)
144
+ y1 = int(target.find('bndbox/ymin').text)
145
+ x2 = int(target.find('bndbox/xmax').text)
146
+ y2 = int(target.find('bndbox/ymax').text)
147
+
148
+ tracklet_anno.append([x1, y1, x2 - x1, y2 - y1])
149
+ target_visible.append(target.find('occluded').text == '0')
150
+
151
+ found = True
152
+ break
153
+ if not found:
154
+ break
155
+
156
+ new_sequence = {'set_id': set_id, 'vid_id': vid_id, 'class_name': class_name_id,
157
+ 'start_frame': tracklet_start, 'anno': tracklet_anno,
158
+ 'target_visible': target_visible, 'image_size': image_size}
159
+ all_sequences.append(new_sequence)
160
+
161
+ return all_sequences