guyuchao commited on
Commit
d6ddad4
·
verified ·
1 Parent(s): ae24095

Add files using upload-large-folder tool

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 +15 -0
  2. torch_hub/checkpoints/alexnet-owt-7be5be79.pth +3 -0
  3. torch_hub/checkpoints/convnext_tiny_1k_224_ema.pth +3 -0
  4. torch_hub/checkpoints/cotracker2.pth +3 -0
  5. torch_hub/checkpoints/dino_vitbase16_pretrain.pth +3 -0
  6. torch_hub/checkpoints/dinov2_vitb14_reg4_pretrain.pth +3 -0
  7. torch_hub/checkpoints/pt_inception-2015-12-05-6726825d.pth +3 -0
  8. torch_hub/checkpoints/vgg16-397923af.pth +3 -0
  9. torch_hub/checkpoints/weights-inception-2015-12-05-6726825d.pth +3 -0
  10. torch_hub/facebookresearch_co-tracker_main/CODE_OF_CONDUCT.md +80 -0
  11. torch_hub/facebookresearch_co-tracker_main/CONTRIBUTING.md +28 -0
  12. torch_hub/facebookresearch_co-tracker_main/LICENSE.md +399 -0
  13. torch_hub/facebookresearch_co-tracker_main/README.md +360 -0
  14. torch_hub/facebookresearch_co-tracker_main/__pycache__/hubconf.cpython-310.pyc +0 -0
  15. torch_hub/facebookresearch_co-tracker_main/assets/apple.mp4 +3 -0
  16. torch_hub/facebookresearch_co-tracker_main/assets/apple_mask.png +0 -0
  17. torch_hub/facebookresearch_co-tracker_main/assets/bmx-bumps.gif +3 -0
  18. torch_hub/facebookresearch_co-tracker_main/assets/teaser.png +3 -0
  19. torch_hub/facebookresearch_co-tracker_main/cotracker/__init__.py +5 -0
  20. torch_hub/facebookresearch_co-tracker_main/cotracker/__pycache__/__init__.cpython-310.pyc +0 -0
  21. torch_hub/facebookresearch_co-tracker_main/cotracker/__pycache__/predictor.cpython-310.pyc +0 -0
  22. torch_hub/facebookresearch_co-tracker_main/cotracker/datasets/__init__.py +5 -0
  23. torch_hub/facebookresearch_co-tracker_main/cotracker/datasets/dataclass_utils.py +168 -0
  24. torch_hub/facebookresearch_co-tracker_main/cotracker/datasets/dr_dataset.py +168 -0
  25. torch_hub/facebookresearch_co-tracker_main/cotracker/datasets/kubric_movif_dataset.py +542 -0
  26. torch_hub/facebookresearch_co-tracker_main/cotracker/datasets/real_dataset.py +282 -0
  27. torch_hub/facebookresearch_co-tracker_main/cotracker/datasets/tap_vid_datasets.py +244 -0
  28. torch_hub/facebookresearch_co-tracker_main/cotracker/datasets/utils.py +120 -0
  29. torch_hub/facebookresearch_co-tracker_main/cotracker/evaluation/__init__.py +5 -0
  30. torch_hub/facebookresearch_co-tracker_main/cotracker/evaluation/configs/eval_dynamic_replica.yaml +6 -0
  31. torch_hub/facebookresearch_co-tracker_main/cotracker/evaluation/configs/eval_tapvid_davis_first.yaml +6 -0
  32. torch_hub/facebookresearch_co-tracker_main/cotracker/evaluation/configs/eval_tapvid_davis_strided.yaml +6 -0
  33. torch_hub/facebookresearch_co-tracker_main/cotracker/evaluation/configs/eval_tapvid_kinetics_first.yaml +6 -0
  34. torch_hub/facebookresearch_co-tracker_main/cotracker/evaluation/configs/eval_tapvid_robotap_first.yaml +4 -0
  35. torch_hub/facebookresearch_co-tracker_main/cotracker/evaluation/configs/eval_tapvid_stacking_first.yaml +6 -0
  36. torch_hub/facebookresearch_co-tracker_main/cotracker/evaluation/configs/eval_tapvid_stacking_strided.yaml +6 -0
  37. torch_hub/facebookresearch_co-tracker_main/cotracker/evaluation/core/__init__.py +5 -0
  38. torch_hub/facebookresearch_co-tracker_main/cotracker/evaluation/core/eval_utils.py +138 -0
  39. torch_hub/facebookresearch_co-tracker_main/cotracker/evaluation/core/evaluator.py +288 -0
  40. torch_hub/facebookresearch_co-tracker_main/cotracker/evaluation/evaluate.py +190 -0
  41. torch_hub/facebookresearch_co-tracker_main/cotracker/models/__init__.py +5 -0
  42. torch_hub/facebookresearch_co-tracker_main/cotracker/models/__pycache__/__init__.cpython-310.pyc +0 -0
  43. torch_hub/facebookresearch_co-tracker_main/cotracker/models/__pycache__/build_cotracker.cpython-310.pyc +0 -0
  44. torch_hub/facebookresearch_co-tracker_main/cotracker/models/bootstap_predictor.py +65 -0
  45. torch_hub/facebookresearch_co-tracker_main/cotracker/models/build_cotracker.py +45 -0
  46. torch_hub/facebookresearch_co-tracker_main/cotracker/models/core/__init__.py +5 -0
  47. torch_hub/facebookresearch_co-tracker_main/cotracker/models/core/__pycache__/__init__.cpython-310.pyc +0 -0
  48. torch_hub/facebookresearch_co-tracker_main/cotracker/models/core/__pycache__/embeddings.cpython-310.pyc +0 -0
  49. torch_hub/facebookresearch_co-tracker_main/cotracker/models/core/__pycache__/model_utils.cpython-310.pyc +0 -0
  50. torch_hub/facebookresearch_co-tracker_main/cotracker/models/core/cotracker/__init__.py +5 -0
.gitattributes CHANGED
@@ -41,3 +41,18 @@ dino_model/facebookresearch_dino_main/.github/dino.gif filter=lfs diff=lfs merge
41
  dreamsim_model/facebookresearch_dino_main/.github/attention_maps.png filter=lfs diff=lfs merge=lfs -text
42
  dreamsim_model/facebookresearch_co-tracker_main/notebooks/demo.ipynb filter=lfs diff=lfs merge=lfs -text
43
  torch_hub/facebookresearch_dino_main/.github/dino.gif filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  dreamsim_model/facebookresearch_dino_main/.github/attention_maps.png filter=lfs diff=lfs merge=lfs -text
42
  dreamsim_model/facebookresearch_co-tracker_main/notebooks/demo.ipynb filter=lfs diff=lfs merge=lfs -text
43
  torch_hub/facebookresearch_dino_main/.github/dino.gif filter=lfs diff=lfs merge=lfs -text
44
+ torch_hub/facebookresearch_dinov2_main/docs/ChannelAdaptiveDINO.png filter=lfs diff=lfs merge=lfs -text
45
+ torch_hub/facebookresearch_dinov2_main/docs/Cell-DINO.png filter=lfs diff=lfs merge=lfs -text
46
+ torch_hub/facebookresearch_co-tracker_main/gradio_demo/videos/teddy.mp4 filter=lfs diff=lfs merge=lfs -text
47
+ torch_hub/facebookresearch_co-tracker_main/gradio_demo/videos/paragliding.mp4 filter=lfs diff=lfs merge=lfs -text
48
+ torch_hub/facebookresearch_co-tracker_main/assets/apple.mp4 filter=lfs diff=lfs merge=lfs -text
49
+ torch_hub/facebookresearch_dino_main/.github/attention_maps.png filter=lfs diff=lfs merge=lfs -text
50
+ torch_hub/facebookresearch_co-tracker_main/notebooks/demo.ipynb filter=lfs diff=lfs merge=lfs -text
51
+ torch_hub/facebookresearch_co-tracker_main/gradio_demo/videos/bear.mp4 filter=lfs diff=lfs merge=lfs -text
52
+ torch_hub/facebookresearch_co-tracker_main/gradio_demo/videos/cat.mp4 filter=lfs diff=lfs merge=lfs -text
53
+ torch_hub/facebookresearch_co-tracker_main/gradio_demo/videos/apple.mp4 filter=lfs diff=lfs merge=lfs -text
54
+ torch_hub/facebookresearch_co-tracker_main/gradio_demo/videos/backpack.mp4 filter=lfs diff=lfs merge=lfs -text
55
+ torch_hub/facebookresearch_co-tracker_main/gradio_demo/videos/pillow.mp4 filter=lfs diff=lfs merge=lfs -text
56
+ torch_hub/facebookresearch_co-tracker_main/gradio_demo/videos/paragliding-launch.mp4 filter=lfs diff=lfs merge=lfs -text
57
+ torch_hub/facebookresearch_co-tracker_main/assets/teaser.png filter=lfs diff=lfs merge=lfs -text
58
+ torch_hub/facebookresearch_co-tracker_main/assets/bmx-bumps.gif filter=lfs diff=lfs merge=lfs -text
torch_hub/checkpoints/alexnet-owt-7be5be79.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7be5be791159472b1fbf3c69796f7cb30dca7ad8466c2df70058c37116cdee02
3
+ size 244408911
torch_hub/checkpoints/convnext_tiny_1k_224_ema.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:14f3164e3ea6ac32ab3f574f528ce817696c9176fad4221e0a77a905a7360595
3
+ size 114414741
torch_hub/checkpoints/cotracker2.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:362f5274376d610dc987b6daf2c2fefe63e06e1835f4ec1a10d0a15c5a4eef4f
3
+ size 204396415
torch_hub/checkpoints/dino_vitbase16_pretrain.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bf34ad0f424b9029b593e8dc3ed553bf26e88bcba0d32bf3e62a6209cb64c85e
3
+ size 343242485
torch_hub/checkpoints/dinov2_vitb14_reg4_pretrain.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:73182a088cf94833c94b1666d1c99e02fe87e2007bff57b564fb6206e25dba71
3
+ size 346393545
torch_hub/checkpoints/pt_inception-2015-12-05-6726825d.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6726825d0af5f729cebd5821db510b11b1cfad8faad88a03f1befd49fb9129b2
3
+ size 95628359
torch_hub/checkpoints/vgg16-397923af.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:397923af8e79cdbb6a7127f12361acd7a2f83e06b05044ddf496e83de57a5bf0
3
+ size 553433881
torch_hub/checkpoints/weights-inception-2015-12-05-6726825d.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6726825d0af5f729cebd5821db510b11b1cfad8faad88a03f1befd49fb9129b2
3
+ size 95628359
torch_hub/facebookresearch_co-tracker_main/CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to make participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, sex characteristics, gender identity and expression,
9
+ level of experience, education, socio-economic status, nationality, personal
10
+ appearance, race, religion, or sexual identity and orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies within all project spaces, and it also applies when
49
+ an individual is representing the project or its community in public spaces.
50
+ Examples of representing a project or community include using an official
51
+ project e-mail address, posting via an official social media account, or acting
52
+ as an appointed representative at an online or offline event. Representation of
53
+ a project may be further defined and clarified by project maintainers.
54
+
55
+ This Code of Conduct also applies outside the project spaces when there is a
56
+ reasonable belief that an individual's behavior may have a negative impact on
57
+ the project or its community.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported by contacting the project team at <opensource-conduct@fb.com>. All
63
+ complaints will be reviewed and investigated and will result in a response that
64
+ is deemed necessary and appropriate to the circumstances. The project team is
65
+ obligated to maintain confidentiality with regard to the reporter of an incident.
66
+ Further details of specific enforcement policies may be posted separately.
67
+
68
+ Project maintainers who do not follow or enforce the Code of Conduct in good
69
+ faith may face temporary or permanent repercussions as determined by other
70
+ members of the project's leadership.
71
+
72
+ ## Attribution
73
+
74
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
75
+ available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
76
+
77
+ [homepage]: https://www.contributor-covenant.org
78
+
79
+ For answers to common questions about this code of conduct, see
80
+ https://www.contributor-covenant.org/faq
torch_hub/facebookresearch_co-tracker_main/CONTRIBUTING.md ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CoTracker
2
+ We want to make contributing to this project as easy and transparent as possible.
3
+
4
+ ## Pull Requests
5
+ We actively welcome your pull requests.
6
+
7
+ 1. Fork the repo and create your branch from `main`.
8
+ 2. If you've changed APIs, update the documentation.
9
+ 3. Make sure your code lints.
10
+ 4. If you haven't already, complete the Contributor License Agreement ("CLA").
11
+
12
+ ## Contributor License Agreement ("CLA")
13
+ In order to accept your pull request, we need you to submit a CLA. You only need
14
+ to do this once to work on any of Meta's open source projects.
15
+
16
+ Complete your CLA here: <https://code.facebook.com/cla>
17
+
18
+ ## Issues
19
+ We use GitHub issues to track public bugs. Please ensure your description is
20
+ clear and has sufficient instructions to be able to reproduce the issue.
21
+
22
+ Meta has a [bounty program](https://www.facebook.com/whitehat/) for the safe
23
+ disclosure of security bugs. In those cases, please go through the process
24
+ outlined on that page and do not file a public issue.
25
+
26
+ ## License
27
+ By contributing to CoTracker, you agree that your contributions will be licensed
28
+ under the LICENSE file in the root directory of this source tree.
torch_hub/facebookresearch_co-tracker_main/LICENSE.md ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Attribution-NonCommercial 4.0 International
2
+
3
+ =======================================================================
4
+
5
+ Creative Commons Corporation ("Creative Commons") is not a law firm and
6
+ does not provide legal services or legal advice. Distribution of
7
+ Creative Commons public licenses does not create a lawyer-client or
8
+ other relationship. Creative Commons makes its licenses and related
9
+ information available on an "as-is" basis. Creative Commons gives no
10
+ warranties regarding its licenses, any material licensed under their
11
+ terms and conditions, or any related information. Creative Commons
12
+ disclaims all liability for damages resulting from their use to the
13
+ fullest extent possible.
14
+
15
+ Using Creative Commons Public Licenses
16
+
17
+ Creative Commons public licenses provide a standard set of terms and
18
+ conditions that creators and other rights holders may use to share
19
+ original works of authorship and other material subject to copyright
20
+ and certain other rights specified in the public license below. The
21
+ following considerations are for informational purposes only, are not
22
+ exhaustive, and do not form part of our licenses.
23
+
24
+ Considerations for licensors: Our public licenses are
25
+ intended for use by those authorized to give the public
26
+ permission to use material in ways otherwise restricted by
27
+ copyright and certain other rights. Our licenses are
28
+ irrevocable. Licensors should read and understand the terms
29
+ and conditions of the license they choose before applying it.
30
+ Licensors should also secure all rights necessary before
31
+ applying our licenses so that the public can reuse the
32
+ material as expected. Licensors should clearly mark any
33
+ material not subject to the license. This includes other CC-
34
+ licensed material, or material used under an exception or
35
+ limitation to copyright. More considerations for licensors:
36
+ wiki.creativecommons.org/Considerations_for_licensors
37
+
38
+ Considerations for the public: By using one of our public
39
+ licenses, a licensor grants the public permission to use the
40
+ licensed material under specified terms and conditions. If
41
+ the licensor's permission is not necessary for any reason--for
42
+ example, because of any applicable exception or limitation to
43
+ copyright--then that use is not regulated by the license. Our
44
+ licenses grant only permissions under copyright and certain
45
+ other rights that a licensor has authority to grant. Use of
46
+ the licensed material may still be restricted for other
47
+ reasons, including because others have copyright or other
48
+ rights in the material. A licensor may make special requests,
49
+ such as asking that all changes be marked or described.
50
+ Although not required by our licenses, you are encouraged to
51
+ respect those requests where reasonable. More_considerations
52
+ for the public:
53
+ wiki.creativecommons.org/Considerations_for_licensees
54
+
55
+ =======================================================================
56
+
57
+ Creative Commons Attribution-NonCommercial 4.0 International Public
58
+ License
59
+
60
+ By exercising the Licensed Rights (defined below), You accept and agree
61
+ to be bound by the terms and conditions of this Creative Commons
62
+ Attribution-NonCommercial 4.0 International Public License ("Public
63
+ License"). To the extent this Public License may be interpreted as a
64
+ contract, You are granted the Licensed Rights in consideration of Your
65
+ acceptance of these terms and conditions, and the Licensor grants You
66
+ such rights in consideration of benefits the Licensor receives from
67
+ making the Licensed Material available under these terms and
68
+ conditions.
69
+
70
+ Section 1 -- Definitions.
71
+
72
+ a. Adapted Material means material subject to Copyright and Similar
73
+ Rights that is derived from or based upon the Licensed Material
74
+ and in which the Licensed Material is translated, altered,
75
+ arranged, transformed, or otherwise modified in a manner requiring
76
+ permission under the Copyright and Similar Rights held by the
77
+ Licensor. For purposes of this Public License, where the Licensed
78
+ Material is a musical work, performance, or sound recording,
79
+ Adapted Material is always produced where the Licensed Material is
80
+ synched in timed relation with a moving image.
81
+
82
+ b. Adapter's License means the license You apply to Your Copyright
83
+ and Similar Rights in Your contributions to Adapted Material in
84
+ accordance with the terms and conditions of this Public License.
85
+
86
+ c. Copyright and Similar Rights means copyright and/or similar rights
87
+ closely related to copyright including, without limitation,
88
+ performance, broadcast, sound recording, and Sui Generis Database
89
+ Rights, without regard to how the rights are labeled or
90
+ categorized. For purposes of this Public License, the rights
91
+ specified in Section 2(b)(1)-(2) are not Copyright and Similar
92
+ Rights.
93
+ d. Effective Technological Measures means those measures that, in the
94
+ absence of proper authority, may not be circumvented under laws
95
+ fulfilling obligations under Article 11 of the WIPO Copyright
96
+ Treaty adopted on December 20, 1996, and/or similar international
97
+ agreements.
98
+
99
+ e. Exceptions and Limitations means fair use, fair dealing, and/or
100
+ any other exception or limitation to Copyright and Similar Rights
101
+ that applies to Your use of the Licensed Material.
102
+
103
+ f. Licensed Material means the artistic or literary work, database,
104
+ or other material to which the Licensor applied this Public
105
+ License.
106
+
107
+ g. Licensed Rights means the rights granted to You subject to the
108
+ terms and conditions of this Public License, which are limited to
109
+ all Copyright and Similar Rights that apply to Your use of the
110
+ Licensed Material and that the Licensor has authority to license.
111
+
112
+ h. Licensor means the individual(s) or entity(ies) granting rights
113
+ under this Public License.
114
+
115
+ i. NonCommercial means not primarily intended for or directed towards
116
+ commercial advantage or monetary compensation. For purposes of
117
+ this Public License, the exchange of the Licensed Material for
118
+ other material subject to Copyright and Similar Rights by digital
119
+ file-sharing or similar means is NonCommercial provided there is
120
+ no payment of monetary compensation in connection with the
121
+ exchange.
122
+
123
+ j. Share means to provide material to the public by any means or
124
+ process that requires permission under the Licensed Rights, such
125
+ as reproduction, public display, public performance, distribution,
126
+ dissemination, communication, or importation, and to make material
127
+ available to the public including in ways that members of the
128
+ public may access the material from a place and at a time
129
+ individually chosen by them.
130
+
131
+ k. Sui Generis Database Rights means rights other than copyright
132
+ resulting from Directive 96/9/EC of the European Parliament and of
133
+ the Council of 11 March 1996 on the legal protection of databases,
134
+ as amended and/or succeeded, as well as other essentially
135
+ equivalent rights anywhere in the world.
136
+
137
+ l. You means the individual or entity exercising the Licensed Rights
138
+ under this Public License. Your has a corresponding meaning.
139
+
140
+ Section 2 -- Scope.
141
+
142
+ a. License grant.
143
+
144
+ 1. Subject to the terms and conditions of this Public License,
145
+ the Licensor hereby grants You a worldwide, royalty-free,
146
+ non-sublicensable, non-exclusive, irrevocable license to
147
+ exercise the Licensed Rights in the Licensed Material to:
148
+
149
+ a. reproduce and Share the Licensed Material, in whole or
150
+ in part, for NonCommercial purposes only; and
151
+
152
+ b. produce, reproduce, and Share Adapted Material for
153
+ NonCommercial purposes only.
154
+
155
+ 2. Exceptions and Limitations. For the avoidance of doubt, where
156
+ Exceptions and Limitations apply to Your use, this Public
157
+ License does not apply, and You do not need to comply with
158
+ its terms and conditions.
159
+
160
+ 3. Term. The term of this Public License is specified in Section
161
+ 6(a).
162
+
163
+ 4. Media and formats; technical modifications allowed. The
164
+ Licensor authorizes You to exercise the Licensed Rights in
165
+ all media and formats whether now known or hereafter created,
166
+ and to make technical modifications necessary to do so. The
167
+ Licensor waives and/or agrees not to assert any right or
168
+ authority to forbid You from making technical modifications
169
+ necessary to exercise the Licensed Rights, including
170
+ technical modifications necessary to circumvent Effective
171
+ Technological Measures. For purposes of this Public License,
172
+ simply making modifications authorized by this Section 2(a)
173
+ (4) never produces Adapted Material.
174
+
175
+ 5. Downstream recipients.
176
+
177
+ a. Offer from the Licensor -- Licensed Material. Every
178
+ recipient of the Licensed Material automatically
179
+ receives an offer from the Licensor to exercise the
180
+ Licensed Rights under the terms and conditions of this
181
+ Public License.
182
+
183
+ b. No downstream restrictions. You may not offer or impose
184
+ any additional or different terms or conditions on, or
185
+ apply any Effective Technological Measures to, the
186
+ Licensed Material if doing so restricts exercise of the
187
+ Licensed Rights by any recipient of the Licensed
188
+ Material.
189
+
190
+ 6. No endorsement. Nothing in this Public License constitutes or
191
+ may be construed as permission to assert or imply that You
192
+ are, or that Your use of the Licensed Material is, connected
193
+ with, or sponsored, endorsed, or granted official status by,
194
+ the Licensor or others designated to receive attribution as
195
+ provided in Section 3(a)(1)(A)(i).
196
+
197
+ b. Other rights.
198
+
199
+ 1. Moral rights, such as the right of integrity, are not
200
+ licensed under this Public License, nor are publicity,
201
+ privacy, and/or other similar personality rights; however, to
202
+ the extent possible, the Licensor waives and/or agrees not to
203
+ assert any such rights held by the Licensor to the limited
204
+ extent necessary to allow You to exercise the Licensed
205
+ Rights, but not otherwise.
206
+
207
+ 2. Patent and trademark rights are not licensed under this
208
+ Public License.
209
+
210
+ 3. To the extent possible, the Licensor waives any right to
211
+ collect royalties from You for the exercise of the Licensed
212
+ Rights, whether directly or through a collecting society
213
+ under any voluntary or waivable statutory or compulsory
214
+ licensing scheme. In all other cases the Licensor expressly
215
+ reserves any right to collect such royalties, including when
216
+ the Licensed Material is used other than for NonCommercial
217
+ purposes.
218
+
219
+ Section 3 -- License Conditions.
220
+
221
+ Your exercise of the Licensed Rights is expressly made subject to the
222
+ following conditions.
223
+
224
+ a. Attribution.
225
+
226
+ 1. If You Share the Licensed Material (including in modified
227
+ form), You must:
228
+
229
+ a. retain the following if it is supplied by the Licensor
230
+ with the Licensed Material:
231
+
232
+ i. identification of the creator(s) of the Licensed
233
+ Material and any others designated to receive
234
+ attribution, in any reasonable manner requested by
235
+ the Licensor (including by pseudonym if
236
+ designated);
237
+
238
+ ii. a copyright notice;
239
+
240
+ iii. a notice that refers to this Public License;
241
+
242
+ iv. a notice that refers to the disclaimer of
243
+ warranties;
244
+
245
+ v. a URI or hyperlink to the Licensed Material to the
246
+ extent reasonably practicable;
247
+
248
+ b. indicate if You modified the Licensed Material and
249
+ retain an indication of any previous modifications; and
250
+
251
+ c. indicate the Licensed Material is licensed under this
252
+ Public License, and include the text of, or the URI or
253
+ hyperlink to, this Public License.
254
+
255
+ 2. You may satisfy the conditions in Section 3(a)(1) in any
256
+ reasonable manner based on the medium, means, and context in
257
+ which You Share the Licensed Material. For example, it may be
258
+ reasonable to satisfy the conditions by providing a URI or
259
+ hyperlink to a resource that includes the required
260
+ information.
261
+
262
+ 3. If requested by the Licensor, You must remove any of the
263
+ information required by Section 3(a)(1)(A) to the extent
264
+ reasonably practicable.
265
+
266
+ 4. If You Share Adapted Material You produce, the Adapter's
267
+ License You apply must not prevent recipients of the Adapted
268
+ Material from complying with this Public License.
269
+
270
+ Section 4 -- Sui Generis Database Rights.
271
+
272
+ Where the Licensed Rights include Sui Generis Database Rights that
273
+ apply to Your use of the Licensed Material:
274
+
275
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right
276
+ to extract, reuse, reproduce, and Share all or a substantial
277
+ portion of the contents of the database for NonCommercial purposes
278
+ only;
279
+
280
+ b. if You include all or a substantial portion of the database
281
+ contents in a database in which You have Sui Generis Database
282
+ Rights, then the database in which You have Sui Generis Database
283
+ Rights (but not its individual contents) is Adapted Material; and
284
+
285
+ c. You must comply with the conditions in Section 3(a) if You Share
286
+ all or a substantial portion of the contents of the database.
287
+
288
+ For the avoidance of doubt, this Section 4 supplements and does not
289
+ replace Your obligations under this Public License where the Licensed
290
+ Rights include other Copyright and Similar Rights.
291
+
292
+ Section 5 -- Disclaimer of Warranties and Limitation of Liability.
293
+
294
+ a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
295
+ EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
296
+ AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
297
+ ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
298
+ IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
299
+ WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
300
+ PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
301
+ ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
302
+ KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
303
+ ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
304
+
305
+ b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
306
+ TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
307
+ NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
308
+ INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
309
+ COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
310
+ USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
311
+ ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
312
+ DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
313
+ IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
314
+
315
+ c. The disclaimer of warranties and limitation of liability provided
316
+ above shall be interpreted in a manner that, to the extent
317
+ possible, most closely approximates an absolute disclaimer and
318
+ waiver of all liability.
319
+
320
+ Section 6 -- Term and Termination.
321
+
322
+ a. This Public License applies for the term of the Copyright and
323
+ Similar Rights licensed here. However, if You fail to comply with
324
+ this Public License, then Your rights under this Public License
325
+ terminate automatically.
326
+
327
+ b. Where Your right to use the Licensed Material has terminated under
328
+ Section 6(a), it reinstates:
329
+
330
+ 1. automatically as of the date the violation is cured, provided
331
+ it is cured within 30 days of Your discovery of the
332
+ violation; or
333
+
334
+ 2. upon express reinstatement by the Licensor.
335
+
336
+ For the avoidance of doubt, this Section 6(b) does not affect any
337
+ right the Licensor may have to seek remedies for Your violations
338
+ of this Public License.
339
+
340
+ c. For the avoidance of doubt, the Licensor may also offer the
341
+ Licensed Material under separate terms or conditions or stop
342
+ distributing the Licensed Material at any time; however, doing so
343
+ will not terminate this Public License.
344
+
345
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
346
+ License.
347
+
348
+ Section 7 -- Other Terms and Conditions.
349
+
350
+ a. The Licensor shall not be bound by any additional or different
351
+ terms or conditions communicated by You unless expressly agreed.
352
+
353
+ b. Any arrangements, understandings, or agreements regarding the
354
+ Licensed Material not stated herein are separate from and
355
+ independent of the terms and conditions of this Public License.
356
+
357
+ Section 8 -- Interpretation.
358
+
359
+ a. For the avoidance of doubt, this Public License does not, and
360
+ shall not be interpreted to, reduce, limit, restrict, or impose
361
+ conditions on any use of the Licensed Material that could lawfully
362
+ be made without permission under this Public License.
363
+
364
+ b. To the extent possible, if any provision of this Public License is
365
+ deemed unenforceable, it shall be automatically reformed to the
366
+ minimum extent necessary to make it enforceable. If the provision
367
+ cannot be reformed, it shall be severed from this Public License
368
+ without affecting the enforceability of the remaining terms and
369
+ conditions.
370
+
371
+ c. No term or condition of this Public License will be waived and no
372
+ failure to comply consented to unless expressly agreed to by the
373
+ Licensor.
374
+
375
+ d. Nothing in this Public License constitutes or may be interpreted
376
+ as a limitation upon, or waiver of, any privileges and immunities
377
+ that apply to the Licensor or You, including from the legal
378
+ processes of any jurisdiction or authority.
379
+
380
+ =======================================================================
381
+
382
+ Creative Commons is not a party to its public
383
+ licenses. Notwithstanding, Creative Commons may elect to apply one of
384
+ its public licenses to material it publishes and in those instances
385
+ will be considered the “Licensor.” The text of the Creative Commons
386
+ public licenses is dedicated to the public domain under the CC0 Public
387
+ Domain Dedication. Except for the limited purpose of indicating that
388
+ material is shared under a Creative Commons public license or as
389
+ otherwise permitted by the Creative Commons policies published at
390
+ creativecommons.org/policies, Creative Commons does not authorize the
391
+ use of the trademark "Creative Commons" or any other trademark or logo
392
+ of Creative Commons without its prior written consent including,
393
+ without limitation, in connection with any unauthorized modifications
394
+ to any of its public licenses or any other arrangements,
395
+ understandings, or agreements concerning use of licensed material. For
396
+ the avoidance of doubt, this paragraph does not form part of the
397
+ public licenses.
398
+
399
+ Creative Commons may be contacted at creativecommons.org.
torch_hub/facebookresearch_co-tracker_main/README.md ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CoTracker3: Simpler and Better Point Tracking by Pseudo-Labelling Real Videos
2
+
3
+ **[Meta AI Research, GenAI](https://ai.facebook.com/research/)**; **[University of Oxford, VGG](https://www.robots.ox.ac.uk/~vgg/)**
4
+
5
+ [Nikita Karaev](https://nikitakaraevv.github.io/), [Iurii Makarov](https://linkedin.com/in/lvoursl), [Jianyuan Wang](https://jytime.github.io/), [Ignacio Rocco](https://www.irocco.info/), [Benjamin Graham](https://ai.facebook.com/people/benjamin-graham/), [Natalia Neverova](https://nneverova.github.io/), [Andrea Vedaldi](https://www.robots.ox.ac.uk/~vedaldi/), [Christian Rupprecht](https://chrirupp.github.io/)
6
+
7
+ ### [Project Page](https://cotracker3.github.io/) | [Paper #1](https://arxiv.org/abs/2307.07635) | [Paper #2](https://arxiv.org/abs/2410.11831) | [X Thread](https://twitter.com/n_karaev/status/1742638906355470772) | [BibTeX](#citing-cotracker)
8
+
9
+ <a target="_blank" href="https://colab.research.google.com/github/facebookresearch/co-tracker/blob/main/notebooks/demo.ipynb">
10
+ <img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/>
11
+ </a>
12
+ <a href="https://huggingface.co/spaces/facebook/cotracker">
13
+ <img alt="Spaces" src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue">
14
+ </a>
15
+
16
+ <img width="1100" src="./assets/teaser.png" />
17
+
18
+ **CoTracker** is a fast transformer-based model that can track any point in a video. It brings to tracking some of the benefits of Optical Flow.
19
+
20
+ CoTracker can track:
21
+
22
+ - **Any pixel** in a video
23
+ - A **quasi-dense** set of pixels together
24
+ - Points can be manually selected or sampled on a grid in any video frame
25
+
26
+ Try these tracking modes for yourself with our [Colab demo](https://colab.research.google.com/github/facebookresearch/co-tracker/blob/master/notebooks/demo.ipynb) or in the [Hugging Face Space 🤗](https://huggingface.co/spaces/facebook/cotracker).
27
+
28
+ **Updates:**
29
+
30
+ - [January 21, 2025] 📦 Kubric Dataset used for CoTracker3 now available! This dataset contains **6,000 high-resolution sequences** (512×512px, 120 frames) with slight camera motion, rendered using the Kubric engine. Check it out on [Hugging Face Dataset](https://huggingface.co/datasets/facebook/CoTracker3_Kubric).
31
+
32
+ - [October 15, 2024] 📣 We're releasing CoTracker3! State-of-the-art point tracking with a lightweight architecture trained with 1000x less data than previous top-performing models. Code for baseline models and the pseudo-labeling pipeline are available in the repo, as well as model checkpoints. Check out our [paper](https://arxiv.org/abs/2410.11831) for more details.
33
+
34
+ - [September 25, 2024] CoTracker2.1 is now available! This model has better performance on TAP-Vid benchmarks and follows the architecture of the original CoTracker. Try it out!
35
+
36
+ - [June 14, 2024] We have released the code for [VGGSfM](https://github.com/facebookresearch/vggsfm), a model for recovering camera poses and 3D structure from any image sequences based on point tracking! VGGSfM is the first fully differentiable SfM framework that unlocks scalability and outperforms conventional SfM methods on standard benchmarks.
37
+
38
+ - [December 27, 2023] CoTracker2 is now available! It can now track many more (up to **265*265**!) points jointly and it has a cleaner and more memory-efficient implementation. It also supports online processing. See the [updated paper](https://arxiv.org/abs/2307.07635) for more details. The old version remains available [here](https://github.com/facebookresearch/co-tracker/tree/8d364031971f6b3efec945dd15c468a183e58212).
39
+
40
+ - [September 5, 2023] You can now run our Gradio demo [locally](./gradio_demo/app.py).
41
+
42
+ ## Quick start
43
+ The easiest way to use CoTracker is to load a pretrained model from `torch.hub`:
44
+
45
+ ### Offline mode:
46
+ ```pip install imageio[ffmpeg]```, then:
47
+ ```python
48
+ import torch
49
+ # Download the video
50
+ url = 'https://github.com/facebookresearch/co-tracker/raw/refs/heads/main/assets/apple.mp4'
51
+
52
+ import imageio.v3 as iio
53
+ frames = iio.imread(url, plugin="FFMPEG") # plugin="pyav"
54
+
55
+ device = 'cuda'
56
+ grid_size = 10
57
+ video = torch.tensor(frames).permute(0, 3, 1, 2)[None].float().to(device) # B T C H W
58
+
59
+ # Run Offline CoTracker:
60
+ cotracker = torch.hub.load("facebookresearch/co-tracker", "cotracker3_offline").to(device)
61
+ pred_tracks, pred_visibility = cotracker(video, grid_size=grid_size) # B T N 2, B T N 1
62
+ ```
63
+ ### Online mode:
64
+ ```python
65
+ cotracker = torch.hub.load("facebookresearch/co-tracker", "cotracker3_online").to(device)
66
+
67
+ # Run Online CoTracker, the same model with a different API:
68
+ # Initialize online processing
69
+ cotracker(video_chunk=video, is_first_step=True, grid_size=grid_size)
70
+
71
+ # Process the video
72
+ for ind in range(0, video.shape[1] - cotracker.step, cotracker.step):
73
+ pred_tracks, pred_visibility = cotracker(
74
+ video_chunk=video[:, ind : ind + cotracker.step * 2]
75
+ ) # B T N 2, B T N 1
76
+ ```
77
+ Online processing is more memory-efficient and allows for the processing of longer videos. However, in the example provided above, the video length is known! See [the online demo](./online_demo.py) for an example of tracking from an online stream with an unknown video length.
78
+
79
+ ### Visualize predicted tracks:
80
+ After [installing](#installation-instructions) CoTracker, you can visualize tracks with:
81
+ ```python
82
+ from cotracker.utils.visualizer import Visualizer
83
+
84
+ vis = Visualizer(save_dir="./saved_videos", pad_value=120, linewidth=3)
85
+ vis.visualize(video, pred_tracks, pred_visibility)
86
+ ```
87
+
88
+ We offer a number of other ways to interact with CoTracker:
89
+
90
+ 1. Interactive Gradio demo:
91
+ - A demo is available in the [`facebook/cotracker` Hugging Face Space 🤗](https://huggingface.co/spaces/facebook/cotracker).
92
+ - You can use the gradio demo locally by running [`python -m gradio_demo.app`](./gradio_demo/app.py) after installing the required packages: `pip install -r gradio_demo/requirements.txt`.
93
+ 2. Jupyter notebook:
94
+ - You can run the notebook in
95
+ [Google Colab](https://colab.research.google.com/github/facebookresearch/co-tracker/blob/master/notebooks/demo.ipynb).
96
+ - Or explore the notebook located at [`notebooks/demo.ipynb`](./notebooks/demo.ipynb).
97
+ 2. You can [install](#installation-instructions) CoTracker _locally_ and then:
98
+ - Run an *offline* demo with 10 ⨉ 10 points sampled on a grid on the first frame of a video (results will be saved to `./saved_videos/demo.mp4`)):
99
+
100
+ ```bash
101
+ python demo.py --grid_size 10
102
+ ```
103
+ - Run an *online* demo:
104
+
105
+ ```bash
106
+ python online_demo.py
107
+ ```
108
+
109
+ A GPU is strongly recommended for using CoTracker locally.
110
+
111
+ <img width="500" src="./assets/bmx-bumps.gif" />
112
+
113
+
114
+ ## Installation Instructions
115
+ You can use a Pretrained Model via PyTorch Hub, as described above, or install CoTracker from this GitHub repo.
116
+ This is the best way if you need to run our local demo or evaluate/train CoTracker.
117
+
118
+ Ensure you have both _PyTorch_ and _TorchVision_ installed on your system. Follow the instructions [here](https://pytorch.org/get-started/locally/) for the installation.
119
+ We strongly recommend installing both PyTorch and TorchVision with CUDA support, although for small tasks CoTracker can be run on CPU.
120
+
121
+
122
+
123
+
124
+ ### Install a Development Version
125
+
126
+ ```bash
127
+ git clone https://github.com/facebookresearch/co-tracker
128
+ cd co-tracker
129
+ pip install -e .
130
+ pip install matplotlib flow_vis tqdm tensorboard
131
+ ```
132
+
133
+ You can manually download all CoTracker3 checkpoints (baseline and scaled models, as well as single and sliding window architectures) from the links below and place them in the `checkpoints` folder as follows:
134
+
135
+ ```bash
136
+ mkdir -p checkpoints
137
+ cd checkpoints
138
+ # download the online (multi window) model
139
+ wget https://huggingface.co/facebook/cotracker3/resolve/main/scaled_online.pth
140
+ # download the offline (single window) model
141
+ wget https://huggingface.co/facebook/cotracker3/resolve/main/scaled_offline.pth
142
+ cd ..
143
+ ```
144
+ You can also download CoTracker3 checkpoints trained only on Kubric:
145
+ ```bash
146
+ # download the online (sliding window) model
147
+ wget https://huggingface.co/facebook/cotracker3/resolve/main/baseline_online.pth
148
+ # download the offline (single window) model
149
+ wget https://huggingface.co/facebook/cotracker3/resolve/main/baseline_offline.pth
150
+ ```
151
+ For old checkpoints, see [this section](#previous-version).
152
+
153
+ ## Evaluation
154
+
155
+ To reproduce the results presented in the paper, download the following datasets:
156
+
157
+ - [TAP-Vid](https://github.com/deepmind/tapnet)
158
+ - [Dynamic Replica](https://dynamic-stereo.github.io/)
159
+
160
+ And install the necessary dependencies:
161
+
162
+ ```bash
163
+ pip install hydra-core==1.1.0 mediapy
164
+ ```
165
+
166
+ Then, execute the following command to evaluate the online model on TAP-Vid DAVIS:
167
+
168
+ ```bash
169
+ python ./cotracker/evaluation/evaluate.py --config-name eval_tapvid_davis_first exp_dir=./eval_outputs dataset_root=your/tapvid/path
170
+ ```
171
+ And the offline model:
172
+ ```bash
173
+ python ./cotracker/evaluation/evaluate.py --config-name eval_tapvid_davis_first exp_dir=./eval_outputs dataset_root=/fsx-repligen/shared/datasets/tapvid offline_model=True window_len=60 checkpoint=./checkpoints/scaled_offline.pth
174
+ ```
175
+ We run evaluations jointly on all the target points at a time for faster inference. With such evaluations, the numbers are similar to those presented in the paper. If you want to reproduce the exact numbers from the paper, add the flag `single_point=True`.
176
+
177
+ These are the numbers that you should be able to reproduce using the released checkpoint and the current version of the codebase:
178
+ | | Kinetics, $\delta_\text{avg}^\text{vis}$ | DAVIS, $\delta_\text{avg}^\text{vis}$ | RoboTAP, $\delta_\text{avg}^\text{vis}$ | RGB-S, $\delta_\text{avg}^\text{vis}$|
179
+ | :---: |:---: | :---: | :---: | :---: |
180
+ | CoTracker2, 27.12.23 | 61.8 | 74.6 | 69.6 | 73.4 |
181
+ | CoTracker2.1, 25.09.24 | 63 | 76.1 | 70.6 | 79.6 |
182
+ | CoTracker3 offline, 15.10.24 | 67.8 | **76.9** | 78.0 | **85.0** |
183
+ | CoTracker3 online, 15.10.24 | **68.3** | 76.7 | **78.8** | 82.7 |
184
+
185
+
186
+ ## Training
187
+
188
+ ### Baseline
189
+ To train the CoTracker as described in our paper, you first need to generate annotations for [Google Kubric](https://github.com/google-research/kubric) MOVI-f dataset.
190
+ Instructions for annotation generation can be found [here](https://github.com/deepmind/tapnet).
191
+ You can also find a discussion on dataset generation in [this issue](https://github.com/facebookresearch/co-tracker/issues/8).
192
+
193
+ Once you have the annotated dataset, you need to make sure you followed the steps for evaluation setup and install the training dependencies:
194
+
195
+ ```bash
196
+ pip install pip==24.0
197
+ pip install pytorch_lightning==1.6.0 tensorboard opencv-python
198
+ ```
199
+
200
+ Now you can launch training on Kubric.
201
+ Our model was trained for 50000 iterations on 32 GPUs (4 nodes with 8 GPUs).
202
+ Modify _dataset_root_ and _ckpt_path_ accordingly before running this command. For training on 4 nodes, add `--num_nodes 4`.
203
+
204
+ Here is an example of how to launch training of the online model on Kubric:
205
+ ```bash
206
+ python train_on_kubric.py --batch_size 1 --num_steps 50000 \
207
+ --ckpt_path ./ --model_name cotracker_three --save_freq 200 --sequence_len 64 \
208
+ --eval_datasets tapvid_davis_first tapvid_stacking --traj_per_sample 384 \
209
+ --sliding_window_len 16 --train_datasets kubric --save_every_n_epoch 5 \
210
+ --evaluate_every_n_epoch 5 --model_stride 4 --dataset_root ${path_to_your_dataset} \
211
+ --num_nodes 4 --num_virtual_tracks 64 --mixed_precision --corr_radius 3 \
212
+ --wdecay 0.0005 --linear_layer_for_vis_conf --validate_at_start --add_huber_loss
213
+ ```
214
+
215
+ Training the offline model on Kubric:
216
+ ```bash
217
+ python train_on_kubric.py --batch_size 1 --num_steps 50000 \
218
+ --ckpt_path ./ --model_name cotracker_three --save_freq 200 --sequence_len 60 \
219
+ --eval_datasets tapvid_davis_first tapvid_stacking --traj_per_sample 512 \
220
+ --sliding_window_len 60 --train_datasets kubric --save_every_n_epoch 5 \
221
+ --evaluate_every_n_epoch 5 --model_stride 4 --dataset_root ${path_to_your_dataset} \
222
+ --num_nodes 4 --num_virtual_tracks 64 --mixed_precision --offline_model \
223
+ --random_frame_rate --query_sampling_method random --corr_radius 3 \
224
+ --wdecay 0.0005 --random_seq_len --linear_layer_for_vis_conf \
225
+ --validate_at_start --add_huber_loss
226
+ ```
227
+
228
+ ### Fine-tuning with pseudo labels
229
+ In order to launch training with pseudo-labelling, you need to collect your own dataset of real videos. There is a sample class available in [`cotracker/datasets/real_dataset.py`](./cotracker/datasets/real_dataset.py) with keyword-based filtering that we used for training. Your class should implement loading a video and storing it in the `CoTrackerData` class as a field, while pseudo labels will be generated in `train_on_real_data.py`.
230
+
231
+ You should have an existing Kubric-trained model for fine-tuning with pseudo labels. Here is an example of how you can launch fine-tuning of the online model:
232
+ ```bash
233
+ python ./train_on_real_data.py --batch_size 1 --num_steps 15000 \
234
+ --ckpt_path ./ --model_name cotracker_three --save_freq 200 --sequence_len 64 \
235
+ --eval_datasets tapvid_stacking tapvid_davis_first --traj_per_sample 384 \
236
+ --save_every_n_epoch 15 --evaluate_every_n_epoch 15 --model_stride 4 \
237
+ --dataset_root ${path_to_your_dataset} --num_nodes 4 --real_data_splits 0 \
238
+ --num_virtual_tracks 64 --mixed_precision --random_frame_rate \
239
+ --restore_ckpt ./checkpoints/baseline_online.pth \
240
+ --lr 0.00005 --real_data_filter_sift --validate_at_start \
241
+ --sliding_window_len 16 --limit_samples 15000
242
+
243
+ ```
244
+ And the offline model:
245
+ ```bash
246
+ python train_on_real_data.py --batch_size 1 --num_steps 15000 \
247
+ --ckpt_path ./ --model_name cotracker_three --save_freq 200 --sequence_len 80 \
248
+ --eval_datasets tapvid_stacking tapvid_davis_first --traj_per_sample 384 --save_every_n_epoch 15 \
249
+ --evaluate_every_n_epoch 15 --model_stride 4 --dataset_root ${path_to_your_dataset} \
250
+ --num_nodes 4 --real_data_splits 0 --num_virtual_tracks 64 --mixed_precision \
251
+ --random_frame_rate --restore_ckpt ./checkpoints/baseline_offline.pth --lr 0.00005 \
252
+ --real_data_filter_sift --validate_at_start --offline_model --limit_samples 15000
253
+ ```
254
+
255
+
256
+
257
+ ## Development
258
+
259
+ ### Building the documentation
260
+
261
+ To build CoTracker documentation, first install the dependencies:
262
+
263
+ ```bash
264
+ pip install sphinx
265
+ pip install sphinxcontrib-bibtex
266
+ ```
267
+
268
+ Then you can use this command to generate the documentation in the `docs/_build/html` folder:
269
+
270
+ ```bash
271
+ make -C docs html
272
+ ```
273
+
274
+
275
+ ## Previous versions
276
+ ### CoTracker v2
277
+ You could use CoTracker v2 with torch.hub in both offline and online modes.
278
+ #### Offline mode:
279
+ ```pip install imageio[ffmpeg]```, then:
280
+ ```python
281
+ import torch
282
+ # Download the video
283
+ url = 'https://github.com/facebookresearch/co-tracker/blob/main/assets/apple.mp4'
284
+
285
+ import imageio.v3 as iio
286
+ frames = iio.imread(url, plugin="FFMPEG") # plugin="pyav"
287
+
288
+ device = 'cuda'
289
+ grid_size = 10
290
+ video = torch.tensor(frames).permute(0, 3, 1, 2)[None].float().to(device) # B T C H W
291
+
292
+ # Run Offline CoTracker:
293
+ cotracker = torch.hub.load("facebookresearch/co-tracker", "cotracker2").to(device)
294
+ pred_tracks, pred_visibility = cotracker(video, grid_size=grid_size) # B T N 2, B T N 1
295
+ ```
296
+ #### Online mode:
297
+ ```python
298
+ cotracker = torch.hub.load("facebookresearch/co-tracker", "cotracker2_online").to(device)
299
+
300
+ # Run Online CoTracker, the same model with a different API:
301
+ # Initialize online processing
302
+ cotracker(video_chunk=video, is_first_step=True, grid_size=grid_size)
303
+
304
+ # Process the video
305
+ for ind in range(0, video.shape[1] - cotracker.step, cotracker.step):
306
+ pred_tracks, pred_visibility = cotracker(
307
+ video_chunk=video[:, ind : ind + cotracker.step * 2]
308
+ ) # B T N 2, B T N 1
309
+ ```
310
+
311
+ Checkpoint for v2 could be downloaded with the following command:
312
+ ```bash
313
+ wget https://huggingface.co/facebook/cotracker/resolve/main/cotracker2.pth
314
+ ```
315
+
316
+ ### CoTracker v1
317
+ It is directly available via pytorch hub:
318
+ ```python
319
+ import torch
320
+ import einops
321
+ import timm
322
+ import tqdm
323
+
324
+ cotracker = torch.hub.load("facebookresearch/co-tracker:v1.0", "cotracker_w8")
325
+ ```
326
+ The old version of the code is available [here](https://github.com/facebookresearch/co-tracker/tree/8d364031971f6b3efec945dd15c468a183e58212).
327
+ You can also download the corresponding checkpoints:
328
+ ```bash
329
+ wget https://dl.fbaipublicfiles.com/cotracker/cotracker_stride_4_wind_8.pth
330
+ wget https://dl.fbaipublicfiles.com/cotracker/cotracker_stride_4_wind_12.pth
331
+ wget https://dl.fbaipublicfiles.com/cotracker/cotracker_stride_8_wind_16.pth
332
+ ```
333
+
334
+ ## License
335
+
336
+ The majority of CoTracker is licensed under CC-BY-NC, however portions of the project are available under separate license terms: Particle Video Revisited is licensed under the MIT license, TAP-Vid and LocoTrack are licensed under the Apache 2.0 license.
337
+
338
+ ## Acknowledgments
339
+
340
+ We would like to thank [PIPs](https://github.com/aharley/pips), [TAP-Vid](https://github.com/deepmind/tapnet), [LocoTrack](https://github.com/cvlab-kaist/locotrack) for publicly releasing their code and data. We also want to thank [Luke Melas-Kyriazi](https://lukemelas.github.io/) for proofreading the paper, [Jianyuan Wang](https://jytime.github.io/), [Roman Shapovalov](https://shapovalov.ro/) and [Adam W. Harley](https://adamharley.com/) for the insightful discussions.
341
+
342
+ ## Citing CoTracker
343
+
344
+ If you find our repository useful, please consider giving it a star ⭐ and citing our research papers in your work:
345
+ ```bibtex
346
+ @inproceedings{karaev23cotracker,
347
+ title = {CoTracker: It is Better to Track Together},
348
+ author = {Nikita Karaev and Ignacio Rocco and Benjamin Graham and Natalia Neverova and Andrea Vedaldi and Christian Rupprecht},
349
+ booktitle = {Proc. {ECCV}},
350
+ year = {2024}
351
+ }
352
+ ```
353
+ ```bibtex
354
+ @inproceedings{karaev24cotracker3,
355
+ title = {CoTracker3: Simpler and Better Point Tracking by Pseudo-Labelling Real Videos},
356
+ author = {Nikita Karaev and Iurii Makarov and Jianyuan Wang and Natalia Neverova and Andrea Vedaldi and Christian Rupprecht},
357
+ booktitle = {Proc. {arXiv:2410.11831}},
358
+ year = {2024}
359
+ }
360
+ ```
torch_hub/facebookresearch_co-tracker_main/__pycache__/hubconf.cpython-310.pyc ADDED
Binary file (2.82 kB). View file
 
torch_hub/facebookresearch_co-tracker_main/assets/apple.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c7f48c5cfb1479e1dbc1df2373d5cad4f55c198bbdb379da0ece10087971542a
3
+ size 1219872
torch_hub/facebookresearch_co-tracker_main/assets/apple_mask.png ADDED
torch_hub/facebookresearch_co-tracker_main/assets/bmx-bumps.gif ADDED

Git LFS Details

  • SHA256: c96947f7db09bb39e9e2c365fdb34ff27860234fe8044fc07f271ba521f503ba
  • Pointer size: 132 Bytes
  • Size of remote file: 7.67 MB
torch_hub/facebookresearch_co-tracker_main/assets/teaser.png ADDED

Git LFS Details

  • SHA256: 1037b7035a9507bbb3a4afc120742cc2d1eb516f033d2a77bfbcb3501c4ccae7
  • Pointer size: 132 Bytes
  • Size of remote file: 6.03 MB
torch_hub/facebookresearch_co-tracker_main/cotracker/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
torch_hub/facebookresearch_co-tracker_main/cotracker/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (170 Bytes). View file
 
torch_hub/facebookresearch_co-tracker_main/cotracker/__pycache__/predictor.cpython-310.pyc ADDED
Binary file (6.57 kB). View file
 
torch_hub/facebookresearch_co-tracker_main/cotracker/datasets/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
torch_hub/facebookresearch_co-tracker_main/cotracker/datasets/dataclass_utils.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+
8
+ import json
9
+ import dataclasses
10
+ import numpy as np
11
+ from dataclasses import Field, MISSING
12
+ from typing import IO, TypeVar, Type, get_args, get_origin, Union, Any, Tuple
13
+
14
+ _X = TypeVar("_X")
15
+
16
+
17
+ def load_dataclass(f: IO, cls: Type[_X], binary: bool = False) -> _X:
18
+ """
19
+ Loads to a @dataclass or collection hierarchy including dataclasses
20
+ from a json recursively.
21
+ Call it like load_dataclass(f, typing.List[FrameAnnotationAnnotation]).
22
+ raises KeyError if json has keys not mapping to the dataclass fields.
23
+
24
+ Args:
25
+ f: Either a path to a file, or a file opened for writing.
26
+ cls: The class of the loaded dataclass.
27
+ binary: Set to True if `f` is a file handle, else False.
28
+ """
29
+ if binary:
30
+ asdict = json.loads(f.read().decode("utf8"))
31
+ else:
32
+ asdict = json.load(f)
33
+
34
+ # in the list case, run a faster "vectorized" version
35
+ cls = get_args(cls)[0]
36
+ res = list(_dataclass_list_from_dict_list(asdict, cls))
37
+
38
+ return res
39
+
40
+
41
+ def _resolve_optional(type_: Any) -> Tuple[bool, Any]:
42
+ """Check whether `type_` is equivalent to `typing.Optional[T]` for some T."""
43
+ if get_origin(type_) is Union:
44
+ args = get_args(type_)
45
+ if len(args) == 2 and args[1] == type(None): # noqa E721
46
+ return True, args[0]
47
+ if type_ is Any:
48
+ return True, Any
49
+
50
+ return False, type_
51
+
52
+
53
+ def _unwrap_type(tp):
54
+ # strips Optional wrapper, if any
55
+ if get_origin(tp) is Union:
56
+ args = get_args(tp)
57
+ if len(args) == 2 and any(a is type(None) for a in args): # noqa: E721
58
+ # this is typing.Optional
59
+ return args[0] if args[1] is type(None) else args[1] # noqa: E721
60
+ return tp
61
+
62
+
63
+ def _get_dataclass_field_default(field: Field) -> Any:
64
+ if field.default_factory is not MISSING:
65
+ # pyre-fixme[29]: `Union[dataclasses._MISSING_TYPE,
66
+ # dataclasses._DefaultFactory[typing.Any]]` is not a function.
67
+ return field.default_factory()
68
+ elif field.default is not MISSING:
69
+ return field.default
70
+ else:
71
+ return None
72
+
73
+
74
+ def _dataclass_list_from_dict_list(dlist, typeannot):
75
+ """
76
+ Vectorised version of `_dataclass_from_dict`.
77
+ The output should be equivalent to
78
+ `[_dataclass_from_dict(d, typeannot) for d in dlist]`.
79
+
80
+ Args:
81
+ dlist: list of objects to convert.
82
+ typeannot: type of each of those objects.
83
+ Returns:
84
+ iterator or list over converted objects of the same length as `dlist`.
85
+
86
+ Raises:
87
+ ValueError: it assumes the objects have None's in consistent places across
88
+ objects, otherwise it would ignore some values. This generally holds for
89
+ auto-generated annotations, but otherwise use `_dataclass_from_dict`.
90
+ """
91
+
92
+ cls = get_origin(typeannot) or typeannot
93
+
94
+ if typeannot is Any:
95
+ return dlist
96
+ if all(obj is None for obj in dlist): # 1st recursion base: all None nodes
97
+ return dlist
98
+ if any(obj is None for obj in dlist):
99
+ # filter out Nones and recurse on the resulting list
100
+ idx_notnone = [(i, obj) for i, obj in enumerate(dlist) if obj is not None]
101
+ idx, notnone = zip(*idx_notnone)
102
+ converted = _dataclass_list_from_dict_list(notnone, typeannot)
103
+ res = [None] * len(dlist)
104
+ for i, obj in zip(idx, converted):
105
+ res[i] = obj
106
+ return res
107
+
108
+ is_optional, contained_type = _resolve_optional(typeannot)
109
+ if is_optional:
110
+ return _dataclass_list_from_dict_list(dlist, contained_type)
111
+
112
+ # otherwise, we dispatch by the type of the provided annotation to convert to
113
+ if issubclass(cls, tuple) and hasattr(cls, "_fields"): # namedtuple
114
+ # For namedtuple, call the function recursively on the lists of corresponding keys
115
+ types = cls.__annotations__.values()
116
+ dlist_T = zip(*dlist)
117
+ res_T = [
118
+ _dataclass_list_from_dict_list(key_list, tp)
119
+ for key_list, tp in zip(dlist_T, types)
120
+ ]
121
+ return [cls(*converted_as_tuple) for converted_as_tuple in zip(*res_T)]
122
+ elif issubclass(cls, (list, tuple)):
123
+ # For list/tuple, call the function recursively on the lists of corresponding positions
124
+ types = get_args(typeannot)
125
+ if len(types) == 1: # probably List; replicate for all items
126
+ types = types * len(dlist[0])
127
+ dlist_T = zip(*dlist)
128
+ res_T = (
129
+ _dataclass_list_from_dict_list(pos_list, tp)
130
+ for pos_list, tp in zip(dlist_T, types)
131
+ )
132
+ if issubclass(cls, tuple):
133
+ return list(zip(*res_T))
134
+ else:
135
+ return [cls(converted_as_tuple) for converted_as_tuple in zip(*res_T)]
136
+ elif issubclass(cls, dict):
137
+ # For the dictionary, call the function recursively on concatenated keys and vertices
138
+ key_t, val_t = get_args(typeannot)
139
+ all_keys_res = _dataclass_list_from_dict_list(
140
+ [k for obj in dlist for k in obj.keys()], key_t
141
+ )
142
+ all_vals_res = _dataclass_list_from_dict_list(
143
+ [k for obj in dlist for k in obj.values()], val_t
144
+ )
145
+ indices = np.cumsum([len(obj) for obj in dlist])
146
+ assert indices[-1] == len(all_keys_res)
147
+
148
+ keys = np.split(list(all_keys_res), indices[:-1])
149
+ all_vals_res_iter = iter(all_vals_res)
150
+ return [cls(zip(k, all_vals_res_iter)) for k in keys]
151
+ elif not dataclasses.is_dataclass(typeannot):
152
+ return dlist
153
+
154
+ # dataclass node: 2nd recursion base; call the function recursively on the lists
155
+ # of the corresponding fields
156
+ assert dataclasses.is_dataclass(cls)
157
+ fieldtypes = {
158
+ f.name: (_unwrap_type(f.type), _get_dataclass_field_default(f))
159
+ for f in dataclasses.fields(typeannot)
160
+ }
161
+
162
+ # NOTE the default object is shared here
163
+ key_lists = (
164
+ _dataclass_list_from_dict_list([obj.get(k, default) for obj in dlist], type_)
165
+ for k, (type_, default) in fieldtypes.items()
166
+ )
167
+ transposed = zip(*key_lists)
168
+ return [cls(*vals_as_tuple) for vals_as_tuple in transposed]
torch_hub/facebookresearch_co-tracker_main/cotracker/datasets/dr_dataset.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+
8
+ import os
9
+ import gzip
10
+ import torch
11
+ import numpy as np
12
+ import torch.utils.data as data
13
+ from collections import defaultdict
14
+ from dataclasses import dataclass
15
+ from typing import List, Optional, Any, Dict, Tuple
16
+
17
+ from cotracker.datasets.utils import CoTrackerData
18
+ from cotracker.datasets.dataclass_utils import load_dataclass
19
+
20
+
21
+ @dataclass
22
+ class ImageAnnotation:
23
+ # path to jpg file, relative w.r.t. dataset_root
24
+ path: str
25
+ # H x W
26
+ size: Tuple[int, int]
27
+
28
+
29
+ @dataclass
30
+ class DynamicReplicaFrameAnnotation:
31
+ """A dataclass used to load annotations from json."""
32
+
33
+ # can be used to join with `SequenceAnnotation`
34
+ sequence_name: str
35
+ # 0-based, continuous frame number within sequence
36
+ frame_number: int
37
+ # timestamp in seconds from the video start
38
+ frame_timestamp: float
39
+
40
+ image: ImageAnnotation
41
+ meta: Optional[Dict[str, Any]] = None
42
+
43
+ camera_name: Optional[str] = None
44
+ trajectories: Optional[str] = None
45
+
46
+
47
+ class DynamicReplicaDataset(data.Dataset):
48
+ def __init__(
49
+ self,
50
+ root,
51
+ split="valid",
52
+ traj_per_sample=256,
53
+ crop_size=None,
54
+ sample_len=-1,
55
+ only_first_n_samples=-1,
56
+ rgbd_input=False,
57
+ ):
58
+ super(DynamicReplicaDataset, self).__init__()
59
+ self.root = root
60
+ self.sample_len = sample_len
61
+ self.split = split
62
+ self.traj_per_sample = traj_per_sample
63
+ self.rgbd_input = rgbd_input
64
+ self.crop_size = crop_size
65
+ frame_annotations_file = f"frame_annotations_{split}.jgz"
66
+ self.sample_list = []
67
+ with gzip.open(
68
+ os.path.join(root, split, frame_annotations_file), "rt", encoding="utf8"
69
+ ) as zipfile:
70
+ frame_annots_list = load_dataclass(
71
+ zipfile, List[DynamicReplicaFrameAnnotation]
72
+ )
73
+ seq_annot = defaultdict(list)
74
+ for frame_annot in frame_annots_list:
75
+ if frame_annot.camera_name == "left":
76
+ seq_annot[frame_annot.sequence_name].append(frame_annot)
77
+
78
+ for seq_name in seq_annot.keys():
79
+ seq_len = len(seq_annot[seq_name])
80
+
81
+ step = self.sample_len if self.sample_len > 0 else seq_len
82
+ counter = 0
83
+
84
+ for ref_idx in range(0, seq_len, step):
85
+ sample = seq_annot[seq_name][ref_idx : ref_idx + step]
86
+ self.sample_list.append(sample)
87
+ counter += 1
88
+ if only_first_n_samples > 0 and counter >= only_first_n_samples:
89
+ break
90
+
91
+ def __len__(self):
92
+ return len(self.sample_list)
93
+
94
+ def crop(self, rgbs, trajs):
95
+ T, N, _ = trajs.shape
96
+
97
+ S = len(rgbs)
98
+ H, W = rgbs[0].shape[:2]
99
+ assert S == T
100
+
101
+ H_new = H
102
+ W_new = W
103
+
104
+ # simple random crop
105
+ y0 = 0 if self.crop_size[0] >= H_new else (H_new - self.crop_size[0]) // 2
106
+ x0 = 0 if self.crop_size[1] >= W_new else (W_new - self.crop_size[1]) // 2
107
+ rgbs = [
108
+ rgb[y0 : y0 + self.crop_size[0], x0 : x0 + self.crop_size[1]]
109
+ for rgb in rgbs
110
+ ]
111
+
112
+ trajs[:, :, 0] -= x0
113
+ trajs[:, :, 1] -= y0
114
+
115
+ return rgbs, trajs
116
+
117
+ def __getitem__(self, index):
118
+ sample = self.sample_list[index]
119
+ T = len(sample)
120
+ rgbs, visibilities, traj_2d = [], [], []
121
+
122
+ H, W = sample[0].image.size
123
+ image_size = (H, W)
124
+
125
+ for i in range(T):
126
+ traj_path = os.path.join(
127
+ self.root, self.split, sample[i].trajectories["path"]
128
+ )
129
+ traj = torch.load(traj_path)
130
+
131
+ visibilities.append(traj["verts_inds_vis"].numpy())
132
+
133
+ rgbs.append(traj["img"].numpy())
134
+ traj_2d.append(traj["traj_2d"].numpy()[..., :2])
135
+
136
+ traj_2d = np.stack(traj_2d)
137
+ visibility = np.stack(visibilities)
138
+ T, N, D = traj_2d.shape
139
+ # subsample trajectories for augmentations
140
+ visible_inds_sampled = torch.randperm(N)[: self.traj_per_sample]
141
+
142
+ traj_2d = traj_2d[:, visible_inds_sampled]
143
+ visibility = visibility[:, visible_inds_sampled]
144
+
145
+ if self.crop_size is not None:
146
+ rgbs, traj_2d = self.crop(rgbs, traj_2d)
147
+ H, W, _ = rgbs[0].shape
148
+ image_size = self.crop_size
149
+
150
+ visibility[traj_2d[:, :, 0] > image_size[1] - 1] = False
151
+ visibility[traj_2d[:, :, 0] < 0] = False
152
+ visibility[traj_2d[:, :, 1] > image_size[0] - 1] = False
153
+ visibility[traj_2d[:, :, 1] < 0] = False
154
+
155
+ # filter out points that're visible for less than 10 frames
156
+ visible_inds_resampled = visibility.sum(0) > 10
157
+ traj_2d = torch.from_numpy(traj_2d[:, visible_inds_resampled])
158
+ visibility = torch.from_numpy(visibility[:, visible_inds_resampled])
159
+
160
+ rgbs = np.stack(rgbs, 0)
161
+ video = torch.from_numpy(rgbs).reshape(T, H, W, 3).permute(0, 3, 1, 2).float()
162
+ return CoTrackerData(
163
+ video=video,
164
+ trajectory=traj_2d,
165
+ visibility=visibility,
166
+ valid=torch.ones(T, N),
167
+ seq_name=sample[0].sequence_name,
168
+ )
torch_hub/facebookresearch_co-tracker_main/cotracker/datasets/kubric_movif_dataset.py ADDED
@@ -0,0 +1,542 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import os
8
+ import torch
9
+ import cv2
10
+
11
+ import imageio
12
+ import numpy as np
13
+
14
+ from cotracker.datasets.utils import CoTrackerData
15
+ from torchvision.transforms import ColorJitter, GaussianBlur
16
+ from PIL import Image
17
+ from cotracker.models.core.model_utils import smart_cat
18
+
19
+
20
+ class CoTrackerDataset(torch.utils.data.Dataset):
21
+ def __init__(
22
+ self,
23
+ data_root,
24
+ crop_size=(384, 512),
25
+ seq_len=24,
26
+ traj_per_sample=768,
27
+ sample_vis_last_frame=False,
28
+ use_augs=False,
29
+ ):
30
+ super(CoTrackerDataset, self).__init__()
31
+ np.random.seed(0)
32
+ torch.manual_seed(0)
33
+ self.data_root = data_root
34
+ self.seq_len = seq_len
35
+ self.traj_per_sample = traj_per_sample
36
+ self.sample_vis_last_frame = sample_vis_last_frame
37
+ self.use_augs = use_augs
38
+ self.crop_size = crop_size
39
+ # photometric augmentation
40
+ self.photo_aug = ColorJitter(
41
+ brightness=0.2, contrast=0.2, saturation=0.2, hue=0.25 / 3.14
42
+ )
43
+ self.blur_aug = GaussianBlur(11, sigma=(0.1, 2.0))
44
+
45
+ self.blur_aug_prob = 0.25
46
+ self.color_aug_prob = 0.25
47
+
48
+ # occlusion augmentation
49
+ self.eraser_aug_prob = 0.5
50
+ self.eraser_bounds = [2, 100]
51
+ self.eraser_max = 10
52
+
53
+ # occlusion augmentation
54
+ self.replace_aug_prob = 0.5
55
+ self.replace_bounds = [2, 100]
56
+ self.replace_max = 10
57
+
58
+ # spatial augmentations
59
+ self.pad_bounds = [0, 100]
60
+ self.crop_size = crop_size
61
+ self.resize_lim = [0.25, 2.0] # sample resizes from here
62
+ self.resize_delta = 0.2
63
+ self.max_crop_offset = 50
64
+
65
+ self.do_flip = True
66
+ self.h_flip_prob = 0.5
67
+ self.v_flip_prob = 0.5
68
+
69
+ def getitem_helper(self, index):
70
+ return NotImplementedError
71
+
72
+ def __getitem__(self, index):
73
+ gotit = False
74
+
75
+ sample, gotit = self.getitem_helper(index)
76
+ if not gotit:
77
+ print("warning: sampling failed")
78
+ # fake sample, so we can still collate
79
+ sample = CoTrackerData(
80
+ video=torch.zeros(
81
+ (self.seq_len, 3, self.crop_size[0], self.crop_size[1])
82
+ ),
83
+ trajectory=torch.zeros((self.seq_len, self.traj_per_sample, 2)),
84
+ visibility=torch.zeros((self.seq_len, self.traj_per_sample)),
85
+ valid=torch.zeros((self.seq_len, self.traj_per_sample)),
86
+ # dataset_name="kubric",
87
+ )
88
+
89
+ return sample, gotit
90
+
91
+ def add_photometric_augs(self, rgbs, trajs, visibles, eraser=True, replace=True):
92
+ T, N, _ = trajs.shape
93
+
94
+ S = len(rgbs)
95
+ H, W = rgbs[0].shape[:2]
96
+ assert S == T
97
+
98
+ if eraser:
99
+ ############ eraser transform (per image after the first) ############
100
+ rgbs = [rgb.astype(np.float32) for rgb in rgbs]
101
+ for i in range(1, S):
102
+ if np.random.rand() < self.eraser_aug_prob:
103
+ for _ in range(
104
+ np.random.randint(1, self.eraser_max + 1)
105
+ ): # number of times to occlude
106
+ xc = np.random.randint(0, W)
107
+ yc = np.random.randint(0, H)
108
+ dx = np.random.randint(
109
+ self.eraser_bounds[0], self.eraser_bounds[1]
110
+ )
111
+ dy = np.random.randint(
112
+ self.eraser_bounds[0], self.eraser_bounds[1]
113
+ )
114
+ x0 = np.clip(xc - dx / 2, 0, W - 1).round().astype(np.int32)
115
+ x1 = np.clip(xc + dx / 2, 0, W - 1).round().astype(np.int32)
116
+ y0 = np.clip(yc - dy / 2, 0, H - 1).round().astype(np.int32)
117
+ y1 = np.clip(yc + dy / 2, 0, H - 1).round().astype(np.int32)
118
+
119
+ mean_color = np.mean(
120
+ rgbs[i][y0:y1, x0:x1, :].reshape(-1, 3), axis=0
121
+ )
122
+ rgbs[i][y0:y1, x0:x1, :] = mean_color
123
+
124
+ occ_inds = np.logical_and(
125
+ np.logical_and(trajs[i, :, 0] >= x0, trajs[i, :, 0] < x1),
126
+ np.logical_and(trajs[i, :, 1] >= y0, trajs[i, :, 1] < y1),
127
+ )
128
+ visibles[i, occ_inds] = 0
129
+ rgbs = [rgb.astype(np.uint8) for rgb in rgbs]
130
+
131
+ if replace:
132
+ rgbs_alt = [
133
+ np.array(self.photo_aug(Image.fromarray(rgb)), dtype=np.uint8)
134
+ for rgb in rgbs
135
+ ]
136
+ rgbs_alt = [
137
+ np.array(self.photo_aug(Image.fromarray(rgb)), dtype=np.uint8)
138
+ for rgb in rgbs_alt
139
+ ]
140
+
141
+ ############ replace transform (per image after the first) ############
142
+ rgbs = [rgb.astype(np.float32) for rgb in rgbs]
143
+ rgbs_alt = [rgb.astype(np.float32) for rgb in rgbs_alt]
144
+ for i in range(1, S):
145
+ if np.random.rand() < self.replace_aug_prob:
146
+ for _ in range(
147
+ np.random.randint(1, self.replace_max + 1)
148
+ ): # number of times to occlude
149
+ xc = np.random.randint(0, W)
150
+ yc = np.random.randint(0, H)
151
+ dx = np.random.randint(
152
+ self.replace_bounds[0], self.replace_bounds[1]
153
+ )
154
+ dy = np.random.randint(
155
+ self.replace_bounds[0], self.replace_bounds[1]
156
+ )
157
+ x0 = np.clip(xc - dx / 2, 0, W - 1).round().astype(np.int32)
158
+ x1 = np.clip(xc + dx / 2, 0, W - 1).round().astype(np.int32)
159
+ y0 = np.clip(yc - dy / 2, 0, H - 1).round().astype(np.int32)
160
+ y1 = np.clip(yc + dy / 2, 0, H - 1).round().astype(np.int32)
161
+
162
+ wid = x1 - x0
163
+ hei = y1 - y0
164
+ y00 = np.random.randint(0, H - hei)
165
+ x00 = np.random.randint(0, W - wid)
166
+ fr = np.random.randint(0, S)
167
+ rep = rgbs_alt[fr][y00 : y00 + hei, x00 : x00 + wid, :]
168
+ rgbs[i][y0:y1, x0:x1, :] = rep
169
+
170
+ occ_inds = np.logical_and(
171
+ np.logical_and(trajs[i, :, 0] >= x0, trajs[i, :, 0] < x1),
172
+ np.logical_and(trajs[i, :, 1] >= y0, trajs[i, :, 1] < y1),
173
+ )
174
+ visibles[i, occ_inds] = 0
175
+ rgbs = [rgb.astype(np.uint8) for rgb in rgbs]
176
+
177
+ ############ photometric augmentation ############
178
+ if np.random.rand() < self.color_aug_prob:
179
+ # random per-frame amount of aug
180
+ rgbs = [
181
+ np.array(self.photo_aug(Image.fromarray(rgb)), dtype=np.uint8)
182
+ for rgb in rgbs
183
+ ]
184
+
185
+ if np.random.rand() < self.blur_aug_prob:
186
+ # random per-frame amount of blur
187
+ rgbs = [
188
+ np.array(self.blur_aug(Image.fromarray(rgb)), dtype=np.uint8)
189
+ for rgb in rgbs
190
+ ]
191
+
192
+ return rgbs, trajs, visibles
193
+
194
+ def add_spatial_augs(self, rgbs, trajs, visibles, crop_size):
195
+ T, N, __ = trajs.shape
196
+
197
+ S = len(rgbs)
198
+ H, W = rgbs[0].shape[:2]
199
+ assert S == T
200
+
201
+ rgbs = [rgb.astype(np.float32) for rgb in rgbs]
202
+
203
+ ############ spatial transform ############
204
+
205
+ # padding
206
+ pad_x0 = np.random.randint(self.pad_bounds[0], self.pad_bounds[1])
207
+ pad_x1 = np.random.randint(self.pad_bounds[0], self.pad_bounds[1])
208
+ pad_y0 = np.random.randint(self.pad_bounds[0], self.pad_bounds[1])
209
+ pad_y1 = np.random.randint(self.pad_bounds[0], self.pad_bounds[1])
210
+
211
+ rgbs = [
212
+ np.pad(rgb, ((pad_y0, pad_y1), (pad_x0, pad_x1), (0, 0))) for rgb in rgbs
213
+ ]
214
+ trajs[:, :, 0] += pad_x0
215
+ trajs[:, :, 1] += pad_y0
216
+ H, W = rgbs[0].shape[:2]
217
+
218
+ # scaling + stretching
219
+ scale = np.random.uniform(self.resize_lim[0], self.resize_lim[1])
220
+ scale_x = scale
221
+ scale_y = scale
222
+ H_new = H
223
+ W_new = W
224
+
225
+ scale_delta_x = 0.0
226
+ scale_delta_y = 0.0
227
+
228
+ rgbs_scaled = []
229
+ for s in range(S):
230
+ if s == 1:
231
+ scale_delta_x = np.random.uniform(-self.resize_delta, self.resize_delta)
232
+ scale_delta_y = np.random.uniform(-self.resize_delta, self.resize_delta)
233
+ elif s > 1:
234
+ scale_delta_x = (
235
+ scale_delta_x * 0.8
236
+ + np.random.uniform(-self.resize_delta, self.resize_delta) * 0.2
237
+ )
238
+ scale_delta_y = (
239
+ scale_delta_y * 0.8
240
+ + np.random.uniform(-self.resize_delta, self.resize_delta) * 0.2
241
+ )
242
+ scale_x = scale_x + scale_delta_x
243
+ scale_y = scale_y + scale_delta_y
244
+
245
+ # bring h/w closer
246
+ scale_xy = (scale_x + scale_y) * 0.5
247
+ scale_x = scale_x * 0.5 + scale_xy * 0.5
248
+ scale_y = scale_y * 0.5 + scale_xy * 0.5
249
+
250
+ # don't get too crazy
251
+ scale_x = np.clip(scale_x, 0.2, 2.0)
252
+ scale_y = np.clip(scale_y, 0.2, 2.0)
253
+
254
+ H_new = int(H * scale_y)
255
+ W_new = int(W * scale_x)
256
+
257
+ # make it at least slightly bigger than the crop area,
258
+ # so that the random cropping can add diversity
259
+ H_new = np.clip(H_new, crop_size[0] + 10, None)
260
+ W_new = np.clip(W_new, crop_size[1] + 10, None)
261
+ # recompute scale in case we clipped
262
+ scale_x = (W_new - 1) / float(W - 1)
263
+ scale_y = (H_new - 1) / float(H - 1)
264
+ rgbs_scaled.append(
265
+ cv2.resize(rgbs[s], (W_new, H_new), interpolation=cv2.INTER_LINEAR)
266
+ )
267
+ trajs[s, :, 0] *= scale_x
268
+ trajs[s, :, 1] *= scale_y
269
+ rgbs = rgbs_scaled
270
+ ok_inds = visibles[0, :] > 0
271
+ vis_trajs = trajs[:, ok_inds] # S,?,2
272
+
273
+ if vis_trajs.shape[1] > 0:
274
+ mid_x = np.mean(vis_trajs[0, :, 0])
275
+ mid_y = np.mean(vis_trajs[0, :, 1])
276
+ else:
277
+ mid_y = crop_size[0]
278
+ mid_x = crop_size[1]
279
+
280
+ x0 = int(mid_x - crop_size[1] // 2)
281
+ y0 = int(mid_y - crop_size[0] // 2)
282
+
283
+ offset_x = 0
284
+ offset_y = 0
285
+
286
+ for s in range(S):
287
+ # on each frame, shift a bit more
288
+ if s == 1:
289
+ offset_x = np.random.randint(
290
+ -self.max_crop_offset, self.max_crop_offset
291
+ )
292
+ offset_y = np.random.randint(
293
+ -self.max_crop_offset, self.max_crop_offset
294
+ )
295
+ elif s > 1:
296
+ offset_x = int(
297
+ offset_x * 0.8
298
+ + np.random.randint(-self.max_crop_offset, self.max_crop_offset + 1)
299
+ * 0.2
300
+ )
301
+ offset_y = int(
302
+ offset_y * 0.8
303
+ + np.random.randint(-self.max_crop_offset, self.max_crop_offset + 1)
304
+ * 0.2
305
+ )
306
+ x0 = x0 + offset_x
307
+ y0 = y0 + offset_y
308
+
309
+ H_new, W_new = rgbs[s].shape[:2]
310
+ if H_new == crop_size[0]:
311
+ y0 = 0
312
+ else:
313
+ y0 = min(max(0, y0), H_new - crop_size[0] - 1)
314
+
315
+ if W_new == crop_size[1]:
316
+ x0 = 0
317
+ else:
318
+ x0 = min(max(0, x0), W_new - crop_size[1] - 1)
319
+
320
+ rgbs[s] = rgbs[s][y0 : y0 + crop_size[0], x0 : x0 + crop_size[1]]
321
+ trajs[s, :, 0] -= x0
322
+ trajs[s, :, 1] -= y0
323
+
324
+ H_new = crop_size[0]
325
+ W_new = crop_size[1]
326
+
327
+ # flip
328
+ h_flipped = False
329
+ v_flipped = False
330
+ if self.do_flip:
331
+ # h flip
332
+ if np.random.rand() < self.h_flip_prob:
333
+ h_flipped = True
334
+ rgbs = [rgb[:, ::-1] for rgb in rgbs]
335
+ # v flip
336
+ if np.random.rand() < self.v_flip_prob:
337
+ v_flipped = True
338
+ rgbs = [rgb[::-1] for rgb in rgbs]
339
+ if h_flipped:
340
+ trajs[:, :, 0] = W_new - trajs[:, :, 0]
341
+ if v_flipped:
342
+ trajs[:, :, 1] = H_new - trajs[:, :, 1]
343
+ return np.stack(rgbs), trajs
344
+
345
+ def crop(self, rgbs, trajs, crop_size):
346
+ T, N, _ = trajs.shape
347
+
348
+ S = len(rgbs)
349
+ H, W = rgbs[0].shape[:2]
350
+ assert S == T
351
+
352
+ ############ spatial transform ############
353
+
354
+ H_new = H
355
+ W_new = W
356
+
357
+ # simple random crop
358
+ y0 = 0 if crop_size[0] >= H_new else (H_new - crop_size[0]) // 2
359
+ # np.random.randint(0,
360
+ x0 = 0 if crop_size[1] >= W_new else np.random.randint(0, W_new - crop_size[1])
361
+ rgbs = [rgb[y0 : y0 + crop_size[0], x0 : x0 + crop_size[1]] for rgb in rgbs]
362
+
363
+ trajs[:, :, 0] -= x0
364
+ trajs[:, :, 1] -= y0
365
+
366
+ return np.stack(rgbs), trajs
367
+
368
+
369
+ class KubricMovifDataset(CoTrackerDataset):
370
+ def __init__(
371
+ self,
372
+ data_root,
373
+ crop_size=(384, 512),
374
+ seq_len=24,
375
+ traj_per_sample=768,
376
+ sample_vis_last_frame=False,
377
+ use_augs=False,
378
+ random_seq_len=False,
379
+ random_frame_rate=False,
380
+ random_number_traj=False,
381
+ split="train",
382
+ ):
383
+ super(KubricMovifDataset, self).__init__(
384
+ data_root=data_root,
385
+ crop_size=crop_size,
386
+ seq_len=seq_len,
387
+ traj_per_sample=traj_per_sample,
388
+ sample_vis_last_frame=sample_vis_last_frame,
389
+ use_augs=use_augs,
390
+ )
391
+ self.random_seq_len = random_seq_len
392
+ self.random_frame_rate = random_frame_rate
393
+ self.random_number_traj = random_number_traj
394
+ self.pad_bounds = [0, 25]
395
+ self.resize_lim = [0.75, 1.25] # sample resizes from here
396
+ self.resize_delta = 0.05
397
+ self.max_crop_offset = 15
398
+ self.split = split
399
+
400
+ self.seq_names = [
401
+ fname
402
+ for fname in os.listdir(data_root)
403
+ if os.path.isdir(os.path.join(data_root, fname))
404
+ ]
405
+ if self.split == "valid":
406
+ self.seq_names = self.seq_names[:30]
407
+ assert use_augs == False
408
+
409
+ print("found %d unique videos in %s" % (len(self.seq_names), self.data_root))
410
+
411
+ def getitem_helper(self, index):
412
+ gotit = True
413
+ seq_name = self.seq_names[index]
414
+ npy_path = os.path.join(self.data_root, seq_name, seq_name + ".npy")
415
+ rgb_path = os.path.join(self.data_root, seq_name, "frames")
416
+
417
+ img_paths = sorted(os.listdir(rgb_path))
418
+ rgbs = []
419
+ for i, img_path in enumerate(img_paths):
420
+ rgbs.append(imageio.v2.imread(os.path.join(rgb_path, img_path)))
421
+
422
+ rgbs = np.stack(rgbs)
423
+ annot_dict = np.load(npy_path, allow_pickle=True).item()
424
+ traj_2d = annot_dict["coords"]
425
+ visibility = annot_dict["visibility"]
426
+
427
+ frame_rate = 1
428
+ final_num_traj = self.traj_per_sample
429
+ crop_size = self.crop_size
430
+
431
+ # random crop
432
+ min_num_traj = 1
433
+ assert self.traj_per_sample >= min_num_traj
434
+ if self.random_seq_len and self.random_number_traj:
435
+ final_num_traj = np.random.randint(min_num_traj, self.traj_per_sample)
436
+ alpha = final_num_traj / float(self.traj_per_sample)
437
+ seq_len = int(alpha * 10 + (1 - alpha) * self.seq_len)
438
+ seq_len = np.random.randint(seq_len - 2, seq_len + 2)
439
+ if self.random_frame_rate:
440
+ frame_rate = np.random.randint(1, int((120 / seq_len)) + 1)
441
+ elif self.random_number_traj:
442
+ final_num_traj = np.random.randint(min_num_traj, self.traj_per_sample)
443
+ alpha = final_num_traj / float(self.traj_per_sample)
444
+ seq_len = 8 * int(alpha * 2 + (1 - alpha) * self.seq_len // 8)
445
+ # seq_len = np.random.randint(seq_len , seq_len + 2)
446
+ if self.random_frame_rate:
447
+ frame_rate = np.random.randint(1, int((120 / seq_len)) + 1)
448
+ elif self.random_seq_len:
449
+ seq_len = np.random.randint(int(self.seq_len / 2), self.seq_len)
450
+ if self.random_frame_rate:
451
+ frame_rate = np.random.randint(1, int((120 / seq_len)) + 1)
452
+ else:
453
+ seq_len = self.seq_len
454
+ if self.random_frame_rate:
455
+ frame_rate = np.random.randint(1, int((120 / seq_len)) + 1)
456
+
457
+ traj_2d = np.transpose(traj_2d, (1, 0, 2))
458
+ visibility = np.transpose(np.logical_not(visibility), (1, 0))
459
+
460
+ no_augs = False
461
+ if seq_len < len(rgbs):
462
+ if seq_len * frame_rate < len(rgbs):
463
+ start_ind = np.random.choice(len(rgbs) - (seq_len * frame_rate), 1)[0]
464
+ else:
465
+ start_ind = 0
466
+ rgbs = rgbs[start_ind : start_ind + seq_len * frame_rate : frame_rate]
467
+ traj_2d = traj_2d[start_ind : start_ind + seq_len * frame_rate : frame_rate]
468
+ visibility = visibility[
469
+ start_ind : start_ind + seq_len * frame_rate : frame_rate
470
+ ]
471
+
472
+ assert seq_len <= len(rgbs)
473
+
474
+ if not no_augs:
475
+ if self.use_augs:
476
+ rgbs, traj_2d, visibility = self.add_photometric_augs(
477
+ rgbs, traj_2d, visibility, replace=False
478
+ )
479
+ rgbs, traj_2d = self.add_spatial_augs(
480
+ rgbs, traj_2d, visibility, crop_size
481
+ )
482
+ else:
483
+ rgbs, traj_2d = self.crop(rgbs, traj_2d, crop_size)
484
+
485
+ visibility[traj_2d[:, :, 0] > crop_size[1] - 1] = False
486
+ visibility[traj_2d[:, :, 0] < 0] = False
487
+ visibility[traj_2d[:, :, 1] > crop_size[0] - 1] = False
488
+ visibility[traj_2d[:, :, 1] < 0] = False
489
+
490
+ visibility = torch.from_numpy(visibility)
491
+ traj_2d = torch.from_numpy(traj_2d)
492
+
493
+ crop_tensor = torch.tensor(crop_size).flip(0)[None, None] / 2.0
494
+ close_pts_inds = torch.all(
495
+ torch.linalg.vector_norm(traj_2d[..., :2] - crop_tensor, dim=-1) < 1000.0,
496
+ dim=0,
497
+ )
498
+ traj_2d = traj_2d[:, close_pts_inds]
499
+ visibility = visibility[:, close_pts_inds]
500
+
501
+ visibile_pts_first_frame_inds = (visibility[0]).nonzero(as_tuple=False)[:, 0]
502
+
503
+ visibile_pts_mid_frame_inds = (visibility[seq_len // 2]).nonzero(
504
+ as_tuple=False
505
+ )[:, 0]
506
+ visibile_pts_inds = torch.cat(
507
+ (visibile_pts_first_frame_inds, visibile_pts_mid_frame_inds), dim=0
508
+ )
509
+ if self.sample_vis_last_frame:
510
+ visibile_pts_last_frame_inds = (visibility[seq_len - 1]).nonzero(
511
+ as_tuple=False
512
+ )[:, 0]
513
+ visibile_pts_inds = torch.cat(
514
+ (visibile_pts_inds, visibile_pts_last_frame_inds), dim=0
515
+ )
516
+ point_inds = torch.randperm(len(visibile_pts_inds))[: self.traj_per_sample]
517
+ if len(point_inds) < self.traj_per_sample:
518
+ gotit = False
519
+
520
+ visible_inds_sampled = visibile_pts_inds[point_inds]
521
+
522
+ trajs = traj_2d[:, visible_inds_sampled].float()
523
+ visibles = visibility[:, visible_inds_sampled]
524
+ valids = torch.ones_like(visibles)
525
+
526
+ trajs = trajs[:, :final_num_traj]
527
+ visibles = visibles[:, :final_num_traj]
528
+ valids = valids[:, :final_num_traj]
529
+
530
+ rgbs = torch.from_numpy(rgbs).permute(0, 3, 1, 2).float()
531
+
532
+ sample = CoTrackerData(
533
+ video=rgbs,
534
+ trajectory=trajs,
535
+ visibility=visibles,
536
+ valid=valids,
537
+ seq_name=seq_name,
538
+ )
539
+ return sample, gotit
540
+
541
+ def __len__(self):
542
+ return len(self.seq_names)
torch_hub/facebookresearch_co-tracker_main/cotracker/datasets/real_dataset.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import os
8
+ import torch
9
+ import json
10
+ import cv2
11
+ import math
12
+ import imageio
13
+ import numpy as np
14
+
15
+ from cotracker.datasets.utils import CoTrackerData
16
+ from torchvision.transforms import ColorJitter, GaussianBlur
17
+ from PIL import Image
18
+ from cotracker.models.core.model_utils import smart_cat
19
+ from torchvision.io import read_video
20
+ import torchvision
21
+ from cotracker.datasets.utils import collate_fn, collate_fn_train, dataclass_to_cuda_
22
+ import torchvision.transforms.functional as F
23
+
24
+
25
+ class RealDataset(torch.utils.data.Dataset):
26
+ def __init__(
27
+ self,
28
+ crop_size=(384, 512),
29
+ seq_len=24,
30
+ traj_per_sample=768,
31
+ random_frame_rate=False,
32
+ random_seq_len=False,
33
+ data_splits=[0],
34
+ random_resize=False,
35
+ limit_samples=10000,
36
+ ):
37
+ super(RealDataset, self).__init__()
38
+ np.random.seed(0)
39
+ torch.manual_seed(0)
40
+ raise ValueError(f"This dataset wasn't released. You should collect your own dataset of real videos before training with this dataset class.")
41
+
42
+ stopwords = set(
43
+ [
44
+ "river",
45
+ "water",
46
+ "shore",
47
+ "lake",
48
+ "sea",
49
+ "ocean",
50
+ "silhouette",
51
+ "matte",
52
+ "online",
53
+ "virtual",
54
+ "meditation",
55
+ "artwork",
56
+ "drawing",
57
+ "animation",
58
+ "abstract",
59
+ "background",
60
+ "concept",
61
+ "cartoon",
62
+ "symbolic",
63
+ "painting",
64
+ "sketch",
65
+ "fireworks",
66
+ "fire",
67
+ "sky",
68
+ "darkness",
69
+ "timelapse",
70
+ "time-lapse",
71
+ "cgi",
72
+ "computer",
73
+ "computer-generated",
74
+ "drawing",
75
+ "draw",
76
+ "cgi",
77
+ "animate",
78
+ "cartoon",
79
+ "static",
80
+ "abstract",
81
+ "abstraction",
82
+ "3d",
83
+ "fandom",
84
+ "fantasy",
85
+ "graphics",
86
+ "cell",
87
+ "holographic",
88
+ "generated",
89
+ "generation" "telephoto",
90
+ "animated",
91
+ "disko",
92
+ "generate" "2d",
93
+ "3d",
94
+ "geometric",
95
+ "geometry",
96
+ "render",
97
+ "rendering",
98
+ "timelapse",
99
+ "slomo",
100
+ "slo",
101
+ "wallpaper",
102
+ "pattern",
103
+ "tile",
104
+ "generated",
105
+ "chroma",
106
+ "www",
107
+ "http",
108
+ "cannabis",
109
+ "loop",
110
+ "cycle",
111
+ "alpha",
112
+ "abstract",
113
+ "concept",
114
+ "digital",
115
+ "graphic",
116
+ "skies",
117
+ "fountain",
118
+ "train",
119
+ "rapid",
120
+ "fast",
121
+ "quick",
122
+ "vfx",
123
+ "effect",
124
+ ]
125
+ )
126
+
127
+ def no_stopwords_in_key(key, stopwords):
128
+ for s in stopwords:
129
+ if s in key.split(","):
130
+ return False
131
+ return True
132
+
133
+ filelist_all = []
134
+
135
+ for part in data_splits:
136
+ filelist = np.load('YOUR FILELIST')
137
+ captions = np.load('YOUR CAPTIONS')
138
+ keywords = np.load('YOUR KEYWORDS')
139
+
140
+ filtered_seqs_motion = [
141
+ i
142
+ for i, key in enumerate(keywords)
143
+ if "motion" in key.split(",")
144
+ and (
145
+ "man" in key.split(",")
146
+ or "woman" in key.split(",")
147
+ or "animal" in key.split(",")
148
+ or "child" in key.split(",")
149
+ )
150
+ and no_stopwords_in_key(key, stopwords)
151
+ ]
152
+ print("filtered_seqs_motion", len(filtered_seqs_motion))
153
+ filtered_seqs = filtered_seqs_motion
154
+
155
+ print(f"filtered_seqs {part}", len(filtered_seqs))
156
+ filelist_all = filelist_all + filelist[filtered_seqs].tolist()
157
+
158
+ if len(filelist_all) > limit_samples:
159
+ break
160
+
161
+ self.filelist = filelist_all[:limit_samples]
162
+ print(f"found {len(self.filelist)} unique videos")
163
+ self.traj_per_sample = traj_per_sample
164
+ self.crop_size = crop_size
165
+ self.seq_len = seq_len
166
+ self.random_frame_rate = random_frame_rate
167
+ self.random_resize = random_resize
168
+ self.random_seq_len = random_seq_len
169
+
170
+ def crop(self, rgbs):
171
+ S = len(rgbs)
172
+
173
+ H, W = rgbs.shape[2:]
174
+
175
+ H_new = H
176
+ W_new = W
177
+
178
+ # simple random crop
179
+ y0 = (
180
+ 0
181
+ if self.crop_size[0] >= H_new
182
+ else np.random.randint(0, H_new - self.crop_size[0])
183
+ )
184
+ x0 = (
185
+ 0
186
+ if self.crop_size[1] >= W_new
187
+ else np.random.randint(0, W_new - self.crop_size[1])
188
+ )
189
+ rgbs = [
190
+ rgb[:, y0 : y0 + self.crop_size[0], x0 : x0 + self.crop_size[1]]
191
+ for rgb in rgbs
192
+ ]
193
+
194
+ return torch.stack(rgbs)
195
+
196
+ def __getitem__(self, index):
197
+ gotit = False
198
+
199
+ sample, gotit = self.getitem_helper(index)
200
+ if not gotit:
201
+ print("warning: sampling failed")
202
+ # fake sample, so we can still collate
203
+ sample = CoTrackerData(
204
+ video=torch.zeros(
205
+ (self.seq_len, 3, self.crop_size[0], self.crop_size[1])
206
+ ),
207
+ trajectory=torch.ones(1, 1, 1, 2),
208
+ visibility=torch.ones(1, 1, 1),
209
+ valid=torch.ones(1, 1, 1),
210
+ )
211
+
212
+ return sample, gotit
213
+
214
+ def sample_h_w(self):
215
+ area = np.random.uniform(0.6, 1)
216
+ a1 = np.random.uniform(area, 1)
217
+ a2 = np.random.uniform(area, 1)
218
+ h = (a1 + a2) / 2.0
219
+ w = area / h
220
+ return h, w
221
+
222
+ def getitem_helper(self, index):
223
+ gotit = True
224
+ video_path = self.filelist[index]
225
+
226
+ rgbs, _, _ = read_video(str(video_path), output_format="TCHW", pts_unit="sec")
227
+ if rgbs.numel() == 0:
228
+ return None, False
229
+ seq_name = video_path
230
+ frame_rate = 1
231
+
232
+ if self.random_seq_len:
233
+ seq_len = np.random.randint(int(self.seq_len / 2), self.seq_len)
234
+ else:
235
+ seq_len = self.seq_len
236
+
237
+ while len(rgbs) < seq_len:
238
+ rgbs = torch.cat([rgbs, rgbs.flip(0)])
239
+ if seq_len < 8:
240
+ print("seq_len < 8, return NONE")
241
+ return None, False
242
+ if self.random_frame_rate:
243
+ max_frame_rate = min(4, int((len(rgbs) / seq_len)))
244
+ if max_frame_rate > 1:
245
+ frame_rate = np.random.randint(1, max_frame_rate)
246
+
247
+ if seq_len * frame_rate < len(rgbs):
248
+ start_ind = np.random.choice(len(rgbs) - (seq_len * frame_rate), 1)[0]
249
+ else:
250
+ start_ind = 0
251
+ rgbs = rgbs[start_ind : start_ind + seq_len * frame_rate : frame_rate]
252
+
253
+ assert seq_len <= len(rgbs)
254
+
255
+ if self.random_resize and np.random.rand() < 0.5:
256
+ video = []
257
+ rgbs = rgbs.permute(0, 2, 3, 1).numpy()
258
+
259
+ for i in range(len(rgbs)):
260
+ rgb = cv2.resize(
261
+ rgbs[i],
262
+ (self.crop_size[1], self.crop_size[0]),
263
+ interpolation=cv2.INTER_LINEAR,
264
+ )
265
+ video.append(rgb)
266
+ video = torch.tensor(np.stack(video)).permute(0, 3, 1, 2)
267
+
268
+ else:
269
+ video = self.crop(rgbs)
270
+
271
+ sample = CoTrackerData(
272
+ video=video,
273
+ trajectory=torch.ones(seq_len, self.traj_per_sample, 2),
274
+ visibility=torch.ones(seq_len, self.traj_per_sample),
275
+ valid=torch.ones(seq_len, self.traj_per_sample),
276
+ seq_name=seq_name,
277
+ )
278
+
279
+ return sample, gotit
280
+
281
+ def __len__(self):
282
+ return len(self.filelist)
torch_hub/facebookresearch_co-tracker_main/cotracker/datasets/tap_vid_datasets.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import os
8
+ import io
9
+ import glob
10
+ import torch
11
+ import pickle
12
+ import numpy as np
13
+ import mediapy as media
14
+ import random
15
+ from PIL import Image
16
+ from typing import Mapping, Tuple, Union
17
+
18
+ from cotracker.datasets.utils import CoTrackerData
19
+
20
+ DatasetElement = Mapping[str, Mapping[str, Union[np.ndarray, str]]]
21
+
22
+
23
+ def resize_video(video: np.ndarray, output_size: Tuple[int, int]) -> np.ndarray:
24
+ """Resize a video to output_size."""
25
+ # If you have a GPU, consider replacing this with a GPU-enabled resize op,
26
+ # such as a jitted jax.image.resize. It will make things faster.
27
+ return media.resize_video(video, output_size)
28
+
29
+
30
+ def sample_queries_first(
31
+ target_occluded: np.ndarray,
32
+ target_points: np.ndarray,
33
+ frames: np.ndarray,
34
+ ) -> Mapping[str, np.ndarray]:
35
+ """Package a set of frames and tracks for use in TAPNet evaluations.
36
+ Given a set of frames and tracks with no query points, use the first
37
+ visible point in each track as the query.
38
+ Args:
39
+ target_occluded: Boolean occlusion flag, of shape [n_tracks, n_frames],
40
+ where True indicates occluded.
41
+ target_points: Position, of shape [n_tracks, n_frames, 2], where each point
42
+ is [x,y] scaled between 0 and 1.
43
+ frames: Video tensor, of shape [n_frames, height, width, 3]. Scaled between
44
+ -1 and 1.
45
+ Returns:
46
+ A dict with the keys:
47
+ video: Video tensor of shape [1, n_frames, height, width, 3]
48
+ query_points: Query points of shape [1, n_queries, 3] where
49
+ each point is [t, y, x] scaled to the range [-1, 1]
50
+ target_points: Target points of shape [1, n_queries, n_frames, 2] where
51
+ each point is [x, y] scaled to the range [-1, 1]
52
+ """
53
+ valid = np.sum(~target_occluded, axis=1) > 0
54
+ target_points = target_points[valid, :]
55
+ target_occluded = target_occluded[valid, :]
56
+
57
+ query_points = []
58
+ for i in range(target_points.shape[0]):
59
+ index = np.where(target_occluded[i] == 0)[0][0]
60
+ x, y = target_points[i, index, 0], target_points[i, index, 1]
61
+ query_points.append(np.array([index, y, x])) # [t, y, x]
62
+ query_points = np.stack(query_points, axis=0)
63
+
64
+ return {
65
+ "video": frames[np.newaxis, ...],
66
+ "query_points": query_points[np.newaxis, ...],
67
+ "target_points": target_points[np.newaxis, ...],
68
+ "occluded": target_occluded[np.newaxis, ...],
69
+ }
70
+
71
+
72
+ def sample_queries_strided(
73
+ target_occluded: np.ndarray,
74
+ target_points: np.ndarray,
75
+ frames: np.ndarray,
76
+ query_stride: int = 5,
77
+ ) -> Mapping[str, np.ndarray]:
78
+ """Package a set of frames and tracks for use in TAPNet evaluations.
79
+
80
+ Given a set of frames and tracks with no query points, sample queries
81
+ strided every query_stride frames, ignoring points that are not visible
82
+ at the selected frames.
83
+
84
+ Args:
85
+ target_occluded: Boolean occlusion flag, of shape [n_tracks, n_frames],
86
+ where True indicates occluded.
87
+ target_points: Position, of shape [n_tracks, n_frames, 2], where each point
88
+ is [x,y] scaled between 0 and 1.
89
+ frames: Video tensor, of shape [n_frames, height, width, 3]. Scaled between
90
+ -1 and 1.
91
+ query_stride: When sampling query points, search for un-occluded points
92
+ every query_stride frames and convert each one into a query.
93
+
94
+ Returns:
95
+ A dict with the keys:
96
+ video: Video tensor of shape [1, n_frames, height, width, 3]. The video
97
+ has floats scaled to the range [-1, 1].
98
+ query_points: Query points of shape [1, n_queries, 3] where
99
+ each point is [t, y, x] scaled to the range [-1, 1].
100
+ target_points: Target points of shape [1, n_queries, n_frames, 2] where
101
+ each point is [x, y] scaled to the range [-1, 1].
102
+ trackgroup: Index of the original track that each query point was
103
+ sampled from. This is useful for visualization.
104
+ """
105
+ tracks = []
106
+ occs = []
107
+ queries = []
108
+ trackgroups = []
109
+ total = 0
110
+ trackgroup = np.arange(target_occluded.shape[0])
111
+ for i in range(0, target_occluded.shape[1], query_stride):
112
+ mask = target_occluded[:, i] == 0
113
+ query = np.stack(
114
+ [
115
+ i * np.ones(target_occluded.shape[0:1]),
116
+ target_points[:, i, 1],
117
+ target_points[:, i, 0],
118
+ ],
119
+ axis=-1,
120
+ )
121
+ queries.append(query[mask])
122
+ tracks.append(target_points[mask])
123
+ occs.append(target_occluded[mask])
124
+ trackgroups.append(trackgroup[mask])
125
+ total += np.array(np.sum(target_occluded[:, i] == 0))
126
+
127
+ return {
128
+ "video": frames[np.newaxis, ...],
129
+ "query_points": np.concatenate(queries, axis=0)[np.newaxis, ...],
130
+ "target_points": np.concatenate(tracks, axis=0)[np.newaxis, ...],
131
+ "occluded": np.concatenate(occs, axis=0)[np.newaxis, ...],
132
+ "trackgroup": np.concatenate(trackgroups, axis=0)[np.newaxis, ...],
133
+ }
134
+
135
+
136
+ class TapVidDataset(torch.utils.data.Dataset):
137
+ def __init__(
138
+ self,
139
+ data_root,
140
+ dataset_type="davis",
141
+ resize_to=[256, 256],
142
+ queried_first=True,
143
+ fast_eval=False,
144
+ ):
145
+ local_random = random.Random()
146
+ local_random.seed(42)
147
+ self.fast_eval = fast_eval
148
+ self.dataset_type = dataset_type
149
+ self.resize_to = resize_to
150
+ self.queried_first = queried_first
151
+ if self.dataset_type == "kinetics":
152
+ all_paths = glob.glob(os.path.join(data_root, "*_of_0010.pkl"))
153
+ points_dataset = []
154
+ for pickle_path in all_paths:
155
+ with open(pickle_path, "rb") as f:
156
+ data = pickle.load(f)
157
+ points_dataset = points_dataset + data
158
+ if fast_eval:
159
+ points_dataset = local_random.sample(points_dataset, 50)
160
+ self.points_dataset = points_dataset
161
+
162
+ elif self.dataset_type == "robotap":
163
+ all_paths = glob.glob(os.path.join(data_root, "robotap_split*.pkl"))
164
+ points_dataset = None
165
+ for pickle_path in all_paths:
166
+ with open(pickle_path, "rb") as f:
167
+ data = pickle.load(f)
168
+ if points_dataset is None:
169
+ points_dataset = dict(data)
170
+ else:
171
+ points_dataset.update(data)
172
+ if fast_eval:
173
+ points_dataset_keys = local_random.sample(
174
+ sorted(points_dataset.keys()), 50
175
+ )
176
+ points_dataset = {k: points_dataset[k] for k in points_dataset_keys}
177
+ self.points_dataset = points_dataset
178
+ self.video_names = list(self.points_dataset.keys())
179
+ else:
180
+ with open(data_root, "rb") as f:
181
+ self.points_dataset = pickle.load(f)
182
+ if self.dataset_type == "davis":
183
+ self.video_names = list(self.points_dataset.keys())
184
+ elif self.dataset_type == "stacking":
185
+ # print("self.points_dataset", self.points_dataset)
186
+ self.video_names = [i for i in range(len(self.points_dataset))]
187
+ print("found %d unique videos in %s" % (len(self.points_dataset), data_root))
188
+
189
+ def __getitem__(self, index):
190
+ if self.dataset_type == "davis" or self.dataset_type == "robotap":
191
+ video_name = self.video_names[index]
192
+ else:
193
+ video_name = index
194
+ video = self.points_dataset[video_name]
195
+ frames = video["video"]
196
+
197
+ if self.fast_eval and frames.shape[0] > 300:
198
+ return self.__getitem__((index + 1) % self.__len__())
199
+ if isinstance(frames[0], bytes):
200
+ # TAP-Vid is stored and JPEG bytes rather than `np.ndarray`s.
201
+ def decode(frame):
202
+ byteio = io.BytesIO(frame)
203
+ img = Image.open(byteio)
204
+ return np.array(img)
205
+
206
+ frames = np.array([decode(frame) for frame in frames])
207
+
208
+ target_points = self.points_dataset[video_name]["points"]
209
+ if self.resize_to is not None:
210
+ frames = resize_video(frames, self.resize_to)
211
+ target_points *= np.array(
212
+ [self.resize_to[1] - 1, self.resize_to[0] - 1]
213
+ ) # 1 should be mapped to resize_to-1
214
+ else:
215
+ target_points *= np.array([frames.shape[2] - 1, frames.shape[1] - 1])
216
+
217
+ target_occ = self.points_dataset[video_name]["occluded"]
218
+ if self.queried_first:
219
+ converted = sample_queries_first(target_occ, target_points, frames)
220
+ else:
221
+ converted = sample_queries_strided(target_occ, target_points, frames)
222
+ assert converted["target_points"].shape[1] == converted["query_points"].shape[1]
223
+
224
+ trajs = (
225
+ torch.from_numpy(converted["target_points"])[0].permute(1, 0, 2).float()
226
+ ) # T, N, D
227
+
228
+ rgbs = torch.from_numpy(frames).permute(0, 3, 1, 2).float()
229
+ visibles = torch.logical_not(torch.from_numpy(converted["occluded"]))[
230
+ 0
231
+ ].permute(
232
+ 1, 0
233
+ ) # T, N
234
+ query_points = torch.from_numpy(converted["query_points"])[0] # T, N
235
+ return CoTrackerData(
236
+ rgbs,
237
+ trajs,
238
+ visibles,
239
+ seq_name=str(video_name),
240
+ query_points=query_points,
241
+ )
242
+
243
+ def __len__(self):
244
+ return len(self.points_dataset)
torch_hub/facebookresearch_co-tracker_main/cotracker/datasets/utils.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+
8
+ import torch
9
+ import dataclasses
10
+ import torch.nn.functional as F
11
+ from dataclasses import dataclass
12
+ from typing import Any, Optional, Dict
13
+
14
+
15
+ @dataclass(eq=False)
16
+ class CoTrackerData:
17
+ """
18
+ Dataclass for storing video tracks data.
19
+ """
20
+
21
+ video: torch.Tensor # B, S, C, H, W
22
+ trajectory: torch.Tensor # B, S, N, 2
23
+ visibility: torch.Tensor # B, S, N
24
+ # optional data
25
+ valid: Optional[torch.Tensor] = None # B, S, N
26
+ segmentation: Optional[torch.Tensor] = None # B, S, 1, H, W
27
+ seq_name: Optional[str] = None
28
+ query_points: Optional[torch.Tensor] = None # TapVID evaluation format
29
+ transforms: Optional[Dict[str, Any]] = None
30
+ aug_video: Optional[torch.Tensor] = None
31
+
32
+
33
+ def collate_fn(batch):
34
+ """
35
+ Collate function for video tracks data.
36
+ """
37
+ video = torch.stack([b.video for b in batch], dim=0)
38
+ trajectory = torch.stack([b.trajectory for b in batch], dim=0)
39
+ visibility = torch.stack([b.visibility for b in batch], dim=0)
40
+ query_points = segmentation = None
41
+ if batch[0].query_points is not None:
42
+ query_points = torch.stack([b.query_points for b in batch], dim=0)
43
+ if batch[0].segmentation is not None:
44
+ segmentation = torch.stack([b.segmentation for b in batch], dim=0)
45
+ seq_name = [b.seq_name for b in batch]
46
+
47
+ return CoTrackerData(
48
+ video=video,
49
+ trajectory=trajectory,
50
+ visibility=visibility,
51
+ segmentation=segmentation,
52
+ seq_name=seq_name,
53
+ query_points=query_points,
54
+ )
55
+
56
+
57
+ def collate_fn_train(batch):
58
+ """
59
+ Collate function for video tracks data during training.
60
+ """
61
+ gotit = [gotit for _, gotit in batch]
62
+ video = torch.stack([b.video for b, _ in batch], dim=0)
63
+ trajectory = torch.stack([b.trajectory for b, _ in batch], dim=0)
64
+ visibility = torch.stack([b.visibility for b, _ in batch], dim=0)
65
+ valid = torch.stack([b.valid for b, _ in batch], dim=0)
66
+ seq_name = [b.seq_name for b, _ in batch]
67
+ query_points = transforms = aug_video = None
68
+ if batch[0][0].query_points is not None:
69
+ query_points = torch.stack([b.query_points for b, _ in batch], dim=0)
70
+
71
+ if batch[0][0].transforms is not None:
72
+ transforms = [b.transforms for b, _ in batch]
73
+
74
+ if batch[0][0].aug_video is not None:
75
+ aug_video = torch.stack([b.aug_video for b, _ in batch], dim=0)
76
+ return (
77
+ CoTrackerData(
78
+ video=video,
79
+ trajectory=trajectory,
80
+ visibility=visibility,
81
+ valid=valid,
82
+ seq_name=seq_name,
83
+ query_points=query_points,
84
+ aug_video=aug_video,
85
+ transforms=transforms,
86
+ ),
87
+ gotit,
88
+ )
89
+
90
+
91
+ def try_to_cuda(t: Any) -> Any:
92
+ """
93
+ Try to move the input variable `t` to a cuda device.
94
+
95
+ Args:
96
+ t: Input.
97
+
98
+ Returns:
99
+ t_cuda: `t` moved to a cuda device, if supported.
100
+ """
101
+ try:
102
+ t = t.float().cuda()
103
+ except AttributeError:
104
+ pass
105
+ return t
106
+
107
+
108
+ def dataclass_to_cuda_(obj):
109
+ """
110
+ Move all contents of a dataclass to cuda inplace if supported.
111
+
112
+ Args:
113
+ batch: Input dataclass.
114
+
115
+ Returns:
116
+ batch_cuda: `batch` moved to a cuda device, if supported.
117
+ """
118
+ for f in dataclasses.fields(obj):
119
+ setattr(obj, f.name, try_to_cuda(getattr(obj, f.name)))
120
+ return obj
torch_hub/facebookresearch_co-tracker_main/cotracker/evaluation/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
torch_hub/facebookresearch_co-tracker_main/cotracker/evaluation/configs/eval_dynamic_replica.yaml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ defaults:
2
+ - default_config_eval
3
+ exp_dir: ./outputs/cotracker
4
+ dataset_name: dynamic_replica
5
+
6
+
torch_hub/facebookresearch_co-tracker_main/cotracker/evaluation/configs/eval_tapvid_davis_first.yaml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ defaults:
2
+ - default_config_eval
3
+ exp_dir: ./outputs/cotracker
4
+ dataset_name: tapvid_davis_first
5
+
6
+
torch_hub/facebookresearch_co-tracker_main/cotracker/evaluation/configs/eval_tapvid_davis_strided.yaml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ defaults:
2
+ - default_config_eval
3
+ exp_dir: ./outputs/cotracker
4
+ dataset_name: tapvid_davis_strided
5
+
6
+
torch_hub/facebookresearch_co-tracker_main/cotracker/evaluation/configs/eval_tapvid_kinetics_first.yaml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ defaults:
2
+ - default_config_eval
3
+ exp_dir: ./outputs/cotracker
4
+ dataset_name: tapvid_kinetics_first
5
+
6
+
torch_hub/facebookresearch_co-tracker_main/cotracker/evaluation/configs/eval_tapvid_robotap_first.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ defaults:
2
+ - default_config_eval
3
+ exp_dir: ./outputs/cotracker
4
+ dataset_name: tapvid_robotap_first
torch_hub/facebookresearch_co-tracker_main/cotracker/evaluation/configs/eval_tapvid_stacking_first.yaml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ defaults:
2
+ - default_config_eval
3
+ exp_dir: ./outputs/cotracker
4
+ dataset_name: tapvid_stacking_first
5
+
6
+
torch_hub/facebookresearch_co-tracker_main/cotracker/evaluation/configs/eval_tapvid_stacking_strided.yaml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ defaults:
2
+ - default_config_eval
3
+ exp_dir: ./outputs/cotracker
4
+ dataset_name: tapvid_stacking_strided
5
+
6
+
torch_hub/facebookresearch_co-tracker_main/cotracker/evaluation/core/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
torch_hub/facebookresearch_co-tracker_main/cotracker/evaluation/core/eval_utils.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import numpy as np
8
+
9
+ from typing import Iterable, Mapping, Tuple, Union
10
+
11
+
12
+ def compute_tapvid_metrics(
13
+ query_points: np.ndarray,
14
+ gt_occluded: np.ndarray,
15
+ gt_tracks: np.ndarray,
16
+ pred_occluded: np.ndarray,
17
+ pred_tracks: np.ndarray,
18
+ query_mode: str,
19
+ ) -> Mapping[str, np.ndarray]:
20
+ """Computes TAP-Vid metrics (Jaccard, Pts. Within Thresh, Occ. Acc.)
21
+ See the TAP-Vid paper for details on the metric computation. All inputs are
22
+ given in raster coordinates. The first three arguments should be the direct
23
+ outputs of the reader: the 'query_points', 'occluded', and 'target_points'.
24
+ The paper metrics assume these are scaled relative to 256x256 images.
25
+ pred_occluded and pred_tracks are your algorithm's predictions.
26
+ This function takes a batch of inputs, and computes metrics separately for
27
+ each video. The metrics for the full benchmark are a simple mean of the
28
+ metrics across the full set of videos. These numbers are between 0 and 1,
29
+ but the paper multiplies them by 100 to ease reading.
30
+ Args:
31
+ query_points: The query points, an in the format [t, y, x]. Its size is
32
+ [b, n, 3], where b is the batch size and n is the number of queries
33
+ gt_occluded: A boolean array of shape [b, n, t], where t is the number
34
+ of frames. True indicates that the point is occluded.
35
+ gt_tracks: The target points, of shape [b, n, t, 2]. Each point is
36
+ in the format [x, y]
37
+ pred_occluded: A boolean array of predicted occlusions, in the same
38
+ format as gt_occluded.
39
+ pred_tracks: An array of track predictions from your algorithm, in the
40
+ same format as gt_tracks.
41
+ query_mode: Either 'first' or 'strided', depending on how queries are
42
+ sampled. If 'first', we assume the prior knowledge that all points
43
+ before the query point are occluded, and these are removed from the
44
+ evaluation.
45
+ Returns:
46
+ A dict with the following keys:
47
+ occlusion_accuracy: Accuracy at predicting occlusion.
48
+ pts_within_{x} for x in [1, 2, 4, 8, 16]: Fraction of points
49
+ predicted to be within the given pixel threshold, ignoring occlusion
50
+ prediction.
51
+ jaccard_{x} for x in [1, 2, 4, 8, 16]: Jaccard metric for the given
52
+ threshold
53
+ average_pts_within_thresh: average across pts_within_{x}
54
+ average_jaccard: average across jaccard_{x}
55
+ """
56
+
57
+ metrics = {}
58
+ # Fixed bug is described in:
59
+ # https://github.com/facebookresearch/co-tracker/issues/20
60
+ eye = np.eye(gt_tracks.shape[2], dtype=np.int32)
61
+
62
+ if query_mode == "first":
63
+ # evaluate frames after the query frame
64
+ query_frame_to_eval_frames = np.cumsum(eye, axis=1) - eye
65
+ elif query_mode == "strided":
66
+ # evaluate all frames except the query frame
67
+ query_frame_to_eval_frames = 1 - eye
68
+ else:
69
+ raise ValueError("Unknown query mode " + query_mode)
70
+
71
+ query_frame = query_points[..., 0]
72
+ query_frame = np.round(query_frame).astype(np.int32)
73
+ evaluation_points = query_frame_to_eval_frames[query_frame] > 0
74
+
75
+ # Occlusion accuracy is simply how often the predicted occlusion equals the
76
+ # ground truth.
77
+ occ_acc = np.sum(
78
+ np.equal(pred_occluded, gt_occluded) & evaluation_points,
79
+ axis=(1, 2),
80
+ ) / np.sum(evaluation_points)
81
+ metrics["occlusion_accuracy"] = occ_acc
82
+
83
+ # Next, convert the predictions and ground truth positions into pixel
84
+ # coordinates.
85
+ visible = np.logical_not(gt_occluded)
86
+ pred_visible = np.logical_not(pred_occluded)
87
+ all_frac_within = []
88
+ all_jaccard = []
89
+ for thresh in [1, 2, 4, 8, 16]:
90
+ # True positives are points that are within the threshold and where both
91
+ # the prediction and the ground truth are listed as visible.
92
+ within_dist = np.sum(
93
+ np.square(pred_tracks - gt_tracks),
94
+ axis=-1,
95
+ ) < np.square(thresh)
96
+ is_correct = np.logical_and(within_dist, visible)
97
+
98
+ # Compute the frac_within_threshold, which is the fraction of points
99
+ # within the threshold among points that are visible in the ground truth,
100
+ # ignoring whether they're predicted to be visible.
101
+ count_correct = np.sum(
102
+ is_correct & evaluation_points,
103
+ axis=(1, 2),
104
+ )
105
+ count_visible_points = np.sum(visible & evaluation_points, axis=(1, 2))
106
+ frac_correct = count_correct / count_visible_points
107
+ metrics["pts_within_" + str(thresh)] = frac_correct
108
+ all_frac_within.append(frac_correct)
109
+
110
+ true_positives = np.sum(
111
+ is_correct & pred_visible & evaluation_points, axis=(1, 2)
112
+ )
113
+
114
+ # The denominator of the jaccard metric is the true positives plus
115
+ # false positives plus false negatives. However, note that true positives
116
+ # plus false negatives is simply the number of points in the ground truth
117
+ # which is easier to compute than trying to compute all three quantities.
118
+ # Thus we just add the number of points in the ground truth to the number
119
+ # of false positives.
120
+ #
121
+ # False positives are simply points that are predicted to be visible,
122
+ # but the ground truth is not visible or too far from the prediction.
123
+ gt_positives = np.sum(visible & evaluation_points, axis=(1, 2))
124
+ false_positives = (~visible) & pred_visible
125
+ false_positives = false_positives | ((~within_dist) & pred_visible)
126
+ false_positives = np.sum(false_positives & evaluation_points, axis=(1, 2))
127
+ jaccard = true_positives / (gt_positives + false_positives)
128
+ metrics["jaccard_" + str(thresh)] = jaccard
129
+ all_jaccard.append(jaccard)
130
+ metrics["average_jaccard"] = np.mean(
131
+ np.stack(all_jaccard, axis=1),
132
+ axis=1,
133
+ )
134
+ metrics["average_pts_within_thresh"] = np.mean(
135
+ np.stack(all_frac_within, axis=1),
136
+ axis=1,
137
+ )
138
+ return metrics
torch_hub/facebookresearch_co-tracker_main/cotracker/evaluation/core/evaluator.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from collections import defaultdict
8
+ import os
9
+ from typing import Optional
10
+ import torch
11
+ from tqdm import tqdm
12
+ import numpy as np
13
+
14
+ from torch.utils.tensorboard import SummaryWriter
15
+ from cotracker.datasets.utils import dataclass_to_cuda_
16
+ from cotracker.utils.visualizer import Visualizer
17
+ from cotracker.models.core.model_utils import reduce_masked_mean
18
+ from cotracker.evaluation.core.eval_utils import compute_tapvid_metrics
19
+ from cotracker.predictor import CoTrackerOnlinePredictor
20
+ from cotracker.models.core.cotracker.cotracker3_offline import CoTrackerThreeOffline
21
+ from cotracker.models.core.cotracker.cotracker3_online import CoTrackerThreeOnline
22
+ import logging
23
+
24
+
25
+ class Evaluator:
26
+ """
27
+ A class defining the CoTracker evaluator.
28
+ """
29
+
30
+ def __init__(self, exp_dir) -> None:
31
+ # Visualization
32
+ self.exp_dir = exp_dir
33
+ os.makedirs(exp_dir, exist_ok=True)
34
+ self.visualization_filepaths = defaultdict(lambda: defaultdict(list))
35
+ self.visualize_dir = os.path.join(exp_dir, "visualisations")
36
+
37
+ def compute_metrics(self, metrics, sample, pred_trajectory, dataset_name):
38
+ if isinstance(pred_trajectory, tuple):
39
+ pred_trajectory, pred_visibility = pred_trajectory
40
+ else:
41
+ pred_visibility = None
42
+ if "tapvid" in dataset_name:
43
+ B, T, N, D = sample.trajectory.shape
44
+ traj = sample.trajectory.clone()
45
+ thr = 0.6
46
+
47
+ if pred_visibility is None:
48
+ logging.warning("visibility is NONE")
49
+ pred_visibility = torch.zeros_like(sample.visibility)
50
+
51
+ if not pred_visibility.dtype == torch.bool:
52
+ pred_visibility = pred_visibility > thr
53
+
54
+ query_points = sample.query_points.clone().cpu().numpy()
55
+
56
+ pred_visibility = pred_visibility[:, :, :N]
57
+ pred_trajectory = pred_trajectory[:, :, :N]
58
+
59
+ gt_tracks = traj.permute(0, 2, 1, 3).cpu().numpy()
60
+ gt_occluded = (
61
+ torch.logical_not(sample.visibility.clone().permute(0, 2, 1))
62
+ .cpu()
63
+ .numpy()
64
+ )
65
+
66
+ pred_occluded = (
67
+ torch.logical_not(pred_visibility.clone().permute(0, 2, 1))
68
+ .cpu()
69
+ .numpy()
70
+ )
71
+ pred_tracks = pred_trajectory.permute(0, 2, 1, 3).cpu().numpy()
72
+
73
+ out_metrics = compute_tapvid_metrics(
74
+ query_points,
75
+ gt_occluded,
76
+ gt_tracks,
77
+ pred_occluded,
78
+ pred_tracks,
79
+ query_mode="strided" if "strided" in dataset_name else "first",
80
+ )
81
+
82
+ metrics[sample.seq_name[0]] = out_metrics
83
+ for metric_name in out_metrics.keys():
84
+ if "avg" not in metrics:
85
+ metrics["avg"] = {}
86
+ metrics["avg"][metric_name] = np.mean(
87
+ [v[metric_name] for k, v in metrics.items() if k != "avg"]
88
+ )
89
+
90
+ logging.info(f"Metrics: {out_metrics}")
91
+ logging.info(f"avg: {metrics['avg']}")
92
+ print("metrics", out_metrics)
93
+ print("avg", metrics["avg"])
94
+ elif dataset_name == "dynamic_replica" or dataset_name == "pointodyssey":
95
+ *_, N, _ = sample.trajectory.shape
96
+ B, T, N = sample.visibility.shape
97
+ H, W = sample.video.shape[-2:]
98
+ device = sample.video.device
99
+
100
+ out_metrics = {}
101
+
102
+ d_vis_sum = d_occ_sum = d_sum_all = 0.0
103
+ thrs = [1, 2, 4, 8, 16]
104
+ sx_ = (W - 1) / 255.0
105
+ sy_ = (H - 1) / 255.0
106
+ sc_py = np.array([sx_, sy_]).reshape([1, 1, 2])
107
+ sc_pt = torch.from_numpy(sc_py).float().to(device)
108
+ __, first_visible_inds = torch.max(sample.visibility, dim=1)
109
+
110
+ frame_ids_tensor = torch.arange(T, device=device)[None, :, None].repeat(
111
+ B, 1, N
112
+ )
113
+ start_tracking_mask = frame_ids_tensor > (first_visible_inds.unsqueeze(1))
114
+
115
+ for thr in thrs:
116
+ d_ = (
117
+ torch.norm(
118
+ pred_trajectory[..., :2] / sc_pt
119
+ - sample.trajectory[..., :2] / sc_pt,
120
+ dim=-1,
121
+ )
122
+ < thr
123
+ ).float() # B,S-1,N
124
+ d_occ = (
125
+ reduce_masked_mean(
126
+ d_, (1 - sample.visibility) * start_tracking_mask
127
+ ).item()
128
+ * 100.0
129
+ )
130
+ d_occ_sum += d_occ
131
+ out_metrics[f"accuracy_occ_{thr}"] = d_occ
132
+
133
+ d_vis = (
134
+ reduce_masked_mean(
135
+ d_, sample.visibility * start_tracking_mask
136
+ ).item()
137
+ * 100.0
138
+ )
139
+ d_vis_sum += d_vis
140
+ out_metrics[f"accuracy_vis_{thr}"] = d_vis
141
+
142
+ d_all = reduce_masked_mean(d_, start_tracking_mask).item() * 100.0
143
+ d_sum_all += d_all
144
+ out_metrics[f"accuracy_{thr}"] = d_all
145
+
146
+ d_occ_avg = d_occ_sum / len(thrs)
147
+ d_vis_avg = d_vis_sum / len(thrs)
148
+ d_all_avg = d_sum_all / len(thrs)
149
+
150
+ sur_thr = 50
151
+ dists = torch.norm(
152
+ pred_trajectory[..., :2] / sc_pt - sample.trajectory[..., :2] / sc_pt,
153
+ dim=-1,
154
+ ) # B,S,N
155
+ dist_ok = 1 - (dists > sur_thr).float() * sample.visibility # B,S,N
156
+ survival = torch.cumprod(dist_ok, dim=1) # B,S,N
157
+ out_metrics["survival"] = torch.mean(survival).item() * 100.0
158
+
159
+ out_metrics["accuracy_occ"] = d_occ_avg
160
+ out_metrics["accuracy_vis"] = d_vis_avg
161
+ out_metrics["accuracy"] = d_all_avg
162
+
163
+ metrics[sample.seq_name[0]] = out_metrics
164
+ for metric_name in out_metrics.keys():
165
+ if "avg" not in metrics:
166
+ metrics["avg"] = {}
167
+ metrics["avg"][metric_name] = float(
168
+ np.mean([v[metric_name] for k, v in metrics.items() if k != "avg"])
169
+ )
170
+
171
+ logging.info(f"Metrics: {out_metrics}")
172
+ logging.info(f"avg: {metrics['avg']}")
173
+ print("metrics", out_metrics)
174
+ print("avg", metrics["avg"])
175
+
176
+ @torch.no_grad()
177
+ def evaluate_sequence(
178
+ self,
179
+ model,
180
+ test_dataloader: torch.utils.data.DataLoader,
181
+ dataset_name: str,
182
+ train_mode=False,
183
+ visualize_every: int = 50,
184
+ writer: Optional[SummaryWriter] = None,
185
+ step: Optional[int] = 0,
186
+ ):
187
+ metrics = {}
188
+
189
+ vis = Visualizer(
190
+ save_dir=self.exp_dir,
191
+ fps=7,
192
+ )
193
+
194
+ for ind, sample in enumerate(tqdm(test_dataloader)):
195
+ if isinstance(sample, tuple):
196
+ sample, gotit = sample
197
+ if not all(gotit):
198
+ print("batch is None")
199
+ continue
200
+ if torch.cuda.is_available():
201
+ dataclass_to_cuda_(sample)
202
+ device = torch.device("cuda")
203
+ else:
204
+ device = torch.device("cpu")
205
+
206
+ if (
207
+ not train_mode
208
+ and hasattr(model, "sequence_len")
209
+ and (sample.visibility[:, : model.sequence_len].sum() == 0)
210
+ ):
211
+ print(f"skipping batch {ind}")
212
+ continue
213
+
214
+ if "tapvid" in dataset_name:
215
+ queries = sample.query_points.clone().float()
216
+
217
+ queries = torch.stack(
218
+ [
219
+ queries[:, :, 0],
220
+ queries[:, :, 2],
221
+ queries[:, :, 1],
222
+ ],
223
+ dim=2,
224
+ ).to(device)
225
+ else:
226
+ queries = torch.cat(
227
+ [
228
+ torch.zeros_like(sample.trajectory[:, 0, :, :1]),
229
+ sample.trajectory[:, 0],
230
+ ],
231
+ dim=2,
232
+ ).to(device)
233
+
234
+ if isinstance(model.model, CoTrackerThreeOnline):
235
+ online_model = CoTrackerOnlinePredictor(checkpoint=None)
236
+ online_model.model = model.model
237
+ online_model.step = model.model.window_len // 2
238
+ online_model(
239
+ video_chunk=sample.video,
240
+ is_first_step=True,
241
+ queries=queries,
242
+ add_support_grid=False,
243
+ )
244
+ # Process the video
245
+ for ind in range(
246
+ 0, sample.video.shape[1] - online_model.step, online_model.step
247
+ ):
248
+ pred_tracks, pred_visibility = online_model(
249
+ video_chunk=sample.video[:, ind : ind + online_model.step * 2],
250
+ add_support_grid=False,
251
+ grid_size=0,
252
+ ) # B T N 2, B T N 1
253
+ pred_tracks = (pred_tracks, pred_visibility)
254
+ else:
255
+ pred_tracks = model(sample.video, queries)
256
+
257
+ if "strided" in dataset_name:
258
+ inv_video = sample.video.flip(1).clone()
259
+ inv_queries = queries.clone()
260
+ inv_queries[:, :, 0] = inv_video.shape[1] - inv_queries[:, :, 0] - 1
261
+
262
+ pred_trj, pred_vsb = pred_tracks
263
+ inv_pred_trj, inv_pred_vsb = model(inv_video, inv_queries)
264
+
265
+ inv_pred_trj = inv_pred_trj.flip(1)
266
+ inv_pred_vsb = inv_pred_vsb.flip(1)
267
+
268
+ mask = pred_trj == 0
269
+
270
+ pred_trj[mask] = inv_pred_trj[mask]
271
+ pred_vsb[mask[:, :, :, 0]] = inv_pred_vsb[mask[:, :, :, 0]]
272
+
273
+ pred_tracks = pred_trj, pred_vsb
274
+
275
+ if dataset_name == "badja" or dataset_name == "fastcapture":
276
+ seq_name = sample.seq_name[0]
277
+ else:
278
+ seq_name = str(ind)
279
+ if ind % visualize_every == 0:
280
+ vis.visualize(
281
+ sample.video,
282
+ pred_tracks[0] if isinstance(pred_tracks, tuple) else pred_tracks,
283
+ filename=dataset_name + "_" + seq_name,
284
+ writer=writer,
285
+ step=step,
286
+ )
287
+ self.compute_metrics(metrics, sample, pred_tracks, dataset_name)
288
+ return metrics
torch_hub/facebookresearch_co-tracker_main/cotracker/evaluation/evaluate.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import json
8
+ import os
9
+ import hydra
10
+ import numpy as np
11
+ import torch
12
+
13
+ from typing import Optional
14
+ from dataclasses import dataclass, field
15
+
16
+ from omegaconf import OmegaConf
17
+
18
+ from cotracker.datasets.utils import collate_fn
19
+ from cotracker.models.evaluation_predictor import EvaluationPredictor
20
+
21
+ from cotracker.evaluation.core.evaluator import Evaluator
22
+ from cotracker.models.build_cotracker import build_cotracker
23
+
24
+
25
+ @dataclass(eq=False)
26
+ class DefaultConfig:
27
+ # Directory where all outputs of the experiment will be saved.
28
+ exp_dir: str = "./outputs"
29
+
30
+ # Name of the dataset to be used for the evaluation.
31
+ dataset_name: str = "tapvid_davis_first"
32
+ # The root directory of the dataset.
33
+ dataset_root: str = "./"
34
+
35
+ # Path to the pre-trained model checkpoint to be used for the evaluation.
36
+ # The default value is the path to a specific CoTracker model checkpoint.
37
+ checkpoint: str = "./checkpoints/scaled_online.pth"
38
+ # EvaluationPredictor parameters
39
+ # The size (N) of the support grid used in the predictor.
40
+ # The total number of points is (N*N).
41
+ grid_size: int = 5
42
+ # The size (N) of the local support grid.
43
+ local_grid_size: int = 8
44
+ num_uniformly_sampled_pts: int = 0
45
+ sift_size: int = 0
46
+ # A flag indicating whether to evaluate one ground truth point at a time.
47
+ single_point: bool = False
48
+ offline_model: bool = False
49
+ window_len: int = 16
50
+ # The number of iterative updates for each sliding window.
51
+ n_iters: int = 6
52
+
53
+ seed: int = 0
54
+ gpu_idx: int = 0
55
+ local_extent: int = 50
56
+
57
+ v2: bool = False
58
+
59
+ # Override hydra's working directory to current working dir,
60
+ # also disable storing the .hydra logs:
61
+ hydra: dict = field(
62
+ default_factory=lambda: {
63
+ "run": {"dir": "."},
64
+ "output_subdir": None,
65
+ }
66
+ )
67
+
68
+
69
+ def run_eval(cfg: DefaultConfig):
70
+ """
71
+ The function evaluates CoTracker on a specified benchmark dataset based on a provided configuration.
72
+
73
+ Args:
74
+ cfg (DefaultConfig): An instance of DefaultConfig class which includes:
75
+ - exp_dir (str): The directory path for the experiment.
76
+ - dataset_name (str): The name of the dataset to be used.
77
+ - dataset_root (str): The root directory of the dataset.
78
+ - checkpoint (str): The path to the CoTracker model's checkpoint.
79
+ - single_point (bool): A flag indicating whether to evaluate one ground truth point at a time.
80
+ - n_iters (int): The number of iterative updates for each sliding window.
81
+ - seed (int): The seed for setting the random state for reproducibility.
82
+ - gpu_idx (int): The index of the GPU to be used.
83
+ """
84
+ # Creating the experiment directory if it doesn't exist
85
+ os.makedirs(cfg.exp_dir, exist_ok=True)
86
+
87
+ # Saving the experiment configuration to a .yaml file in the experiment directory
88
+ cfg_file = os.path.join(cfg.exp_dir, "expconfig.yaml")
89
+ with open(cfg_file, "w") as f:
90
+ OmegaConf.save(config=cfg, f=f)
91
+
92
+ evaluator = Evaluator(cfg.exp_dir)
93
+ cotracker_model = build_cotracker(
94
+ cfg.checkpoint, offline=cfg.offline_model, window_len=cfg.window_len, v2=cfg.v2
95
+ )
96
+
97
+ # Creating the EvaluationPredictor object
98
+ predictor = EvaluationPredictor(
99
+ cotracker_model,
100
+ grid_size=cfg.grid_size,
101
+ local_grid_size=cfg.local_grid_size,
102
+ sift_size=cfg.sift_size,
103
+ single_point=cfg.single_point,
104
+ num_uniformly_sampled_pts=cfg.num_uniformly_sampled_pts,
105
+ n_iters=cfg.n_iters,
106
+ local_extent=cfg.local_extent,
107
+ interp_shape=(384, 512),
108
+ )
109
+
110
+ if torch.cuda.is_available():
111
+ predictor.model = predictor.model.cuda()
112
+
113
+ # Setting the random seeds
114
+ torch.manual_seed(cfg.seed)
115
+ np.random.seed(cfg.seed)
116
+
117
+ # Constructing the specified dataset
118
+ curr_collate_fn = collate_fn
119
+ if "tapvid" in cfg.dataset_name:
120
+ from cotracker.datasets.tap_vid_datasets import TapVidDataset
121
+
122
+ dataset_type = cfg.dataset_name.split("_")[1]
123
+ if dataset_type == "davis":
124
+ data_root = os.path.join(
125
+ cfg.dataset_root, "tapvid_davis", "tapvid_davis.pkl"
126
+ )
127
+ elif dataset_type == "kinetics":
128
+ data_root = os.path.join(cfg.dataset_root, "tapvid_kinetics")
129
+ elif dataset_type == "robotap":
130
+ data_root = os.path.join(cfg.dataset_root, "tapvid_robotap")
131
+ elif dataset_type == "stacking":
132
+ data_root = os.path.join(
133
+ cfg.dataset_root, "tapvid_rgb_stacking", "tapvid_rgb_stacking.pkl"
134
+ )
135
+
136
+ test_dataset = TapVidDataset(
137
+ dataset_type=dataset_type,
138
+ data_root=data_root,
139
+ queried_first=not "strided" in cfg.dataset_name,
140
+ # resize_to=None,
141
+ )
142
+ elif cfg.dataset_name == "dynamic_replica":
143
+ from cotracker.datasets.dr_dataset import DynamicReplicaDataset
144
+
145
+ test_dataset = DynamicReplicaDataset(
146
+ cfg.dataset_root, sample_len=300, only_first_n_samples=1
147
+ )
148
+
149
+ # Creating the DataLoader object
150
+ test_dataloader = torch.utils.data.DataLoader(
151
+ test_dataset,
152
+ batch_size=1,
153
+ shuffle=False,
154
+ num_workers=1,
155
+ collate_fn=curr_collate_fn,
156
+ )
157
+
158
+ # Timing and conducting the evaluation
159
+ import time
160
+
161
+ start = time.time()
162
+ evaluate_result = evaluator.evaluate_sequence(
163
+ predictor, test_dataloader, dataset_name=cfg.dataset_name
164
+ )
165
+ end = time.time()
166
+ print(end - start)
167
+
168
+ # Saving the evaluation results to a .json file
169
+ evaluate_result = evaluate_result["avg"]
170
+ print("evaluate_result", evaluate_result)
171
+ result_file = os.path.join(cfg.exp_dir, f"result_eval_.json")
172
+ evaluate_result["time"] = end - start
173
+ print(f"Dumping eval results to {result_file}.")
174
+ with open(result_file, "w") as f:
175
+ json.dump(evaluate_result, f)
176
+
177
+
178
+ cs = hydra.core.config_store.ConfigStore.instance()
179
+ cs.store(name="default_config_eval", node=DefaultConfig)
180
+
181
+
182
+ @hydra.main(config_path="./configs/", config_name="default_config_eval")
183
+ def evaluate(cfg: DefaultConfig) -> None:
184
+ os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
185
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(cfg.gpu_idx)
186
+ run_eval(cfg)
187
+
188
+
189
+ if __name__ == "__main__":
190
+ evaluate()
torch_hub/facebookresearch_co-tracker_main/cotracker/models/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
torch_hub/facebookresearch_co-tracker_main/cotracker/models/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (177 Bytes). View file
 
torch_hub/facebookresearch_co-tracker_main/cotracker/models/__pycache__/build_cotracker.cpython-310.pyc ADDED
Binary file (1.23 kB). View file
 
torch_hub/facebookresearch_co-tracker_main/cotracker/models/bootstap_predictor.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+
4
+ import sys
5
+
6
+ import matplotlib.pyplot as plt
7
+ import mediapy as media
8
+ import numpy as np
9
+ from tapnet.torch.tapir_model import TAPIR
10
+
11
+
12
+ def postprocess_occlusions(occlusions, expected_dist):
13
+ visibles = (1 - F.sigmoid(occlusions)) * (1 - F.sigmoid(expected_dist)) > 0.5
14
+ return visibles
15
+
16
+
17
+ class TAPIRPredictor(torch.nn.Module):
18
+ def __init__(self, bootstap=False, model=None):
19
+ super().__init__()
20
+ self.interp_shape = (256, 256)
21
+ if model is None:
22
+ if bootstap:
23
+ checkpoint = "./tapnet/bootstapir_checkpoint.pt"
24
+ model = TAPIR(pyramid_level=1, extra_convs=True)
25
+ else:
26
+ checkpoint = "./tapnet/tapir_checkpoint_panning.pt"
27
+ model = TAPIR(pyramid_level=0, extra_convs=False)
28
+ model.load_state_dict(torch.load(checkpoint))
29
+ self.model = model.eval().to("cuda")
30
+
31
+ def forward(self, rgbs, queries=None, grid_size=0, iters=6, eval_depth=False):
32
+ B, T, C, H, W = rgbs.shape
33
+ rgbs_ = rgbs.reshape(B * T, C, H, W)
34
+ rgbs_ = F.interpolate(rgbs_, tuple(self.interp_shape), mode="bilinear")
35
+ rgbs_ = rgbs_.reshape(B, T, 3, self.interp_shape[0], self.interp_shape[1])
36
+ rgbs_ = rgbs_[0].permute(0, 2, 3, 1)
37
+ rgbs_ = (rgbs_ / 255.0) * 2 - 1
38
+
39
+ if queries is not None:
40
+ queries = queries.clone().float()
41
+ B, N, D = queries.shape
42
+ assert D == 3
43
+ assert B == 1
44
+ queries[:, :, 1] *= self.interp_shape[1] / W
45
+ queries[:, :, 2] *= self.interp_shape[0] / H
46
+ queries = torch.stack(
47
+ [queries[..., 0], queries[..., 2], queries[..., 1]], dim=-1
48
+ )
49
+
50
+ outputs = self.model(video=rgbs_[None], query_points=queries)
51
+ tracks, occlusions, expected_dist = (
52
+ outputs["tracks"],
53
+ outputs["occlusion"][0],
54
+ outputs["expected_dist"][0],
55
+ )
56
+ visibility = postprocess_occlusions(occlusions, expected_dist)[None].permute(
57
+ 0, 2, 1
58
+ )
59
+
60
+ tracks = tracks.permute(0, 2, 1, 3)
61
+
62
+ tracks[:, :, :, 0] *= W / float(self.interp_shape[1])
63
+ tracks[:, :, :, 1] *= H / float(self.interp_shape[0])
64
+
65
+ return tracks, visibility
torch_hub/facebookresearch_co-tracker_main/cotracker/models/build_cotracker.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import torch
8
+
9
+ from cotracker.models.core.cotracker.cotracker import CoTracker2
10
+ from cotracker.models.core.cotracker.cotracker3_offline import CoTrackerThreeOffline
11
+ from cotracker.models.core.cotracker.cotracker3_online import CoTrackerThreeOnline
12
+
13
+
14
+ def build_cotracker(
15
+ checkpoint: str,
16
+ ):
17
+ if checkpoint is None:
18
+ return build_cotracker()
19
+ model_name = checkpoint.split("/")[-1].split(".")[0]
20
+ if model_name == "cotracker":
21
+ return build_cotracker(checkpoint=checkpoint)
22
+ else:
23
+ raise ValueError(f"Unknown model name {model_name}")
24
+
25
+
26
+ def build_cotracker(checkpoint=None, offline=True, window_len=16, v2=False):
27
+ if v2:
28
+ cotracker = CoTracker2(stride=4, window_len=window_len)
29
+ else:
30
+ if offline:
31
+ cotracker = CoTrackerThreeOffline(
32
+ stride=4, corr_radius=3, window_len=window_len
33
+ )
34
+ else:
35
+ cotracker = CoTrackerThreeOnline(
36
+ stride=4, corr_radius=3, window_len=window_len
37
+ )
38
+
39
+ if checkpoint is not None:
40
+ with open(checkpoint, "rb") as f:
41
+ state_dict = torch.load(f, map_location="cpu")
42
+ if "model" in state_dict:
43
+ state_dict = state_dict["model"]
44
+ cotracker.load_state_dict(state_dict)
45
+ return cotracker
torch_hub/facebookresearch_co-tracker_main/cotracker/models/core/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
torch_hub/facebookresearch_co-tracker_main/cotracker/models/core/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (182 Bytes). View file
 
torch_hub/facebookresearch_co-tracker_main/cotracker/models/core/__pycache__/embeddings.cpython-310.pyc ADDED
Binary file (3.59 kB). View file
 
torch_hub/facebookresearch_co-tracker_main/cotracker/models/core/__pycache__/model_utils.cpython-310.pyc ADDED
Binary file (11.3 kB). View file
 
torch_hub/facebookresearch_co-tracker_main/cotracker/models/core/cotracker/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.