yayalong commited on
Commit
376e4e3
·
verified ·
1 Parent(s): c83306f

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. third_party/GraspGen/sam3/.gitignore +153 -0
  2. third_party/GraspGen/sam3/CODE_OF_CONDUCT.md +80 -0
  3. third_party/GraspGen/sam3/CONTRIBUTING.md +30 -0
  4. third_party/GraspGen/sam3/LICENSE +61 -0
  5. third_party/GraspGen/sam3/MANIFEST.in +6 -0
  6. third_party/GraspGen/sam3/README.md +395 -0
  7. third_party/GraspGen/sam3/README_TRAIN.md +190 -0
  8. third_party/GraspGen/sam3/examples/saco_gold_silver_eval_example.ipynb +0 -0
  9. third_party/GraspGen/sam3/examples/saco_gold_silver_vis_example.ipynb +256 -0
  10. third_party/GraspGen/sam3/examples/saco_veval_eval_example.ipynb +137 -0
  11. third_party/GraspGen/sam3/examples/saco_veval_vis_example.ipynb +269 -0
  12. third_party/GraspGen/sam3/examples/sam3_agent.ipynb +242 -0
  13. third_party/GraspGen/sam3/examples/sam3_for_sam1_task_example.ipynb +846 -0
  14. third_party/GraspGen/sam3/examples/sam3_for_sam2_video_task_example.ipynb +979 -0
  15. third_party/GraspGen/sam3/examples/sam3_image_batched_inference.ipynb +0 -0
  16. third_party/GraspGen/sam3/examples/sam3_image_interactive.ipynb +757 -0
  17. third_party/GraspGen/sam3/examples/sam3_image_predictor_example.ipynb +0 -0
  18. third_party/GraspGen/sam3/examples/sam3_video_predictor_example.ipynb +1603 -0
  19. third_party/GraspGen/sam3/pyproject.toml +133 -0
  20. third_party/GraspGen/sam3/realsense-sam.py +1771 -0
  21. third_party/GraspGen/sam3/sam3/__init__.py +9 -0
  22. third_party/GraspGen/sam3/sam3/eval/__init__.py +3 -0
  23. third_party/GraspGen/sam3/sam3/eval/cgf1_eval.py +705 -0
  24. third_party/GraspGen/sam3/sam3/eval/coco_eval.py +914 -0
  25. third_party/GraspGen/sam3/sam3/eval/coco_eval_offline.py +183 -0
  26. third_party/GraspGen/sam3/sam3/eval/conversion_util.py +213 -0
  27. third_party/GraspGen/sam3/sam3/eval/demo_eval.py +658 -0
  28. third_party/GraspGen/sam3/sam3/eval/saco_veval_eval.py +157 -0
  29. third_party/GraspGen/sam3/sam3/eval/ytvis_eval.py +411 -0
  30. third_party/GraspGen/sam3/sam3/logger.py +56 -0
  31. third_party/GraspGen/sam3/sam3/model_builder.py +802 -0
  32. third_party/GraspGen/sam3/sam3/visualization_utils.py +943 -0
  33. third_party/GraspGen/sam3/scripts/extract_odinw_results.py +97 -0
  34. third_party/GraspGen/sam3/scripts/extract_roboflow_vl100_results.py +382 -0
  35. third_party/tuntunclaw/manipulator_grasp/arm/controller/adaptive_controller/__init__.py +1 -0
  36. third_party/tuntunclaw/manipulator_grasp/arm/controller/adaptive_controller/adaptive_controller.py +44 -0
  37. third_party/tuntunclaw/manipulator_grasp/arm/controller/computed_torque_controller/__init__.py +1 -0
  38. third_party/tuntunclaw/manipulator_grasp/arm/controller/computed_torque_controller/computed_torque_controller.py +30 -0
  39. third_party/tuntunclaw/manipulator_grasp/arm/controller/feedforward_controller/__init__.py +1 -0
  40. third_party/tuntunclaw/manipulator_grasp/arm/controller/feedforward_controller/feedforward_controller.py +26 -0
  41. third_party/tuntunclaw/manipulator_grasp/arm/controller/pid_controller/__init__.py +1 -0
  42. third_party/tuntunclaw/manipulator_grasp/arm/controller/pid_controller/pid_controller.py +77 -0
  43. third_party/tuntunclaw/manipulator_grasp/arm/geometry/collision/GJK.py +125 -0
  44. third_party/tuntunclaw/manipulator_grasp/arm/geometry/collision/__init__.py +6 -0
  45. third_party/tuntunclaw/manipulator_grasp/arm/geometry/collision/colliison.py +9 -0
  46. third_party/tuntunclaw/manipulator_grasp/arm/geometry/collision/collision2d.py +30 -0
  47. third_party/tuntunclaw/manipulator_grasp/arm/geometry/collision/distance.py +195 -0
  48. third_party/tuntunclaw/manipulator_grasp/arm/geometry/collision/distance2d.py +51 -0
  49. third_party/tuntunclaw/manipulator_grasp/arm/geometry/collision/intersect2d.py +18 -0
  50. third_party/tuntunclaw/manipulator_grasp/arm/geometry/rotation/SE3Impl.py +75 -0
third_party/GraspGen/sam3/.gitignore ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ *.egg-info/
24
+ .installed.cfg
25
+ *.egg
26
+ MANIFEST
27
+
28
+ # PyInstaller
29
+ # Usually these files are written by a python script from a template
30
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
31
+ *.manifest
32
+ *.spec
33
+
34
+ # Installer logs
35
+ pip-log.txt
36
+ pip-delete-this-directory.txt
37
+
38
+ # Unit test / coverage reports
39
+ htmlcov/
40
+ .tox/
41
+ .nox/
42
+ .coverage
43
+ .coverage.*
44
+ .cache
45
+ nosetests.xml
46
+ coverage.xml
47
+ *.cover
48
+ .hypothesis/
49
+ .pytest_cache/
50
+
51
+ # Translations
52
+ *.mo
53
+ *.pot
54
+
55
+ # Django stuff:
56
+ *.log
57
+ local_settings.py
58
+ db.sqlite3
59
+
60
+ # Flask stuff:
61
+ instance/
62
+ .webassets-cache
63
+
64
+ # Scrapy stuff:
65
+ .scrapy
66
+
67
+ # Sphinx documentation
68
+ docs/_build/
69
+
70
+ # PyBuilder
71
+ target/
72
+
73
+ # Jupyter Notebook
74
+ .ipynb_checkpoints
75
+ *-Copy*.ipynb
76
+
77
+ # IPython
78
+ profile_default/
79
+ ipython_config.py
80
+
81
+ # pyenv
82
+ .python-version
83
+
84
+ # celery beat schedule file
85
+ celerybeat-schedule
86
+
87
+ # SageMath parsed files
88
+ *.sage.py
89
+
90
+ # Environments
91
+ .env
92
+ .venv
93
+ env/
94
+ venv/
95
+ ENV/
96
+ env.bak/
97
+ venv.bak/
98
+
99
+ # Spyder project settings
100
+ .spyderproject
101
+ .spyproject
102
+
103
+ # Rope project settings
104
+ .ropeproject
105
+
106
+ # mkdocs documentation
107
+ /site
108
+
109
+ # mypy
110
+ .mypy_cache/
111
+ .dmypy.json
112
+ dmypy.json
113
+
114
+ # Pyre type checker
115
+ .pyre/
116
+
117
+ # PyCharm
118
+ .idea/
119
+
120
+ # VS Code
121
+ .vscode/
122
+ *.code-workspace
123
+
124
+ # Model weights and checkpoints
125
+ *.pth
126
+ *.pt
127
+ *.bin
128
+ *.ckpt
129
+ *.safetensors
130
+ weights/
131
+ checkpoints/
132
+ sam3_logs/
133
+
134
+ # Data files
135
+ *.h5
136
+ *.hdf5
137
+ *.pkl
138
+ *.pickle
139
+ *.npy
140
+ *.npz
141
+
142
+ # Logs
143
+ logs/
144
+ runs/
145
+ tensorboard/
146
+
147
+ # OS specific
148
+ .DS_Store
149
+ Thumbs.db
150
+
151
+ # BPE vocabulary files
152
+ *.bpe
153
+ *.vocab
third_party/GraspGen/sam3/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@meta.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
third_party/GraspGen/sam3/CONTRIBUTING.md ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributing to sam3
2
+ We want to make contributing to this project as easy and transparent as
3
+ possible.
4
+
5
+ ## Pull Requests
6
+ We actively welcome your pull requests.
7
+
8
+ 1. Fork the repo and create your branch from `main`.
9
+ 2. If you've added code that should be tested, add tests.
10
+ 3. If you've changed APIs, update the documentation.
11
+ 4. Make sure your code lints.
12
+ 5. If you haven't already, complete the Contributor License Agreement ("CLA").
13
+
14
+ ## Contributor License Agreement ("CLA")
15
+ In order to accept your pull request, we need you to submit a CLA. You only need
16
+ to do this once to work on any of Facebook's open source projects.
17
+
18
+ Complete your CLA here: <https://code.facebook.com/cla>
19
+
20
+ ## Issues
21
+ We use GitHub issues to track public bugs. Please ensure your description is
22
+ clear and has sufficient instructions to be able to reproduce the issue.
23
+
24
+ Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe
25
+ disclosure of security bugs. In those cases, please go through the process
26
+ outlined on that page and do not file a public issue.
27
+
28
+ ## License
29
+ By contributing to sam3, you agree that your contributions will be licensed
30
+ under the LICENSE file in the root directory of this source tree.
third_party/GraspGen/sam3/LICENSE ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ SAM License
2
+ Last Updated: November 19, 2025
3
+
4
+ “Agreement” means the terms and conditions for use, reproduction, distribution and modification of the SAM Materials set forth herein.
5
+
6
+
7
+ “SAM Materials” means, collectively, Documentation and the models, software and algorithms, including machine-learning model code, trained model weights, inference-enabling code, training-enabling code, fine-tuning enabling code, and other elements of the foregoing distributed by Meta and made available under this Agreement.
8
+
9
+ “Documentation” means the specifications, manuals and documentation accompanying
10
+ SAM Materials distributed by Meta.
11
+
12
+
13
+ “Licensee” or “you” means you, or your employer or any other person or entity (if you are entering into this Agreement on such person or entity’s behalf), of the age required under applicable laws, rules or regulations to provide legal consent and that has legal authority to bind your employer or such other person or entity if you are entering in this Agreement on their behalf.
14
+
15
+
16
+ “Meta” or “we” means Meta Platforms Ireland Limited (if you are located in or, if you are an entity, your principal place of business is in the EEA or Switzerland) or Meta Platforms, Inc. (if you are located outside of the EEA or Switzerland).
17
+
18
+
19
+ “Sanctions” means any economic or trade sanctions or restrictions administered or enforced by the United States (including the Office of Foreign Assets Control of the U.S. Department of the Treasury (“OFAC”), the U.S. Department of State and the U.S. Department of Commerce), the United Nations, the European Union, or the United Kingdom.
20
+
21
+
22
+ “Trade Controls” means any of the following: Sanctions and applicable export and import controls.
23
+
24
+ By using or distributing any portion or element of the SAM Materials, you agree to be bound by this Agreement.
25
+
26
+
27
+ 1. License Rights and Redistribution.
28
+
29
+
30
+ a. Grant of Rights. You are granted a non-exclusive, worldwide, non-transferable and royalty-free limited license under Meta’s intellectual property or other rights owned by Meta embodied in the SAM Materials to use, reproduce, distribute, copy, create derivative works of, and make modifications to the SAM Materials.
31
+
32
+ b. Redistribution and Use.
33
+ i. Distribution of SAM Materials, and any derivative works thereof, are subject to the terms of this Agreement. If you distribute or make the SAM Materials, or any derivative works thereof, available to a third party, you may only do so under the terms of this Agreement and you shall provide a copy of this Agreement with any such SAM Materials.
34
+
35
+
36
+ ii. If you submit for publication the results of research you perform on, using, or otherwise in connection with SAM Materials, you must acknowledge the use of SAM Materials in your publication.
37
+
38
+
39
+ iii. Your use of the SAM Materials must comply with applicable laws and regulations, including Trade Control Laws and applicable privacy and data protection laws.
40
+ iv. Your use of the SAM Materials will not involve or encourage others to reverse engineer, decompile or discover the underlying components of the SAM Materials.
41
+ v. You are not the target of Trade Controls and your use of SAM Materials must comply with Trade Controls. You agree not to use, or permit others to use, SAM Materials for any activities subject to the International Traffic in Arms Regulations (ITAR) or end uses prohibited by Trade Controls, including those related to military or warfare purposes, nuclear industries or applications, espionage, or the development or use of guns or illegal weapons.
42
+ 2. User Support. Your use of the SAM Materials is done at your own discretion; Meta does not process any information nor provide any service in relation to such use. Meta is under no obligation to provide any support services for the SAM Materials. Any support provided is “as is”, “with all faults”, and without warranty of any kind.
43
+
44
+
45
+ 3. Disclaimer of Warranty. UNLESS REQUIRED BY APPLICABLE LAW, THE SAM MATERIALS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED ON AN “AS IS” BASIS, WITHOUT WARRANTIES OF ANY KIND, AND META DISCLAIMS ALL WARRANTIES OF ANY KIND, BOTH EXPRESS AND IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING OR REDISTRIBUTING THE SAM MATERIALS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR USE OF THE SAM MATERIALS AND ANY OUTPUT AND RESULTS.
46
+
47
+ 4. Limitation of Liability. IN NO EVENT WILL META OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS AGREEMENT, FOR ANY LOST PROFITS OR ANY DIRECT OR INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, EVEN IF META OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING.
48
+
49
+ 5. Intellectual Property.
50
+
51
+
52
+ a. Subject to Meta’s ownership of SAM Materials and derivatives made by or for Meta, with respect to any derivative works and modifications of the SAM Materials that are made by you, as between you and Meta, you are and will be the owner of such derivative works and modifications.
53
+
54
+ b. If you institute litigation or other proceedings against Meta or any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the SAM Materials, outputs or results, or any portion of any of the foregoing, constitutes infringement of intellectual property or other rights owned or licensable by you, then any licenses granted to you under this Agreement shall terminate as of the date such litigation or claim is filed or instituted. You will indemnify and hold harmless Meta from and against any claim by any third party arising out of or related to your use or distribution of the SAM Materials.
55
+
56
+ 6. Term and Termination. The term of this Agreement will commence upon your acceptance of this Agreement or access to the SAM Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein. Meta may terminate this Agreement if you are in breach of any term or condition of this Agreement. Upon termination of this Agreement, you shall delete and cease use of the SAM Materials. Sections 3, 4 and 7 shall survive the termination of this Agreement.
57
+
58
+ 7. Governing Law and Jurisdiction. This Agreement will be governed and construed under the laws of the State of California without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. The courts of California shall have exclusive jurisdiction of any dispute arising out of this Agreement.
59
+
60
+
61
+ 8. Modifications and Amendments. Meta may modify this Agreement from time to time; provided that they are similar in spirit to the current version of the Agreement, but may differ in detail to address new problems or concerns. All such changes will be effective immediately. Your continued use of the SAM Materials after any modification to this Agreement constitutes your agreement to such modification. Except as provided in this Agreement, no modification or addition to any provision of this Agreement will be binding unless it is in writing and signed by an authorized representative of both you and Meta.
third_party/GraspGen/sam3/MANIFEST.in ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ include LICENSE
2
+ include README.md
3
+ recursive-include examples *.py
4
+ recursive-include examples *.ipynb
5
+ recursive-include examples *.md
6
+ recursive-include tests *.py
third_party/GraspGen/sam3/README.md ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SAM 3: Segment Anything with Concepts
2
+
3
+ Meta Superintelligence Labs
4
+
5
+ [Nicolas Carion](https://www.nicolascarion.com/)\*,
6
+ [Laura Gustafson](https://scholar.google.com/citations?user=c8IpF9gAAAAJ&hl=en)\*,
7
+ [Yuan-Ting Hu](https://scholar.google.com/citations?user=E8DVVYQAAAAJ&hl=en)\*,
8
+ [Shoubhik Debnath](https://scholar.google.com/citations?user=fb6FOfsAAAAJ&hl=en)\*,
9
+ [Ronghang Hu](https://ronghanghu.com/)\*,
10
+ [Didac Suris](https://www.didacsuris.com/)\*,
11
+ [Chaitanya Ryali](https://scholar.google.com/citations?user=4LWx24UAAAAJ&hl=en)\*,
12
+ [Kalyan Vasudev Alwala](https://scholar.google.co.in/citations?user=m34oaWEAAAAJ&hl=en)\*,
13
+ [Haitham Khedr](https://hkhedr.com/)\*, Andrew Huang,
14
+ [Jie Lei](https://jayleicn.github.io/),
15
+ [Tengyu Ma](https://scholar.google.com/citations?user=VeTSl0wAAAAJ&hl=en),
16
+ [Baishan Guo](https://scholar.google.com/citations?user=BC5wDu8AAAAJ&hl=en),
17
+ Arpit Kalla, [Markus Marks](https://damaggu.github.io/),
18
+ [Joseph Greer](https://scholar.google.com/citations?user=guL96CkAAAAJ&hl=en),
19
+ Meng Wang, [Peize Sun](https://peizesun.github.io/),
20
+ [Roman Rädle](https://scholar.google.com/citations?user=Tpt57v0AAAAJ&hl=en),
21
+ [Triantafyllos Afouras](https://www.robots.ox.ac.uk/~afourast/),
22
+ [Effrosyni Mavroudi](https://scholar.google.com/citations?user=vYRzGGEAAAAJ&hl=en),
23
+ [Katherine Xu](https://k8xu.github.io/)°,
24
+ [Tsung-Han Wu](https://patrickthwu.com/)°,
25
+ [Yu Zhou](https://yu-bryan-zhou.github.io/)°,
26
+ [Liliane Momeni](https://scholar.google.com/citations?user=Lb-KgVYAAAAJ&hl=en)°,
27
+ [Rishi Hazra](https://rishihazra.github.io/)°,
28
+ [Shuangrui Ding](https://mark12ding.github.io/)°,
29
+ [Sagar Vaze](https://sgvaze.github.io/)°,
30
+ [Francois Porcher](https://scholar.google.com/citations?user=LgHZ8hUAAAAJ&hl=en)°,
31
+ [Feng Li](https://fengli-ust.github.io/)°,
32
+ [Siyuan Li](https://siyuanliii.github.io/)°,
33
+ [Aishwarya Kamath](https://ashkamath.github.io/)°,
34
+ [Ho Kei Cheng](https://hkchengrex.com/)°,
35
+ [Piotr Dollar](https://pdollar.github.io/)†,
36
+ [Nikhila Ravi](https://nikhilaravi.com/)†,
37
+ [Kate Saenko](https://ai.bu.edu/ksaenko.html)†,
38
+ [Pengchuan Zhang](https://pzzhang.github.io/pzzhang/)†,
39
+ [Christoph Feichtenhofer](https://feichtenhofer.github.io/)†
40
+
41
+ \* core contributor, ° intern, † project lead, order is random within groups
42
+
43
+ [[`Paper`](https://ai.meta.com/research/publications/sam-3-segment-anything-with-concepts/)]
44
+ [[`Project`](https://ai.meta.com/sam3)]
45
+ [[`Demo`](https://segment-anything.com/)]
46
+ [[`Blog`](https://ai.meta.com/blog/segment-anything-model-3/)]
47
+ [[`BibTeX`](#citing-sam-3)]
48
+
49
+ ![SAM 3 architecture](assets/model_diagram.png?raw=true) SAM 3 is a unified foundation model for promptable segmentation in images and videos. It can detect, segment, and track objects using text or visual prompts such as points, boxes, and masks. Compared to its predecessor [SAM 2](https://github.com/facebookresearch/sam2), SAM 3 introduces the ability to exhaustively segment all instances of an open-vocabulary concept specified by a short text phrase or exemplars. Unlike prior work, SAM 3 can handle a vastly larger set of open-vocabulary prompts. It achieves 75-80% of human performance on our new [SA-CO benchmark](https://github.com/facebookresearch/sam3?tab=readme-ov-file#sa-co-dataset) which contains 270K unique concepts, over 50 times more than existing benchmarks.
50
+
51
+ This breakthrough is driven by an innovative data engine that has automatically annotated over 4 million unique concepts, creating the largest high-quality open-vocabulary segmentation dataset to date. In addition, SAM 3 introduces a new model architecture featuring a presence token that improves discrimination between closely related text prompts (e.g., “a player in white” vs. “a player in red”), as well as a decoupled detector–tracker design that minimizes task interference and scales efficiently with data.
52
+
53
+ <p align="center">
54
+ <img src="assets/dog.gif" width=380 />
55
+ <img src="assets/player.gif" width=380 />
56
+ </p>
57
+
58
+ ## Installation
59
+
60
+ ### Prerequisites
61
+
62
+ - Python 3.12 or higher
63
+ - PyTorch 2.7 or higher
64
+ - CUDA-compatible GPU with CUDA 12.6 or higher
65
+
66
+ 1. **Create a new Conda environment:**
67
+
68
+ ```bash
69
+ conda create -n sam3 python=3.12
70
+ conda deactivate
71
+ conda activate sam3
72
+ ```
73
+
74
+ 2. **Install PyTorch with CUDA support:**
75
+
76
+ ```bash
77
+ pip install torch==2.7.0 torchvision torchaudio --index-url https://download.pytorch.org/whl/cu126
78
+ ```
79
+
80
+ 3. **Clone the repository and install the package:**
81
+
82
+ ```bash
83
+ git clone https://github.com/facebookresearch/sam3.git
84
+ cd sam3
85
+ pip install -e .
86
+ ```
87
+
88
+ 4. **Install additional dependencies for example notebooks or development:**
89
+
90
+ ```bash
91
+ # For running example notebooks
92
+ pip install -e ".[notebooks]"
93
+
94
+ # For development
95
+ pip install -e ".[train,dev]"
96
+ ```
97
+
98
+ ## Getting Started
99
+
100
+ ⚠️ Before using SAM 3, please request access to the checkpoints on the SAM 3
101
+ Hugging Face [repo](https://huggingface.co/facebook/sam3). Once accepted, you
102
+ need to be authenticated to download the checkpoints. You can do this by running
103
+ the following [steps](https://huggingface.co/docs/huggingface_hub/en/quick-start#authentication)
104
+ (e.g. `hf auth login` after generating an access token.)
105
+
106
+ ### Basic Usage
107
+
108
+ ```python
109
+ import torch
110
+ #################################### For Image ####################################
111
+ from PIL import Image
112
+ from sam3.model_builder import build_sam3_image_model
113
+ from sam3.model.sam3_image_processor import Sam3Processor
114
+ # Load the model
115
+ model = build_sam3_image_model()
116
+ processor = Sam3Processor(model)
117
+ # Load an image
118
+ image = Image.open("<YOUR_IMAGE_PATH.jpg>")
119
+ inference_state = processor.set_image(image)
120
+ # Prompt the model with text
121
+ output = processor.set_text_prompt(state=inference_state, prompt="<YOUR_TEXT_PROMPT>")
122
+
123
+ # Get the masks, bounding boxes, and scores
124
+ masks, boxes, scores = output["masks"], output["boxes"], output["scores"]
125
+
126
+ #################################### For Video ####################################
127
+
128
+ from sam3.model_builder import build_sam3_video_predictor
129
+
130
+ video_predictor = build_sam3_video_predictor()
131
+ video_path = "<YOUR_VIDEO_PATH>" # a JPEG folder or an MP4 video file
132
+ # Start a session
133
+ response = video_predictor.handle_request(
134
+ request=dict(
135
+ type="start_session",
136
+ resource_path=video_path,
137
+ )
138
+ )
139
+ response = video_predictor.handle_request(
140
+ request=dict(
141
+ type="add_prompt",
142
+ session_id=response["session_id"],
143
+ frame_index=0, # Arbitrary frame index
144
+ text="<YOUR_TEXT_PROMPT>",
145
+ )
146
+ )
147
+ output = response["outputs"]
148
+ ```
149
+
150
+ ## Examples
151
+
152
+ The `examples` directory contains notebooks demonstrating how to use SAM3 with
153
+ various types of prompts:
154
+
155
+ - [`sam3_image_predictor_example.ipynb`](examples/sam3_image_predictor_example.ipynb)
156
+ : Demonstrates how to prompt SAM 3 with text and visual box prompts on images.
157
+ - [`sam3_video_predictor_example.ipynb`](examples/sam3_video_predictor_example.ipynb)
158
+ : Demonstrates how to prompt SAM 3 with text prompts on videos, and doing
159
+ further interactive refinements with points.
160
+ - [`sam3_image_batched_inference.ipynb`](examples/sam3_image_batched_inference.ipynb)
161
+ : Demonstrates how to run batched inference with SAM 3 on images.
162
+ - [`sam3_agent.ipynb`](examples/sam3_agent.ipynb): Demonsterates the use of SAM
163
+ 3 Agent to segment complex text prompt on images.
164
+ - [`saco_gold_silver_vis_example.ipynb`](examples/saco_gold_silver_vis_example.ipynb)
165
+ : Shows a few examples from SA-Co image evaluation set.
166
+ - [`saco_veval_vis_example.ipynb`](examples/saco_veval_vis_example.ipynb) :
167
+ Shows a few examples from SA-Co video evaluation set.
168
+
169
+ There are additional notebooks in the examples directory that demonstrate how to
170
+ use SAM 3 for interactive instance segmentation in images and videos (SAM 1/2
171
+ tasks), or as a tool for an MLLM, and how to run evaluations on the SA-Co
172
+ dataset.
173
+
174
+ To run the Jupyter notebook examples:
175
+
176
+ ```bash
177
+ # Make sure you have the notebooks dependencies installed
178
+ pip install -e ".[notebooks]"
179
+
180
+ # Start Jupyter notebook
181
+ jupyter notebook examples/sam3_image_predictor_example.ipynb
182
+ ```
183
+
184
+ ## Model
185
+
186
+ SAM 3 consists of a detector and a tracker that share a vision encoder. It has 848M parameters. The
187
+ detector is a DETR-based model conditioned on text, geometry, and image
188
+ exemplars. The tracker inherits the SAM 2 transformer encoder-decoder
189
+ architecture, supporting video segmentation and interactive refinement.
190
+
191
+ ## Image Results
192
+
193
+ <div align="center">
194
+ <table style="min-width: 80%; border: 2px solid #ddd; border-collapse: collapse">
195
+ <thead>
196
+ <tr>
197
+ <th rowspan="3" style="border-right: 2px solid #ddd; padding: 12px 20px">Model</th>
198
+ <th colspan="3" style="text-align: center; border-right: 2px solid #ddd; padding: 12px 20px">Instance Segmentation</th>
199
+ <th colspan="5" style="text-align: center; padding: 12px 20px">Box Detection</th>
200
+ </tr>
201
+ <tr>
202
+ <th colspan="2" style="text-align: center; border-right: 1px solid #eee; padding: 12px 20px">LVIS</th>
203
+ <th style="text-align: center; border-right: 2px solid #ddd; padding: 12px 20px">SA-Co/Gold</th>
204
+ <th colspan="2" style="text-align: center; border-right: 1px solid #eee; padding: 12px 20px">LVIS</th>
205
+ <th colspan="2" style="text-align: center; border-right: 1px solid #eee; padding: 12px 20px">COCO</th>
206
+ <th style="text-align: center; padding: 12px 20px">SA-Co/Gold</th>
207
+ </tr>
208
+ <tr>
209
+ <th style="text-align: center; padding: 12px 20px">cgF1</th>
210
+ <th style="text-align: center; border-right: 1px solid #eee; padding: 12px 20px">AP</th>
211
+ <th style="text-align: center; border-right: 2px solid #ddd; padding: 12px 20px">cgF1</th>
212
+ <th style="text-align: center; padding: 12px 20px">cgF1</th>
213
+ <th style="text-align: center; border-right: 1px solid #eee; padding: 12px 20px">AP</th>
214
+ <th style="text-align: center; padding: 12px 20px">AP</th>
215
+ <th style="text-align: center; border-right: 1px solid #eee; padding: 12px 20px">AP<sub>o</sub>
216
+ </th>
217
+ <th style="text-align: center; padding: 12px 20px">cgF1</th>
218
+ </tr>
219
+ </thead>
220
+ <tbody>
221
+ <tr>
222
+ <td style="border-right: 2px solid #ddd; padding: 10px 20px">Human</td>
223
+ <td style="text-align: center; padding: 10px 20px">-</td>
224
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">-</td>
225
+ <td style="text-align: center; border-right: 2px solid #ddd; padding: 10px 20px">72.8</td>
226
+ <td style="text-align: center; padding: 10px 20px">-</td>
227
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">-</td>
228
+ <td style="text-align: center; padding: 10px 20px">-</td>
229
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">-</td>
230
+ <td style="text-align: center; padding: 10px 20px">74.0</td>
231
+ </tr>
232
+ <tr>
233
+ <td style="border-right: 2px solid #ddd; padding: 10px 20px">OWLv2*</td>
234
+ <td style="text-align: center; padding: 10px 20px; color: #999">29.3</td>
235
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px; color: #999">43.4</td>
236
+ <td style="text-align: center; border-right: 2px solid #ddd; padding: 10px 20px">24.6</td>
237
+ <td style="text-align: center; padding: 10px 20px; color: #999">30.2</td>
238
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px; color: #999">45.5</td>
239
+ <td style="text-align: center; padding: 10px 20px">46.1</td>
240
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">23.9</td>
241
+ <td style="text-align: center; padding: 10px 20px">24.5</td>
242
+ </tr>
243
+ <tr>
244
+ <td style="border-right: 2px solid #ddd; padding: 10px 20px">DINO-X</td>
245
+ <td style="text-align: center; padding: 10px 20px">-</td>
246
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">38.5</td>
247
+ <td style="text-align: center; border-right: 2px solid #ddd; padding: 10px 20px">21.3</td>
248
+ <td style="text-align: center; padding: 10px 20px">-</td>
249
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">52.4</td>
250
+ <td style="text-align: center; padding: 10px 20px">56.0</td>
251
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">-</td>
252
+ <td style="text-align: center; padding: 10px 20px">22.5</td>
253
+ </tr>
254
+ <tr>
255
+ <td style="border-right: 2px solid #ddd; padding: 10px 20px">Gemini 2.5</td>
256
+ <td style="text-align: center; padding: 10px 20px">13.4</td>
257
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">-</td>
258
+ <td style="text-align: center; border-right: 2px solid #ddd; padding: 10px 20px">13.0</td>
259
+ <td style="text-align: center; padding: 10px 20px">16.1</td>
260
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">-</td>
261
+ <td style="text-align: center; padding: 10px 20px">-</td>
262
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">-</td>
263
+ <td style="text-align: center; padding: 10px 20px">14.4</td>
264
+ </tr>
265
+ <tr style="border-top: 2px solid #b19c9cff">
266
+ <td style="border-right: 2px solid #ddd; padding: 10px 20px">SAM 3</td>
267
+ <td style="text-align: center; padding: 10px 20px">37.2</td>
268
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">48.5</td>
269
+ <td style="text-align: center; border-right: 2px solid #ddd; padding: 10px 20px">54.1</td>
270
+ <td style="text-align: center; padding: 10px 20px">40.6</td>
271
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">53.6</td>
272
+ <td style="text-align: center; padding: 10px 20px">56.4</td>
273
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">55.7</td>
274
+ <td style="text-align: center; padding: 10px 20px">55.7</td>
275
+ </tr>
276
+ </tbody>
277
+ </table>
278
+
279
+ <p style="text-align: center; margin-top: 10px; font-size: 0.9em; color: #ddd;">* Partially trained on LVIS, AP<sub>o</sub> refers to COCO-O accuracy</p>
280
+
281
+ </div>
282
+
283
+ ## Video Results
284
+
285
+ <div align="center">
286
+ <table style="min-width: 80%; border: 2px solid #ddd; border-collapse: collapse">
287
+ <thead>
288
+ <tr>
289
+ <th rowspan="2" style="border-right: 2px solid #ddd; padding: 12px 20px">Model</th>
290
+ <th colspan="2" style="text-align: center; border-right: 1px solid #eee; padding: 12px 20px">SA-V test</th>
291
+ <th colspan="2" style="text-align: center; border-right: 1px solid #eee; padding: 12px 20px">YT-Temporal-1B test</th>
292
+ <th colspan="2" style="text-align: center; border-right: 1px solid #eee; padding: 12px 20px">SmartGlasses test</th>
293
+ <th style="text-align: center; border-right: 1px solid #eee; padding: 12px 20px">LVVIS test</th>
294
+ <th style="text-align: center; padding: 12px 20px">BURST test</th>
295
+ </tr>
296
+ <tr>
297
+ <th style="text-align: center; padding: 12px 20px">cgF1</th>
298
+ <th style="text-align: center; border-right: 1px solid #eee; padding: 12px 20px">pHOTA</th>
299
+ <th style="text-align: center; padding: 12px 20px">cgF1</th>
300
+ <th style="text-align: center; border-right: 1px solid #eee; padding: 12px 20px">pHOTA</th>
301
+ <th style="text-align: center; padding: 12px 20px">cgF1</th>
302
+ <th style="text-align: center; border-right: 1px solid #eee; padding: 12px 20px">pHOTA</th>
303
+ <th style="text-align: center; border-right: 1px solid #eee; padding: 12px 20px">mAP</th>
304
+ <th style="text-align: center; padding: 12px 20px">HOTA</th>
305
+ </tr>
306
+ </thead>
307
+ <tbody>
308
+ <tr>
309
+ <td style="border-right: 2px solid #ddd; padding: 10px 20px">Human</td>
310
+ <td style="text-align: center; padding: 10px 20px">53.1</td>
311
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">70.5</td>
312
+ <td style="text-align: center; padding: 10px 20px">71.2</td>
313
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">78.4</td>
314
+ <td style="text-align: center; padding: 10px 20px">58.5</td>
315
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">72.3</td>
316
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">-</td>
317
+ <td style="text-align: center; padding: 10px 20px">-</td>
318
+ </tr>
319
+ <tr style="border-top: 2px solid #b19c9cff">
320
+ <td style="border-right: 2px solid #ddd; padding: 10px 20px">SAM 3</td>
321
+ <td style="text-align: center; padding: 10px 20px">30.3</td>
322
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">58.0</td>
323
+ <td style="text-align: center; padding: 10px 20px">50.8</td>
324
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">69.9</td>
325
+ <td style="text-align: center; padding: 10px 20px">36.4</td>
326
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">63.6</td>
327
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">36.3</td>
328
+ <td style="text-align: center; padding: 10px 20px">44.5</td>
329
+ </tr>
330
+ </tbody>
331
+ </table>
332
+ </div>
333
+
334
+ ## SA-Co Dataset
335
+
336
+ We release 2 image benchmarks, [SA-Co/Gold](scripts/eval/gold/README.md) and
337
+ [SA-Co/Silver](scripts/eval/silver/README.md), and a video benchmark
338
+ [SA-Co/VEval](scripts/eval/veval/README.md). The datasets contain images (or videos) with annotated noun phrases. Each image/video and noun phrase pair is annotated with instance masks and unique IDs of each object matching the phrase. Phrases that have no matching objects (negative prompts) have no masks, shown in red font in the figure. See the linked READMEs for more details on how to download and run evaluations on the datasets.
339
+
340
+ * HuggingFace host: [SA-Co/Gold](https://huggingface.co/datasets/facebook/SACo-Gold), [SA-Co/Silver](https://huggingface.co/datasets/facebook/SACo-Silver) and [SA-Co/VEval](https://huggingface.co/datasets/facebook/SACo-VEval)
341
+ * Roboflow host: [SA-Co/Gold](https://universe.roboflow.com/sa-co-gold), [SA-Co/Silver](https://universe.roboflow.com/sa-co-silver) and [SA-Co/VEval](https://universe.roboflow.com/sa-co-veval)
342
+
343
+ ![SA-Co dataset](assets/sa_co_dataset.jpg?raw=true)
344
+
345
+ ## Development
346
+
347
+ To set up the development environment:
348
+
349
+ ```bash
350
+ pip install -e ".[dev,train]"
351
+ ```
352
+
353
+ To format the code:
354
+
355
+ ```bash
356
+ ufmt format .
357
+ ```
358
+
359
+ ## Contributing
360
+
361
+ See [contributing](CONTRIBUTING.md) and the
362
+ [code of conduct](CODE_OF_CONDUCT.md).
363
+
364
+ ## License
365
+
366
+ This project is licensed under the SAM License - see the [LICENSE](LICENSE) file
367
+ for details.
368
+
369
+ ## Acknowledgements
370
+
371
+ We would like to thank the following people for their contributions to the SAM 3 project: Alex He, Alexander Kirillov,
372
+ Alyssa Newcomb, Ana Paula Kirschner Mofarrej, Andrea Madotto, Andrew Westbury, Ashley Gabriel, Azita Shokpour,
373
+ Ben Samples, Bernie Huang, Carleigh Wood, Ching-Feng Yeh, Christian Puhrsch, Claudette Ward, Daniel Bolya,
374
+ Daniel Li, Facundo Figueroa, Fazila Vhora, George Orlin, Hanzi Mao, Helen Klein, Hu Xu, Ida Cheng, Jake Kinney,
375
+ Jiale Zhi, Jo Sampaio, Joel Schlosser, Justin Johnson, Kai Brown, Karen Bergan, Karla Martucci, Kenny Lehmann,
376
+ Maddie Mintz, Mallika Malhotra, Matt Ward, Michelle Chan, Michelle Restrepo, Miranda Hartley, Muhammad Maaz,
377
+ Nisha Deo, Peter Park, Phillip Thomas, Raghu Nayani, Rene Martinez Doehner, Robbie Adkins, Ross Girshik, Sasha
378
+ Mitts, Shashank Jain, Spencer Whitehead, Ty Toledano, Valentin Gabeur, Vincent Cho, Vivian Lee, William Ngan,
379
+ Xuehai He, Yael Yungster, Ziqi Pang, Ziyi Dou, Zoe Quake.
380
+
381
+ ## Citing SAM 3
382
+
383
+ If you use SAM 3 or the SA-Co dataset in your research, please use the following BibTeX entry.
384
+
385
+ ```bibtex
386
+ @misc{carion2025sam3segmentconcepts,
387
+ title={SAM 3: Segment Anything with Concepts},
388
+ author={Nicolas Carion and Laura Gustafson and Yuan-Ting Hu and Shoubhik Debnath and Ronghang Hu and Didac Suris and Chaitanya Ryali and Kalyan Vasudev Alwala and Haitham Khedr and Andrew Huang and Jie Lei and Tengyu Ma and Baishan Guo and Arpit Kalla and Markus Marks and Joseph Greer and Meng Wang and Peize Sun and Roman Rädle and Triantafyllos Afouras and Effrosyni Mavroudi and Katherine Xu and Tsung-Han Wu and Yu Zhou and Liliane Momeni and Rishi Hazra and Shuangrui Ding and Sagar Vaze and Francois Porcher and Feng Li and Siyuan Li and Aishwarya Kamath and Ho Kei Cheng and Piotr Dollár and Nikhila Ravi and Kate Saenko and Pengchuan Zhang and Christoph Feichtenhofer},
389
+ year={2025},
390
+ eprint={2511.16719},
391
+ archivePrefix={arXiv},
392
+ primaryClass={cs.CV},
393
+ url={https://arxiv.org/abs/2511.16719},
394
+ }
395
+ ```
third_party/GraspGen/sam3/README_TRAIN.md ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Training
2
+
3
+ This repository supports finetuning SAM3 models on custom datasets in multi-node setup or local execution. The training script is located at `sam3/train.py` and uses Hydra configuration management to handle complex training setups.
4
+
5
+
6
+ ## Installation
7
+
8
+ ```bash
9
+ cd sam3
10
+ pip install -e ".[train]"
11
+ ```
12
+
13
+ ### Training Script Usage
14
+
15
+ The main training script is located at `sam3/train.py`. It uses Hydra configuration management to handle complex training setups.
16
+
17
+ #### Basic Usage
18
+
19
+ ```bash
20
+ # Example: Train on Roboflow dataset
21
+ python sam3/train/train.py -c configs/roboflow_v100/roboflow_v100_full_ft_100_images.yaml
22
+ # Example: Train on ODinW13 dataset
23
+ python sam3/train/train.py -c configs/odinw13/odinw_text_only_train.yaml
24
+ ```
25
+ Follow [`Roboflow 100-VL`](https://github.com/roboflow/rf100-vl/) to download the roboflow 100-vl datasets. Follow [`GLIP`](https://github.com/microsoft/GLIP) to download the ODinW datasets. The data folder should be organized as follows, and put your roboflow_vl_100_root and odinw_data_root in the job configs.
26
+ ```
27
+ roboflow_vl_100_root:
28
+ 13-lkc01
29
+ train
30
+ valid
31
+ test
32
+ 2024-frc
33
+ actions
34
+ ...
35
+ odinw_data_root:
36
+ AerialMaritimeDrone
37
+ large
38
+ train
39
+ valid
40
+ test
41
+ Aquarium
42
+ ...
43
+ ```
44
+
45
+ #### Command Line Arguments
46
+
47
+ The training script supports several command line arguments:
48
+
49
+ ```bash
50
+ python sam3/train/train.py \
51
+ -c CONFIG_NAME \
52
+ [--use-cluster 0|1] \
53
+ [--partition PARTITION_NAME] \
54
+ [--account ACCOUNT_NAME] \
55
+ [--qos QOS_NAME] \
56
+ [--num-gpus NUM_GPUS] \
57
+ [--num-nodes NUM_NODES]
58
+ ```
59
+
60
+ **Arguments:**
61
+ - `-c, --config`: **Required.** Path to the configuration file (e.g., `sam3/train/configs/roboflow_v100_full_ft_100_images.yaml`)
62
+ - `--use-cluster`: Whether to launch on a cluster (0: local, 1: cluster). Default: uses config setting
63
+ - `--partition`: SLURM partition name for cluster execution
64
+ - `--account`: SLURM account name for cluster execution
65
+ - `--qos`: SLURM QOS (Quality of Service) setting
66
+ - `--num-gpus`: Number of GPUs per node. Default: uses config setting
67
+ - `--num-nodes`: Number of nodes for distributed training. Default: uses config setting
68
+
69
+ #### Local Training Examples
70
+
71
+ ```bash
72
+ # Single GPU training
73
+ python sam3/train/train.py -c configs/roboflow_v100/roboflow_v100_full_ft_100_images.yaml --use-cluster 0 --num-gpus 1
74
+
75
+ # Multi-GPU training on a single node
76
+ python sam3/train/train.py -c configs/roboflow_v100/roboflow_v100_full_ft_100_images.yaml --use-cluster 0 --num-gpus 4
77
+
78
+ # Force local execution even if config specifies GPUs
79
+ python sam3/train/train.py -c configs/roboflow_v100/roboflow_v100_full_ft_100_images.yaml --use-cluster 0
80
+ ```
81
+
82
+ #### Cluster Training Examples
83
+
84
+ ```bash
85
+ # Basic cluster training with default settings from config
86
+ python sam3/train/train.py -c configs/roboflow_v100/roboflow_v100_full_ft_100_images.yaml --use-cluster 1
87
+
88
+ # Cluster training with specific SLURM settings
89
+ python sam3/train/train.py -c configs/roboflow_v100/roboflow_v100_full_ft_100_images.yaml \
90
+ --use-cluster 1 \
91
+ --partition gpu_partition \
92
+ --account my_account \
93
+ --qos high_priority \
94
+ --num-gpus 8 \
95
+ --num-nodes 2
96
+ ```
97
+
98
+ ### Configuration Files
99
+
100
+ Training configurations are stored in `sam3/train/configs/`. The configuration files use Hydra's YAML format and support:
101
+
102
+ - **Dataset Configuration**: Data paths, transforms, and loading parameters
103
+ - **Model Configuration**: Architecture settings, checkpoint paths, and model parameters
104
+ - **Training Configuration**: Batch sizes, learning rates, optimization settings
105
+ - **Launcher Configuration**: Distributed training and cluster settings
106
+ - **Logging Configuration**: TensorBoard, experiment tracking, and output directories
107
+
108
+ #### Key Configuration Sections
109
+
110
+ ```yaml
111
+ # Paths to datasets and checkpoints
112
+ paths:
113
+ bpe_path: /path/to/bpe/file
114
+ dataset_root: /path/to/dataset
115
+ experiment_log_dir: /path/to/logs
116
+
117
+ # Launcher settings for local/cluster execution
118
+ launcher:
119
+ num_nodes: 1
120
+ gpus_per_node: 2
121
+ experiment_log_dir: ${paths.experiment_log_dir}
122
+
123
+ # Cluster execution settings
124
+ submitit:
125
+ use_cluster: True
126
+ timeout_hour: 72
127
+ cpus_per_task: 10
128
+ partition: null
129
+ account: null
130
+ ```
131
+
132
+ ### Monitoring Training
133
+
134
+ The training script automatically sets up logging and saves outputs to the experiment directory:
135
+
136
+ ```bash
137
+ # Logs are saved to the experiment_log_dir specified in config
138
+ experiment_log_dir/
139
+ ├── config.yaml # Original configuration
140
+ ├── config_resolved.yaml # Resolved configuration with all variables expanded
141
+ ├── checkpoints/ # Model checkpoints (if skip_checkpointing=False)
142
+ ├── tensorboard/ # TensorBoard logs
143
+ ├── logs/ # Text logs
144
+ └── submitit_logs/ # Cluster job logs (if using cluster)
145
+ ```
146
+
147
+ You can monitor training progress using TensorBoard:
148
+
149
+ ```bash
150
+ tensorboard --logdir /path/to/experiment_log_dir/tensorboard
151
+ ```
152
+
153
+ ### Job Arrays for Dataset Sweeps
154
+
155
+ The Roboflow and ODinW configuration supports job arrays for training multiple models on different datasets:
156
+
157
+ This feature is specifically enabled via,
158
+ ```yaml
159
+ submitit:
160
+ job_array:
161
+ num_tasks: 100
162
+ task_index: 0
163
+ ```
164
+
165
+ The configuration includes a complete list of 100 Roboflow supercategories, and the `submitit.job_array.task_index` automatically selects which dataset to use based on the array job index.
166
+
167
+ ```bash
168
+ # Submit job array to train on different Roboflow datasets
169
+ # The job array index selects which dataset from all_roboflow_supercategories
170
+ python sam3/train/train.py -c configs/roboflow_v100/roboflow_v100_full_ft_100_images.yaml \
171
+ --use-cluster 1
172
+ ```
173
+
174
+ ### Reproduce ODinW13 10-shot results
175
+ Running the following job will give the results on the ODinW13 seed 300, see `odinw_train.train_file: fewshot_train_shot10_seed300` in the config file.
176
+ ```bash
177
+ # Example: Train on ODinW13 dataset
178
+ python sam3/train/train.py -c configs/odinw13/odinw_text_only_train.yaml
179
+ ```
180
+ Change `odinw_train.train_file` to `fewshot_train_shot10_seed30` and `fewshot_train_shot10_seed3` to get the results for the other two seeds. Final results are aggregated from the three seeds. Notice that a small number of jobs may diverge during training, in which case we just use the last checkpoint's result before it diverges.
181
+
182
+
183
+ ### Eval Script Usage
184
+ With a similar setup as the training config, the training script `sam3/train.py` can also be used for evaluation, too, when setting `trainer.mode = val` in the job config. Run the following job will give the results on the zero-shot results on RF100-VL and ODinW13 datasets.
185
+ ```bash
186
+ # Example: Evaluate on Roboflow dataset
187
+ python sam3/train/train.py -c configs/roboflow_v100/roboflow_v100_eval.yaml
188
+ # Example: Evaluate on ODinW13 dataset
189
+ python sam3/train/train.py -c configs/odinw13/odinw_text_only.yaml
190
+ ```
third_party/GraspGen/sam3/examples/saco_gold_silver_eval_example.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
third_party/GraspGen/sam3/examples/saco_gold_silver_vis_example.ipynb ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "37048f21",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "# Copyright (c) Meta Platforms, Inc. and affiliates."
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "code",
15
+ "execution_count": null,
16
+ "id": "154d8663",
17
+ "metadata": {},
18
+ "outputs": [],
19
+ "source": [
20
+ "using_colab = False"
21
+ ]
22
+ },
23
+ {
24
+ "cell_type": "code",
25
+ "execution_count": null,
26
+ "id": "b85d99d9",
27
+ "metadata": {},
28
+ "outputs": [],
29
+ "source": [
30
+ "if using_colab:\n",
31
+ " import torch\n",
32
+ " import torchvision\n",
33
+ " print(\"PyTorch version:\", torch.__version__)\n",
34
+ " print(\"Torchvision version:\", torchvision.__version__)\n",
35
+ " print(\"CUDA is available:\", torch.cuda.is_available())\n",
36
+ " import sys\n",
37
+ " !{sys.executable} -m pip install opencv-python matplotlib scikit-learn\n",
38
+ " !{sys.executable} -m pip install 'git+https://github.com/facebookresearch/sam3.git'"
39
+ ]
40
+ },
41
+ {
42
+ "cell_type": "code",
43
+ "execution_count": null,
44
+ "id": "da21a3bc",
45
+ "metadata": {},
46
+ "outputs": [],
47
+ "source": [
48
+ "import os\n",
49
+ "from glob import glob\n",
50
+ "\n",
51
+ "import numpy as np\n",
52
+ "import sam3.visualization_utils as utils\n",
53
+ "\n",
54
+ "from matplotlib import pyplot as plt\n",
55
+ "\n",
56
+ "COLORS = utils.pascal_color_map()[1:]"
57
+ ]
58
+ },
59
+ {
60
+ "cell_type": "markdown",
61
+ "id": "57e85e7e",
62
+ "metadata": {},
63
+ "source": [
64
+ "1. Load the data"
65
+ ]
66
+ },
67
+ {
68
+ "cell_type": "code",
69
+ "execution_count": null,
70
+ "id": "a796734e",
71
+ "metadata": {},
72
+ "outputs": [],
73
+ "source": [
74
+ "# Preapre the data path\n",
75
+ "ANNOT_DIR = None # PUT YOUR ANNOTATION PATH HERE\n",
76
+ "IMG_DIR = None # PUT YOUR IMAGE PATH HERE\n",
77
+ "\n",
78
+ "# Load the SA-CO/Gold annotation files\n",
79
+ "annot_file_list = glob(os.path.join(ANNOT_DIR, \"*gold*.json\"))\n",
80
+ "annot_dfs = utils.get_annot_dfs(file_list=annot_file_list)"
81
+ ]
82
+ },
83
+ {
84
+ "cell_type": "markdown",
85
+ "id": "74bf92b1",
86
+ "metadata": {},
87
+ "source": [
88
+ "Show the annotation files being loaded"
89
+ ]
90
+ },
91
+ {
92
+ "cell_type": "code",
93
+ "execution_count": null,
94
+ "id": "a95620ec",
95
+ "metadata": {},
96
+ "outputs": [],
97
+ "source": [
98
+ "annot_dfs.keys()"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "markdown",
103
+ "id": "5ce211d3",
104
+ "metadata": {},
105
+ "source": [
106
+ "2. Examples of the data format"
107
+ ]
108
+ },
109
+ {
110
+ "cell_type": "code",
111
+ "execution_count": null,
112
+ "id": "6ba749db",
113
+ "metadata": {},
114
+ "outputs": [],
115
+ "source": [
116
+ "annot_dfs[\"gold_fg_sports_equipment_merged_a_release_test\"].keys()"
117
+ ]
118
+ },
119
+ {
120
+ "cell_type": "code",
121
+ "execution_count": null,
122
+ "id": "4b6dc186",
123
+ "metadata": {},
124
+ "outputs": [],
125
+ "source": [
126
+ "annot_dfs[\"gold_fg_sports_equipment_merged_a_release_test\"][\"info\"]"
127
+ ]
128
+ },
129
+ {
130
+ "cell_type": "code",
131
+ "execution_count": null,
132
+ "id": "c41091b3",
133
+ "metadata": {},
134
+ "outputs": [],
135
+ "source": [
136
+ "annot_dfs[\"gold_fg_sports_equipment_merged_a_release_test\"][\"images\"].head(3)"
137
+ ]
138
+ },
139
+ {
140
+ "cell_type": "code",
141
+ "execution_count": null,
142
+ "id": "a7df5771",
143
+ "metadata": {},
144
+ "outputs": [],
145
+ "source": [
146
+ "annot_dfs[\"gold_fg_sports_equipment_merged_a_release_test\"][\"annotations\"].head(3)"
147
+ ]
148
+ },
149
+ {
150
+ "cell_type": "markdown",
151
+ "id": "5673a63f",
152
+ "metadata": {},
153
+ "source": [
154
+ "3. Visualize the data"
155
+ ]
156
+ },
157
+ {
158
+ "cell_type": "code",
159
+ "execution_count": null,
160
+ "id": "b1fc2a24",
161
+ "metadata": {},
162
+ "outputs": [],
163
+ "source": [
164
+ "# Select a target dataset\n",
165
+ "target_dataset_name = \"gold_fg_food_merged_a_release_test\"\n",
166
+ "\n",
167
+ "import cv2\n",
168
+ "from pycocotools import mask as mask_util\n",
169
+ "from collections import defaultdict\n",
170
+ "\n",
171
+ "# Group GT annotations by image_id\n",
172
+ "gt_image_np_pairs = annot_dfs[target_dataset_name][\"images\"]\n",
173
+ "gt_annotations = annot_dfs[target_dataset_name][\"annotations\"]\n",
174
+ "\n",
175
+ "gt_image_np_map = {img[\"id\"]: img for _, img in gt_image_np_pairs.iterrows()}\n",
176
+ "gt_image_np_ann_map = defaultdict(list)\n",
177
+ "for _, ann in gt_annotations.iterrows():\n",
178
+ " image_id = ann[\"image_id\"]\n",
179
+ " if image_id not in gt_image_np_ann_map:\n",
180
+ " gt_image_np_ann_map[image_id] = []\n",
181
+ " gt_image_np_ann_map[image_id].append(ann)\n",
182
+ "\n",
183
+ "positiveNPs = common_image_ids = [img_id for img_id in gt_image_np_map.keys() if img_id in gt_image_np_ann_map and gt_image_np_ann_map[img_id]]\n",
184
+ "negativeNPs = [img_id for img_id in gt_image_np_map.keys() if img_id not in gt_image_np_ann_map or not gt_image_np_ann_map[img_id]]\n",
185
+ "\n",
186
+ "num_image_nps_to_show = 10\n",
187
+ "fig, axes = plt.subplots(num_image_nps_to_show, 3, figsize=(15, 5 * num_image_nps_to_show))\n",
188
+ "for idx in range(num_image_nps_to_show):\n",
189
+ " rand_idx = np.random.randint(len(positiveNPs))\n",
190
+ " image_id = positiveNPs[rand_idx]\n",
191
+ " noun_phrase = gt_image_np_map[image_id][\"text_input\"]\n",
192
+ " img_rel_path = gt_image_np_map[image_id][\"file_name\"]\n",
193
+ " full_path = os.path.join(IMG_DIR, f\"{img_rel_path}\")\n",
194
+ " img = cv2.imread(full_path)\n",
195
+ " img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n",
196
+ " gt_annotation = gt_image_np_ann_map[image_id]\n",
197
+ "\n",
198
+ " def display_image_in_subplot(img, axes, row, col, title=\"\"):\n",
199
+ " axes[row, col].imshow(img)\n",
200
+ " axes[row, col].set_title(title)\n",
201
+ " axes[row, col].axis('off')\n",
202
+ "\n",
203
+ "\n",
204
+ " noun_phrases = [noun_phrase]\n",
205
+ " annot_masks = [mask_util.decode(ann[\"segmentation\"]) for ann in gt_annotation]\n",
206
+ "\n",
207
+ " # Show the image\n",
208
+ " display_image_in_subplot(img, axes, idx, 0, f\"{noun_phrase}\")\n",
209
+ "\n",
210
+ " # Show all masks over a white background\n",
211
+ " all_masks = utils.draw_masks_to_frame(\n",
212
+ " frame=np.ones_like(img)*255, masks=annot_masks, colors=COLORS[: len(annot_masks)]\n",
213
+ " )\n",
214
+ " display_image_in_subplot(all_masks, axes, idx, 1, f\"{noun_phrase} - Masks only\")\n",
215
+ "\n",
216
+ " # Show masks overlaid on the image\n",
217
+ " masked_frame = utils.draw_masks_to_frame(\n",
218
+ " frame=img, masks=annot_masks, colors=COLORS[: len(annot_masks)]\n",
219
+ " )\n",
220
+ " display_image_in_subplot(masked_frame, axes, idx, 2, f\"{noun_phrase} - Masks overlaid\")\n"
221
+ ]
222
+ },
223
+ {
224
+ "cell_type": "code",
225
+ "execution_count": null,
226
+ "id": "84a20e0e",
227
+ "metadata": {},
228
+ "outputs": [],
229
+ "source": []
230
+ }
231
+ ],
232
+ "metadata": {
233
+ "fileHeader": "",
234
+ "fileUid": "a2cedcd3-26e1-430d-b718-764d51077f86",
235
+ "isAdHoc": false,
236
+ "kernelspec": {
237
+ "display_name": "Python 3 (ipykernel)",
238
+ "language": "python",
239
+ "name": "python3"
240
+ },
241
+ "language_info": {
242
+ "codemirror_mode": {
243
+ "name": "ipython",
244
+ "version": 3
245
+ },
246
+ "file_extension": ".py",
247
+ "mimetype": "text/x-python",
248
+ "name": "python",
249
+ "nbconvert_exporter": "python",
250
+ "pygments_lexer": "ipython3",
251
+ "version": "3.10.13"
252
+ }
253
+ },
254
+ "nbformat": 4,
255
+ "nbformat_minor": 2
256
+ }
third_party/GraspGen/sam3/examples/saco_veval_eval_example.ipynb ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "0e0d2e74",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "import json\n",
11
+ "import os\n",
12
+ "\n",
13
+ "from sam3.eval.saco_veval_eval import VEvalEvaluator"
14
+ ]
15
+ },
16
+ {
17
+ "cell_type": "code",
18
+ "execution_count": null,
19
+ "id": "b31ab5d3",
20
+ "metadata": {},
21
+ "outputs": [],
22
+ "source": [
23
+ "DATASETS_TO_EVAL = [\n",
24
+ " \"saco_veval_sav_test\",\n",
25
+ " \"saco_veval_yt1b_test\",\n",
26
+ " \"saco_veval_smartglasses_test\",\n",
27
+ "]\n",
28
+ "# Update to the directory where the GT annotation and PRED files exist\n",
29
+ "GT_DIR = None # PUT YOUR ANNOTATION PATH HERE\n",
30
+ "PRED_DIR = None # PUT YOUR IMAGE PATH HERE"
31
+ ]
32
+ },
33
+ {
34
+ "cell_type": "code",
35
+ "execution_count": null,
36
+ "id": "3a602fef",
37
+ "metadata": {},
38
+ "outputs": [],
39
+ "source": [
40
+ "all_eval_res = {}\n",
41
+ "for dataset_name in DATASETS_TO_EVAL:\n",
42
+ " gt_annot_file = os.path.join(GT_DIR, dataset_name + \".json\")\n",
43
+ " pred_file = os.path.join(PRED_DIR, dataset_name + \"_preds.json\")\n",
44
+ " eval_res_file = os.path.join(PRED_DIR, dataset_name + \"_eval_res.json\")\n",
45
+ "\n",
46
+ " if os.path.exists(eval_res_file):\n",
47
+ " with open(eval_res_file, \"r\") as f:\n",
48
+ " eval_res = json.load(f)\n",
49
+ " else:\n",
50
+ " # Alternatively, we can run the evaluator offline first\n",
51
+ " # by leveraging sam3/eval/saco_veval_eval.py\n",
52
+ " print(f\"=== Running evaluation for Pred {pred_file} vs GT {gt_annot_file} ===\")\n",
53
+ " veval_evaluator = VEvalEvaluator(\n",
54
+ " gt_annot_file=gt_annot_file, eval_res_file=eval_res_file\n",
55
+ " )\n",
56
+ " eval_res = veval_evaluator.run_eval(pred_file=pred_file)\n",
57
+ " print(f\"=== Results saved to {eval_res_file} ===\")\n",
58
+ "\n",
59
+ " all_eval_res[dataset_name] = eval_res"
60
+ ]
61
+ },
62
+ {
63
+ "cell_type": "code",
64
+ "execution_count": null,
65
+ "id": "a6dbec47",
66
+ "metadata": {},
67
+ "outputs": [],
68
+ "source": [
69
+ "REPORT_METRICS = {\n",
70
+ " \"video_mask_demo_cgf1_micro_50_95\": \"cgf1\",\n",
71
+ " \"video_mask_all_phrase_HOTA\": \"pHOTA\",\n",
72
+ "}"
73
+ ]
74
+ },
75
+ {
76
+ "cell_type": "code",
77
+ "execution_count": null,
78
+ "id": "cc28d29f",
79
+ "metadata": {},
80
+ "outputs": [],
81
+ "source": [
82
+ "res_to_print = []\n",
83
+ "for dataset_name in DATASETS_TO_EVAL:\n",
84
+ " eval_res = all_eval_res[dataset_name]\n",
85
+ " row = [dataset_name]\n",
86
+ " for metric_k, metric_v in REPORT_METRICS.items():\n",
87
+ " row.append(eval_res[\"dataset_results\"][metric_k])\n",
88
+ " res_to_print.append(row)\n",
89
+ "\n",
90
+ "# Print dataset header (each dataset spans 2 metrics: 13 + 3 + 13 = 29 chars)\n",
91
+ "print(\"| \" + \" | \".join(f\"{ds:^29}\" for ds in DATASETS_TO_EVAL) + \" |\")\n",
92
+ "\n",
93
+ "# Print metric header\n",
94
+ "metrics = list(REPORT_METRICS.values())\n",
95
+ "print(\"| \" + \" | \".join(f\"{m:^13}\" for _ in DATASETS_TO_EVAL for m in metrics) + \" |\")\n",
96
+ "\n",
97
+ "# Print eval results\n",
98
+ "values = []\n",
99
+ "for row in res_to_print:\n",
100
+ " values.extend([f\"{v * 100:^13.1f}\" for v in row[1:]])\n",
101
+ "print(\"| \" + \" | \".join(values) + \" |\")"
102
+ ]
103
+ },
104
+ {
105
+ "cell_type": "code",
106
+ "execution_count": null,
107
+ "id": "9976908b",
108
+ "metadata": {},
109
+ "outputs": [],
110
+ "source": []
111
+ }
112
+ ],
113
+ "metadata": {
114
+ "fileHeader": "",
115
+ "fileUid": "bdaa3851-85de-435f-9582-efb46951a1d0",
116
+ "isAdHoc": false,
117
+ "kernelspec": {
118
+ "display_name": "Python 3 (ipykernel)",
119
+ "language": "python",
120
+ "name": "python3"
121
+ },
122
+ "language_info": {
123
+ "codemirror_mode": {
124
+ "name": "ipython",
125
+ "version": 3
126
+ },
127
+ "file_extension": ".py",
128
+ "mimetype": "text/x-python",
129
+ "name": "python",
130
+ "nbconvert_exporter": "python",
131
+ "pygments_lexer": "ipython3",
132
+ "version": "3.10.13"
133
+ }
134
+ },
135
+ "nbformat": 4,
136
+ "nbformat_minor": 2
137
+ }
third_party/GraspGen/sam3/examples/saco_veval_vis_example.ipynb ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "37048f21",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "# Copyright (c) Meta Platforms, Inc. and affiliates."
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "code",
15
+ "execution_count": null,
16
+ "id": "154d8663",
17
+ "metadata": {},
18
+ "outputs": [],
19
+ "source": [
20
+ "using_colab = False"
21
+ ]
22
+ },
23
+ {
24
+ "cell_type": "code",
25
+ "execution_count": null,
26
+ "id": "b85d99d9",
27
+ "metadata": {},
28
+ "outputs": [],
29
+ "source": [
30
+ "if using_colab:\n",
31
+ " import torch\n",
32
+ " import torchvision\n",
33
+ " print(\"PyTorch version:\", torch.__version__)\n",
34
+ " print(\"Torchvision version:\", torchvision.__version__)\n",
35
+ " print(\"CUDA is available:\", torch.cuda.is_available())\n",
36
+ " import sys\n",
37
+ " !{sys.executable} -m pip install opencv-python matplotlib scikit-learn\n",
38
+ " !{sys.executable} -m pip install 'git+https://github.com/facebookresearch/sam3.git'"
39
+ ]
40
+ },
41
+ {
42
+ "cell_type": "code",
43
+ "execution_count": null,
44
+ "id": "da21a3bc",
45
+ "metadata": {},
46
+ "outputs": [],
47
+ "source": [
48
+ "import os\n",
49
+ "from glob import glob\n",
50
+ "\n",
51
+ "import numpy as np\n",
52
+ "import utils\n",
53
+ "\n",
54
+ "from matplotlib import pyplot as plt\n",
55
+ "\n",
56
+ "COLORS = utils.pascal_color_map()[1:]"
57
+ ]
58
+ },
59
+ {
60
+ "cell_type": "markdown",
61
+ "id": "57e85e7e",
62
+ "metadata": {},
63
+ "source": [
64
+ "1. Load the data"
65
+ ]
66
+ },
67
+ {
68
+ "cell_type": "code",
69
+ "execution_count": null,
70
+ "id": "a796734e",
71
+ "metadata": {},
72
+ "outputs": [],
73
+ "source": [
74
+ "# Preapre the data path\n",
75
+ "DATA_DIR = \"./sam3_saco_veval_data\" # PUT YOUR DATA PATH HERE\n",
76
+ "ANNOT_DIR = os.path.join(DATA_DIR, \"annotation\")\n",
77
+ "\n",
78
+ "# Load the SACO/Veval annotation files\n",
79
+ "annot_file_list = glob(os.path.join(ANNOT_DIR, \"*veval*.json\"))\n",
80
+ "annot_dfs = utils.get_annot_dfs(file_list=annot_file_list)"
81
+ ]
82
+ },
83
+ {
84
+ "cell_type": "markdown",
85
+ "id": "74bf92b1",
86
+ "metadata": {},
87
+ "source": [
88
+ "Show the annotation files being loaded"
89
+ ]
90
+ },
91
+ {
92
+ "cell_type": "code",
93
+ "execution_count": null,
94
+ "id": "a95620ec",
95
+ "metadata": {},
96
+ "outputs": [],
97
+ "source": [
98
+ "annot_dfs.keys()"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "markdown",
103
+ "id": "5ce211d3",
104
+ "metadata": {},
105
+ "source": [
106
+ "2. Examples of the data format"
107
+ ]
108
+ },
109
+ {
110
+ "cell_type": "code",
111
+ "execution_count": null,
112
+ "id": "6ba749db",
113
+ "metadata": {},
114
+ "outputs": [],
115
+ "source": [
116
+ "annot_dfs[\"saco_veval_yt1b_val\"].keys()"
117
+ ]
118
+ },
119
+ {
120
+ "cell_type": "code",
121
+ "execution_count": null,
122
+ "id": "4b6dc186",
123
+ "metadata": {},
124
+ "outputs": [],
125
+ "source": [
126
+ "annot_dfs[\"saco_veval_yt1b_val\"][\"info\"]"
127
+ ]
128
+ },
129
+ {
130
+ "cell_type": "code",
131
+ "execution_count": null,
132
+ "id": "c41091b3",
133
+ "metadata": {},
134
+ "outputs": [],
135
+ "source": [
136
+ "annot_dfs[\"saco_veval_yt1b_val\"][\"videos\"].head(3)"
137
+ ]
138
+ },
139
+ {
140
+ "cell_type": "code",
141
+ "execution_count": null,
142
+ "id": "a7df5771",
143
+ "metadata": {},
144
+ "outputs": [],
145
+ "source": [
146
+ "annot_dfs[\"saco_veval_yt1b_val\"][\"annotations\"].head(3)"
147
+ ]
148
+ },
149
+ {
150
+ "cell_type": "code",
151
+ "execution_count": null,
152
+ "id": "24d2861c",
153
+ "metadata": {},
154
+ "outputs": [],
155
+ "source": [
156
+ "annot_dfs[\"saco_veval_yt1b_val\"][\"categories\"].head(3)"
157
+ ]
158
+ },
159
+ {
160
+ "cell_type": "code",
161
+ "execution_count": null,
162
+ "id": "f9f98f27",
163
+ "metadata": {},
164
+ "outputs": [],
165
+ "source": [
166
+ "annot_dfs[\"saco_veval_yt1b_val\"][\"video_np_pairs\"].head(3)"
167
+ ]
168
+ },
169
+ {
170
+ "cell_type": "markdown",
171
+ "id": "5673a63f",
172
+ "metadata": {},
173
+ "source": [
174
+ "3. Visualize the data"
175
+ ]
176
+ },
177
+ {
178
+ "cell_type": "code",
179
+ "execution_count": null,
180
+ "id": "da827d09",
181
+ "metadata": {},
182
+ "outputs": [],
183
+ "source": [
184
+ "# Select a target dataset\n",
185
+ "target_dataset_name = \"saco_veval_yt1b_val\"\n",
186
+ "\n",
187
+ "# visualize a random positive video-np pair\n",
188
+ "df_pairs = annot_dfs[target_dataset_name][\"video_np_pairs\"]\n",
189
+ "df_positive_pairs = df_pairs[df_pairs.num_masklets > 0]\n",
190
+ "rand_idx = np.random.randint(len(df_positive_pairs))\n",
191
+ "pair_row = df_positive_pairs.iloc[rand_idx]\n",
192
+ "video_id = pair_row.video_id\n",
193
+ "noun_phrase = pair_row.noun_phrase\n",
194
+ "print(f\"Randomly selected video-np pair: video_id={video_id}, noun_phrase={noun_phrase}\")\n",
195
+ "\n",
196
+ "def display_image_in_subplot(img, axes, row, col, title=\"\"):\n",
197
+ " axes[row, col].imshow(img)\n",
198
+ " axes[row, col].set_title(title)\n",
199
+ " axes[row, col].axis('off')\n",
200
+ "\n",
201
+ "num_frames_to_show = 5 # Number of frames to show per dataset\n",
202
+ "every_n_frames = 4 # Interval between frames to show\n",
203
+ "\n",
204
+ "fig, axes = plt.subplots(num_frames_to_show, 3, figsize=(15, 5 * num_frames_to_show))\n",
205
+ "\n",
206
+ "for idx in range(0, num_frames_to_show):\n",
207
+ " sampled_frame_idx = idx * every_n_frames\n",
208
+ " print(f\"Reading annotations for frame {sampled_frame_idx}\")\n",
209
+ " # Get the frame and the corresponding masks and noun phrases\n",
210
+ " frame, annot_masks, annot_noun_phrases = utils.get_all_annotations_for_frame(\n",
211
+ " annot_dfs[target_dataset_name], video_id=video_id, frame_idx=sampled_frame_idx, data_dir=DATA_DIR, dataset=target_dataset_name\n",
212
+ " )\n",
213
+ " # Filter masks and noun phrases by the selected noun phrase\n",
214
+ " annot_masks = [m for m, np in zip(annot_masks, annot_noun_phrases) if np == noun_phrase]\n",
215
+ "\n",
216
+ " # Show the frame\n",
217
+ " display_image_in_subplot(frame, axes, idx, 0, f\"{target_dataset_name} - {noun_phrase} - Frame {sampled_frame_idx}\")\n",
218
+ "\n",
219
+ " # Show the annotated masks\n",
220
+ " if annot_masks is None:\n",
221
+ " print(f\"No masks found for video_id {video_id} at frame {sampled_frame_idx}\")\n",
222
+ " else:\n",
223
+ " # Show all masks over a white background\n",
224
+ " all_masks = utils.draw_masks_to_frame(\n",
225
+ " frame=np.ones_like(frame)*255, masks=annot_masks, colors=COLORS[: len(annot_masks)]\n",
226
+ " )\n",
227
+ " display_image_in_subplot(all_masks, axes, idx, 1, f\"{target_dataset_name} - {noun_phrase} - Frame {sampled_frame_idx} - Masks\")\n",
228
+ " \n",
229
+ " # Show masks overlaid on the frame\n",
230
+ " masked_frame = utils.draw_masks_to_frame(\n",
231
+ " frame=frame, masks=annot_masks, colors=COLORS[: len(annot_masks)]\n",
232
+ " )\n",
233
+ " display_image_in_subplot(masked_frame, axes, idx, 2, f\"Dataset: {target_dataset_name} - {noun_phrase} - Frame {sampled_frame_idx} - Masks overlaid\")\n",
234
+ "\n",
235
+ "plt.tight_layout()\n",
236
+ "plt.show()"
237
+ ]
238
+ },
239
+ {
240
+ "cell_type": "code",
241
+ "execution_count": null,
242
+ "id": "a2a23152",
243
+ "metadata": {},
244
+ "outputs": [],
245
+ "source": []
246
+ }
247
+ ],
248
+ "metadata": {
249
+ "kernelspec": {
250
+ "display_name": "Python 3 (ipykernel)",
251
+ "language": "python",
252
+ "name": "python3"
253
+ },
254
+ "language_info": {
255
+ "codemirror_mode": {
256
+ "name": "ipython",
257
+ "version": 3
258
+ },
259
+ "file_extension": ".py",
260
+ "mimetype": "text/x-python",
261
+ "name": "python",
262
+ "nbconvert_exporter": "python",
263
+ "pygments_lexer": "ipython3",
264
+ "version": "3.10.13"
265
+ }
266
+ },
267
+ "nbformat": 4,
268
+ "nbformat_minor": 5
269
+ }
third_party/GraspGen/sam3/examples/sam3_agent.ipynb ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "metadata": {},
7
+ "outputs": [],
8
+ "source": [
9
+ "# Copyright (c) Meta Platforms, Inc. and affiliates."
10
+ ]
11
+ },
12
+ {
13
+ "cell_type": "markdown",
14
+ "metadata": {},
15
+ "source": [
16
+ "# SAM 3 Agent"
17
+ ]
18
+ },
19
+ {
20
+ "cell_type": "markdown",
21
+ "metadata": {},
22
+ "source": [
23
+ "This notebook shows an example of how an MLLM can use SAM 3 as a tool, i.e., \"SAM 3 Agent\", to segment more complex text queries such as \"the leftmost child wearing blue vest\"."
24
+ ]
25
+ },
26
+ {
27
+ "cell_type": "markdown",
28
+ "metadata": {},
29
+ "source": [
30
+ "## Env Setup"
31
+ ]
32
+ },
33
+ {
34
+ "cell_type": "markdown",
35
+ "metadata": {},
36
+ "source": [
37
+ "First install `sam3` in your environment using the [installation instructions](https://github.com/facebookresearch/sam3?tab=readme-ov-file#installation) in the repository."
38
+ ]
39
+ },
40
+ {
41
+ "cell_type": "code",
42
+ "execution_count": null,
43
+ "metadata": {},
44
+ "outputs": [],
45
+ "source": [
46
+ "import torch\n",
47
+ "# turn on tfloat32 for Ampere GPUs\n",
48
+ "# https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices\n",
49
+ "torch.backends.cuda.matmul.allow_tf32 = True\n",
50
+ "torch.backends.cudnn.allow_tf32 = True\n",
51
+ "\n",
52
+ "# use bfloat16 for the entire notebook. If your card doesn't support it, try float16 instead\n",
53
+ "torch.autocast(\"cuda\", dtype=torch.bfloat16).__enter__()\n",
54
+ "\n",
55
+ "# inference mode for the whole notebook. Disable if you need gradients\n",
56
+ "torch.inference_mode().__enter__()"
57
+ ]
58
+ },
59
+ {
60
+ "cell_type": "code",
61
+ "execution_count": null,
62
+ "metadata": {},
63
+ "outputs": [],
64
+ "source": [
65
+ "import os\n",
66
+ "\n",
67
+ "SAM3_ROOT = os.path.dirname(os.getcwd())\n",
68
+ "os.chdir(SAM3_ROOT)\n",
69
+ "\n",
70
+ "# setup GPU to use - A single GPU is good with the purpose of this demo\n",
71
+ "os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n",
72
+ "_ = os.system(\"nvidia-smi\")"
73
+ ]
74
+ },
75
+ {
76
+ "cell_type": "markdown",
77
+ "metadata": {},
78
+ "source": [
79
+ "## Build SAM3 Model"
80
+ ]
81
+ },
82
+ {
83
+ "cell_type": "code",
84
+ "execution_count": null,
85
+ "metadata": {},
86
+ "outputs": [],
87
+ "source": [
88
+ "import sam3\n",
89
+ "from sam3 import build_sam3_image_model\n",
90
+ "from sam3.model.sam3_image_processor import Sam3Processor\n",
91
+ "\n",
92
+ "sam3_root = os.path.dirname(sam3.__file__)\n",
93
+ "bpe_path = f\"{sam3_root}/assets/bpe_simple_vocab_16e6.txt.gz\"\n",
94
+ "model = build_sam3_image_model(bpe_path=bpe_path)\n",
95
+ "processor = Sam3Processor(model, confidence_threshold=0.5)"
96
+ ]
97
+ },
98
+ {
99
+ "cell_type": "markdown",
100
+ "metadata": {},
101
+ "source": [
102
+ "## LLM Setup\n",
103
+ "\n",
104
+ "Config which MLLM to use, it can either be a model served by vLLM that you launch from your own machine or a model is served via external API. If you want to using a vLLM model, we also provided insturctions below."
105
+ ]
106
+ },
107
+ {
108
+ "cell_type": "code",
109
+ "execution_count": null,
110
+ "metadata": {},
111
+ "outputs": [],
112
+ "source": [
113
+ "LLM_CONFIGS = {\n",
114
+ " # vLLM-served models\n",
115
+ " \"qwen3_vl_8b_thinking\": {\n",
116
+ " \"provider\": \"vllm\",\n",
117
+ " \"model\": \"Qwen/Qwen3-VL-8B-Thinking\",\n",
118
+ " },\n",
119
+ " # models served via external APIs\n",
120
+ " # add your own\n",
121
+ "}\n",
122
+ "\n",
123
+ "model = \"qwen3_vl_8b_thinking\"\n",
124
+ "LLM_API_KEY = \"DUMMY_API_KEY\"\n",
125
+ "\n",
126
+ "llm_config = LLM_CONFIGS[model]\n",
127
+ "llm_config[\"api_key\"] = LLM_API_KEY\n",
128
+ "llm_config[\"name\"] = model\n",
129
+ "\n",
130
+ "# setup API endpoint\n",
131
+ "if llm_config[\"provider\"] == \"vllm\":\n",
132
+ " LLM_SERVER_URL = \"http://0.0.0.0:8001/v1\" # replace this with your vLLM server address as needed\n",
133
+ "else:\n",
134
+ " LLM_SERVER_URL = llm_config[\"base_url\"]"
135
+ ]
136
+ },
137
+ {
138
+ "cell_type": "markdown",
139
+ "metadata": {},
140
+ "source": [
141
+ "### Setup vLLM server \n",
142
+ "This step is only required if you are using a model served by vLLM, skip this step if you are calling LLM using an API like Gemini and GPT.\n",
143
+ "\n",
144
+ "* Install vLLM (in a separate conda env from SAM 3 to avoid dependency conflicts).\n",
145
+ " ```bash\n",
146
+ " conda create -n vllm python=3.12\n",
147
+ " pip install vllm --extra-index-url https://download.pytorch.org/whl/cu128\n",
148
+ " ```\n",
149
+ "* Start vLLM server on the same machine of this notebook\n",
150
+ " ```bash\n",
151
+ " # qwen 3 VL 8B thinking\n",
152
+ " vllm serve Qwen/Qwen3-VL-8B-Thinking --tensor-parallel-size 4 --allowed-local-media-path / --enforce-eager --port 8001\n",
153
+ " ```"
154
+ ]
155
+ },
156
+ {
157
+ "cell_type": "markdown",
158
+ "metadata": {},
159
+ "source": [
160
+ "## Run SAM3 Agent Inference"
161
+ ]
162
+ },
163
+ {
164
+ "cell_type": "code",
165
+ "execution_count": null,
166
+ "metadata": {},
167
+ "outputs": [],
168
+ "source": [
169
+ "from functools import partial\n",
170
+ "from IPython.display import display, Image\n",
171
+ "from sam3.agent.client_llm import send_generate_request as send_generate_request_orig\n",
172
+ "from sam3.agent.client_sam3 import call_sam_service as call_sam_service_orig\n",
173
+ "from sam3.agent.inference import run_single_image_inference"
174
+ ]
175
+ },
176
+ {
177
+ "cell_type": "code",
178
+ "execution_count": null,
179
+ "metadata": {
180
+ "output": {
181
+ "id": 689664053567678,
182
+ "loadingStatus": "loaded"
183
+ }
184
+ },
185
+ "outputs": [],
186
+ "source": [
187
+ "# prepare input args and run single image inference\n",
188
+ "image = \"assets/images/test_image.jpg\"\n",
189
+ "prompt = \"the leftmost child wearing blue vest\"\n",
190
+ "image = os.path.abspath(image)\n",
191
+ "send_generate_request = partial(send_generate_request_orig, server_url=LLM_SERVER_URL, model=llm_config[\"model\"], api_key=llm_config[\"api_key\"])\n",
192
+ "call_sam_service = partial(call_sam_service_orig, sam3_processor=processor)\n",
193
+ "output_image_path = run_single_image_inference(\n",
194
+ " image, prompt, llm_config, send_generate_request, call_sam_service,\n",
195
+ " debug=True, output_dir=\"agent_output\"\n",
196
+ ")\n",
197
+ "\n",
198
+ "# display output\n",
199
+ "if output_image_path is not None:\n",
200
+ " display(Image(filename=output_image_path))"
201
+ ]
202
+ },
203
+ {
204
+ "cell_type": "code",
205
+ "execution_count": null,
206
+ "metadata": {},
207
+ "outputs": [],
208
+ "source": []
209
+ },
210
+ {
211
+ "cell_type": "code",
212
+ "execution_count": null,
213
+ "metadata": {},
214
+ "outputs": [],
215
+ "source": []
216
+ }
217
+ ],
218
+ "metadata": {
219
+ "fileHeader": "",
220
+ "fileUid": "be59e249-6c09-4634-a9e7-1f06fd233c42",
221
+ "isAdHoc": false,
222
+ "kernelspec": {
223
+ "display_name": "Python 3 (ipykernel)",
224
+ "language": "python",
225
+ "name": "python3"
226
+ },
227
+ "language_info": {
228
+ "codemirror_mode": {
229
+ "name": "ipython",
230
+ "version": 3
231
+ },
232
+ "file_extension": ".py",
233
+ "mimetype": "text/x-python",
234
+ "name": "python",
235
+ "nbconvert_exporter": "python",
236
+ "pygments_lexer": "ipython3",
237
+ "version": "3.12.11"
238
+ }
239
+ },
240
+ "nbformat": 4,
241
+ "nbformat_minor": 2
242
+ }
third_party/GraspGen/sam3/examples/sam3_for_sam1_task_example.ipynb ADDED
@@ -0,0 +1,846 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "f400486b",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "# Copyright (c) Meta Platforms, Inc. and affiliates."
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "markdown",
15
+ "id": "a1ae39ff",
16
+ "metadata": {
17
+ "jp-MarkdownHeadingCollapsed": true
18
+ },
19
+ "source": [
20
+ "# Interactive Instance Segmentation using SAM 3"
21
+ ]
22
+ },
23
+ {
24
+ "cell_type": "markdown",
25
+ "id": "b4a4b25c",
26
+ "metadata": {},
27
+ "source": [
28
+ "Segment Anything Model 3 (SAM 3) predicts instance masks that indicate the desired object given geometric prompts (SAM 1 task).\n",
29
+ "The `SAM3Image` and `Sam3Processor` classes provide an easy interface to prompt the model. The user first sets an image using the `Sam3Processor.set_image` method, which computes the necessary image embeddings. Then, prompts can be provided via the `predict` method to efficiently predict masks from those prompts. The model can take as input both point and box prompts, as well as masks from the previous iteration of prediction.\n",
30
+ "\n",
31
+ "This notebook follows the SAM 2 API for interactive image segmentation.\n",
32
+ "\n",
33
+ "# <a target=\"_blank\" href=\"https://colab.research.google.com/github/facebookresearch/sam3/blob/main/notebooks/sam3_for_sam1_task_example.ipynb\">\n",
34
+ "# <img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/>\n",
35
+ "# </a>\n"
36
+ ]
37
+ },
38
+ {
39
+ "cell_type": "markdown",
40
+ "id": "644532a8",
41
+ "metadata": {},
42
+ "source": [
43
+ "## Environment Set-up"
44
+ ]
45
+ },
46
+ {
47
+ "cell_type": "markdown",
48
+ "id": "07fabfee",
49
+ "metadata": {},
50
+ "source": [
51
+ "First install `sam3` in your environment using the [installation instructions](https://github.com/facebookresearch/sam3?tab=readme-ov-file#installation) in the repository."
52
+ ]
53
+ },
54
+ {
55
+ "cell_type": "markdown",
56
+ "id": "0be845da",
57
+ "metadata": {},
58
+ "source": [
59
+ "## Set-up"
60
+ ]
61
+ },
62
+ {
63
+ "cell_type": "markdown",
64
+ "id": "33681dd1",
65
+ "metadata": {},
66
+ "source": [
67
+ "Necessary imports and helper functions for displaying points, boxes, and masks."
68
+ ]
69
+ },
70
+ {
71
+ "cell_type": "code",
72
+ "execution_count": null,
73
+ "id": "fe773ede",
74
+ "metadata": {},
75
+ "outputs": [],
76
+ "source": [
77
+ "using_colab = False"
78
+ ]
79
+ },
80
+ {
81
+ "cell_type": "code",
82
+ "execution_count": null,
83
+ "id": "79250a4e",
84
+ "metadata": {},
85
+ "outputs": [],
86
+ "source": [
87
+ "if using_colab:\n",
88
+ " import torch\n",
89
+ " import torchvision\n",
90
+ " print(\"PyTorch version:\", torch.__version__)\n",
91
+ " print(\"Torchvision version:\", torchvision.__version__)\n",
92
+ " print(\"CUDA is available:\", torch.cuda.is_available())\n",
93
+ " import sys\n",
94
+ " !{sys.executable} -m pip install opencv-python matplotlib scikit-learn\n",
95
+ " !{sys.executable} -m pip install 'git+https://github.com/facebookresearch/sam3.git'"
96
+ ]
97
+ },
98
+ {
99
+ "cell_type": "code",
100
+ "execution_count": null,
101
+ "id": "69b28288",
102
+ "metadata": {},
103
+ "outputs": [],
104
+ "source": [
105
+ "import os\n",
106
+ "# if using Apple MPS, fall back to CPU for unsupported ops\n",
107
+ "os.environ[\"PYTORCH_ENABLE_MPS_FALLBACK\"] = \"1\"\n",
108
+ "import numpy as np\n",
109
+ "import torch\n",
110
+ "import matplotlib.pyplot as plt\n",
111
+ "from PIL import Image\n",
112
+ "import sam3\n",
113
+ "sam3_root = os.path.join(os.path.dirname(sam3.__file__), \"..\")\n"
114
+ ]
115
+ },
116
+ {
117
+ "cell_type": "code",
118
+ "execution_count": null,
119
+ "id": "33a15e2f-c7e1-4e5d-862f-fcb751a60b89",
120
+ "metadata": {},
121
+ "outputs": [],
122
+ "source": [
123
+ "# select the device for computation\n",
124
+ "if torch.cuda.is_available():\n",
125
+ " device = torch.device(\"cuda\")\n",
126
+ "elif torch.backends.mps.is_available():\n",
127
+ " device = torch.device(\"mps\")\n",
128
+ "else:\n",
129
+ " device = torch.device(\"cpu\")\n",
130
+ "print(f\"using device: {device}\")\n",
131
+ "\n",
132
+ "if device.type == \"cuda\":\n",
133
+ " # use bfloat16 for the entire notebook\n",
134
+ " torch.autocast(\"cuda\", dtype=torch.bfloat16).__enter__()\n",
135
+ " # turn on tfloat32 for Ampere GPUs (https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices)\n",
136
+ " if torch.cuda.get_device_properties(0).major >= 8:\n",
137
+ " torch.backends.cuda.matmul.allow_tf32 = True\n",
138
+ " torch.backends.cudnn.allow_tf32 = True\n",
139
+ "elif device.type == \"mps\":\n",
140
+ " print(\n",
141
+ " \"\\nSupport for MPS devices is preliminary. SAM 3 is trained with CUDA and might \"\n",
142
+ " \"give numerically different outputs and sometimes degraded performance on MPS. \"\n",
143
+ " \"See e.g. https://github.com/pytorch/pytorch/issues/84936 for a discussion.\"\n",
144
+ " )"
145
+ ]
146
+ },
147
+ {
148
+ "cell_type": "code",
149
+ "execution_count": null,
150
+ "id": "29bc90d5",
151
+ "metadata": {},
152
+ "outputs": [],
153
+ "source": [
154
+ "np.random.seed(3)\n",
155
+ "\n",
156
+ "def show_mask(mask, ax, random_color=False, borders = True):\n",
157
+ " if random_color:\n",
158
+ " color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)\n",
159
+ " else:\n",
160
+ " color = np.array([30/255, 144/255, 255/255, 0.6])\n",
161
+ " h, w = mask.shape[-2:]\n",
162
+ " mask = mask.astype(np.uint8)\n",
163
+ " mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)\n",
164
+ " if borders:\n",
165
+ " import cv2\n",
166
+ " contours, _ = cv2.findContours(mask,cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) \n",
167
+ " # Try to smooth contours\n",
168
+ " contours = [cv2.approxPolyDP(contour, epsilon=0.01, closed=True) for contour in contours]\n",
169
+ " mask_image = cv2.drawContours(mask_image, contours, -1, (1, 1, 1, 0.5), thickness=2) \n",
170
+ " ax.imshow(mask_image)\n",
171
+ "\n",
172
+ "def show_points(coords, labels, ax, marker_size=375):\n",
173
+ " pos_points = coords[labels==1]\n",
174
+ " neg_points = coords[labels==0]\n",
175
+ " ax.scatter(pos_points[:, 0], pos_points[:, 1], color='green', marker='*', s=marker_size, edgecolor='white', linewidth=1.25)\n",
176
+ " ax.scatter(neg_points[:, 0], neg_points[:, 1], color='red', marker='*', s=marker_size, edgecolor='white', linewidth=1.25) \n",
177
+ "\n",
178
+ "def show_box(box, ax):\n",
179
+ " x0, y0 = box[0], box[1]\n",
180
+ " w, h = box[2] - box[0], box[3] - box[1]\n",
181
+ " ax.add_patch(plt.Rectangle((x0, y0), w, h, edgecolor='green', facecolor=(0, 0, 0, 0), lw=2)) \n",
182
+ "\n",
183
+ "def show_masks(image, masks, scores, point_coords=None, box_coords=None, input_labels=None, borders=True):\n",
184
+ " for i, (mask, score) in enumerate(zip(masks, scores)):\n",
185
+ " plt.figure(figsize=(10, 10))\n",
186
+ " plt.imshow(image)\n",
187
+ " show_mask(mask, plt.gca(), borders=borders)\n",
188
+ " if point_coords is not None:\n",
189
+ " assert input_labels is not None\n",
190
+ " show_points(point_coords, input_labels, plt.gca())\n",
191
+ " if box_coords is not None:\n",
192
+ " # boxes\n",
193
+ " show_box(box_coords, plt.gca())\n",
194
+ " if len(scores) > 1:\n",
195
+ " plt.title(f\"Mask {i+1}, Score: {score:.3f}\", fontsize=18)\n",
196
+ " plt.axis('off')\n",
197
+ " plt.show()"
198
+ ]
199
+ },
200
+ {
201
+ "cell_type": "markdown",
202
+ "id": "23842fb2",
203
+ "metadata": {},
204
+ "source": [
205
+ "## Example image"
206
+ ]
207
+ },
208
+ {
209
+ "cell_type": "code",
210
+ "execution_count": null,
211
+ "id": "3c2e4f6b",
212
+ "metadata": {},
213
+ "outputs": [],
214
+ "source": [
215
+ "image = Image.open(f\"{sam3_root}/assets/images/truck.jpg\")"
216
+ ]
217
+ },
218
+ {
219
+ "cell_type": "code",
220
+ "execution_count": null,
221
+ "id": "e30125fd",
222
+ "metadata": {},
223
+ "outputs": [],
224
+ "source": [
225
+ "plt.figure(figsize=(10, 10))\n",
226
+ "plt.imshow(image)\n",
227
+ "plt.axis('on')\n",
228
+ "plt.show()"
229
+ ]
230
+ },
231
+ {
232
+ "cell_type": "markdown",
233
+ "id": "98b228b8",
234
+ "metadata": {},
235
+ "source": [
236
+ "## Selecting objects with SAM 3"
237
+ ]
238
+ },
239
+ {
240
+ "cell_type": "markdown",
241
+ "id": "0bb1927b",
242
+ "metadata": {},
243
+ "source": [
244
+ "First, load the SAM 3 model. Running on CUDA and using the default model are recommended for best results."
245
+ ]
246
+ },
247
+ {
248
+ "cell_type": "code",
249
+ "execution_count": null,
250
+ "id": "7e28150b",
251
+ "metadata": {},
252
+ "outputs": [],
253
+ "source": [
254
+ "from sam3 import build_sam3_image_model\n",
255
+ "from sam3.model.sam3_image_processor import Sam3Processor\n",
256
+ "\n",
257
+ "bpe_path = f\"{sam3_root}/assets/bpe_simple_vocab_16e6.txt.gz\"\n",
258
+ "model = build_sam3_image_model(bpe_path=bpe_path, enable_inst_interactivity=True)\n"
259
+ ]
260
+ },
261
+ {
262
+ "cell_type": "markdown",
263
+ "id": "c925e829",
264
+ "metadata": {},
265
+ "source": [
266
+ "Process the image to produce an image embedding by calling `Sam3Processor.set_image`."
267
+ ]
268
+ },
269
+ {
270
+ "cell_type": "code",
271
+ "execution_count": null,
272
+ "id": "d95d48dd",
273
+ "metadata": {},
274
+ "outputs": [],
275
+ "source": [
276
+ "processor = Sam3Processor(model)\n",
277
+ "inference_state = processor.set_image(image)"
278
+ ]
279
+ },
280
+ {
281
+ "cell_type": "markdown",
282
+ "id": "d8fc7a46",
283
+ "metadata": {},
284
+ "source": [
285
+ "To select the truck, choose a point on it. Points are input to the model in (x,y) format and come with labels 1 (foreground point) or 0 (background point). Multiple points can be input; here we use only one. The chosen point will be shown as a star on the image."
286
+ ]
287
+ },
288
+ {
289
+ "cell_type": "code",
290
+ "execution_count": null,
291
+ "id": "5c69570c",
292
+ "metadata": {},
293
+ "outputs": [],
294
+ "source": [
295
+ "input_point = np.array([[520, 375]])\n",
296
+ "input_label = np.array([1])"
297
+ ]
298
+ },
299
+ {
300
+ "cell_type": "code",
301
+ "execution_count": null,
302
+ "id": "a91ba973",
303
+ "metadata": {},
304
+ "outputs": [],
305
+ "source": [
306
+ "plt.figure(figsize=(10, 10))\n",
307
+ "plt.imshow(image)\n",
308
+ "show_points(input_point, input_label, plt.gca())\n",
309
+ "plt.axis('on')\n",
310
+ "plt.show() "
311
+ ]
312
+ },
313
+ {
314
+ "cell_type": "markdown",
315
+ "id": "c765e952",
316
+ "metadata": {},
317
+ "source": [
318
+ "Predict with `SAM3Image.predict_inst`. The model returns masks, quality predictions for those masks, and low resolution mask logits that can be passed to the next iteration of prediction."
319
+ ]
320
+ },
321
+ {
322
+ "cell_type": "code",
323
+ "execution_count": null,
324
+ "id": "5373fd68",
325
+ "metadata": {},
326
+ "outputs": [],
327
+ "source": [
328
+ "masks, scores, logits = model.predict_inst(\n",
329
+ " inference_state,\n",
330
+ " point_coords=input_point,\n",
331
+ " point_labels=input_label,\n",
332
+ " multimask_output=True,\n",
333
+ ")\n",
334
+ "sorted_ind = np.argsort(scores)[::-1]\n",
335
+ "masks = masks[sorted_ind]\n",
336
+ "scores = scores[sorted_ind]\n",
337
+ "logits = logits[sorted_ind]"
338
+ ]
339
+ },
340
+ {
341
+ "cell_type": "markdown",
342
+ "id": "c7f0e938",
343
+ "metadata": {},
344
+ "source": [
345
+ "With `multimask_output=True` (the default setting), SAM 3 outputs 3 masks, where `scores` gives the model's own estimation of the quality of these masks. This setting is intended for ambiguous input prompts, and helps the model disambiguate different objects consistent with the prompt. When `False`, it will return a single mask. For ambiguous prompts such as a single point, it is recommended to use `multimask_output=True` even if only a single mask is desired; the best single mask can be chosen by picking the one with the highest score returned in `scores`. This will often result in a better mask."
346
+ ]
347
+ },
348
+ {
349
+ "cell_type": "code",
350
+ "execution_count": null,
351
+ "id": "47821187",
352
+ "metadata": {},
353
+ "outputs": [],
354
+ "source": [
355
+ "masks.shape # (number_of_masks) x H x W"
356
+ ]
357
+ },
358
+ {
359
+ "cell_type": "code",
360
+ "execution_count": null,
361
+ "id": "e9c227a6",
362
+ "metadata": {},
363
+ "outputs": [],
364
+ "source": [
365
+ "show_masks(image, masks, scores, point_coords=input_point, input_labels=input_label, borders=True)"
366
+ ]
367
+ },
368
+ {
369
+ "cell_type": "markdown",
370
+ "id": "3fa31f7c",
371
+ "metadata": {},
372
+ "source": [
373
+ "## Specifying a specific object with additional points"
374
+ ]
375
+ },
376
+ {
377
+ "cell_type": "markdown",
378
+ "id": "88d6d29a",
379
+ "metadata": {},
380
+ "source": [
381
+ "The single input point is ambiguous, and the model has returned multiple objects consistent with it. To obtain a single object, multiple points can be provided. If available, a mask from a previous iteration can also be supplied to the model to aid in prediction. When specifying a single object with multiple prompts, a single mask can be requested by setting `multimask_output=False`."
382
+ ]
383
+ },
384
+ {
385
+ "cell_type": "code",
386
+ "execution_count": null,
387
+ "id": "f6923b94",
388
+ "metadata": {},
389
+ "outputs": [],
390
+ "source": [
391
+ "input_point = np.array([[500, 375], [1125, 625]])\n",
392
+ "input_label = np.array([1, 1])\n",
393
+ "\n",
394
+ "mask_input = logits[np.argmax(scores), :, :] # Choose the model's best mask"
395
+ ]
396
+ },
397
+ {
398
+ "cell_type": "code",
399
+ "execution_count": null,
400
+ "id": "d98f96a1",
401
+ "metadata": {},
402
+ "outputs": [],
403
+ "source": [
404
+ "masks, scores, _ = model.predict_inst(\n",
405
+ " inference_state,\n",
406
+ " point_coords=input_point,\n",
407
+ " point_labels=input_label,\n",
408
+ " mask_input=mask_input[None, :, :],\n",
409
+ " multimask_output=False,\n",
410
+ ")"
411
+ ]
412
+ },
413
+ {
414
+ "cell_type": "code",
415
+ "execution_count": null,
416
+ "id": "0ce8b82f",
417
+ "metadata": {},
418
+ "outputs": [],
419
+ "source": [
420
+ "masks.shape"
421
+ ]
422
+ },
423
+ {
424
+ "cell_type": "code",
425
+ "execution_count": null,
426
+ "id": "e06d5c8d",
427
+ "metadata": {},
428
+ "outputs": [],
429
+ "source": [
430
+ "show_masks(image, masks, scores, point_coords=input_point, input_labels=input_label)"
431
+ ]
432
+ },
433
+ {
434
+ "cell_type": "markdown",
435
+ "id": "c93e2087",
436
+ "metadata": {},
437
+ "source": [
438
+ "To exclude the car and specify just the window, a background point (with label 0, here shown in red) can be supplied."
439
+ ]
440
+ },
441
+ {
442
+ "cell_type": "code",
443
+ "execution_count": null,
444
+ "id": "9a196f68",
445
+ "metadata": {},
446
+ "outputs": [],
447
+ "source": [
448
+ "input_point = np.array([[500, 375], [1125, 625]])\n",
449
+ "input_label = np.array([1, 0])\n",
450
+ "\n",
451
+ "mask_input = logits[np.argmax(scores), :, :] # Choose the model's best mask"
452
+ ]
453
+ },
454
+ {
455
+ "cell_type": "code",
456
+ "execution_count": null,
457
+ "id": "81a52282",
458
+ "metadata": {},
459
+ "outputs": [],
460
+ "source": [
461
+ "masks, scores, _ = model.predict_inst(\n",
462
+ " inference_state,\n",
463
+ " point_coords=input_point,\n",
464
+ " point_labels=input_label,\n",
465
+ " mask_input=mask_input[None, :, :],\n",
466
+ " multimask_output=False,\n",
467
+ ")"
468
+ ]
469
+ },
470
+ {
471
+ "cell_type": "code",
472
+ "execution_count": null,
473
+ "id": "bfca709f",
474
+ "metadata": {},
475
+ "outputs": [],
476
+ "source": [
477
+ "show_masks(image, masks, scores, point_coords=input_point, input_labels=input_label)"
478
+ ]
479
+ },
480
+ {
481
+ "cell_type": "markdown",
482
+ "id": "41e2d5a9",
483
+ "metadata": {},
484
+ "source": [
485
+ "## Specifying a specific object with a box"
486
+ ]
487
+ },
488
+ {
489
+ "cell_type": "markdown",
490
+ "id": "d61ca7ac",
491
+ "metadata": {},
492
+ "source": [
493
+ "The model can also take a box as input, provided in xyxy format."
494
+ ]
495
+ },
496
+ {
497
+ "cell_type": "code",
498
+ "execution_count": null,
499
+ "id": "8ea92a7b",
500
+ "metadata": {},
501
+ "outputs": [],
502
+ "source": [
503
+ "input_box = np.array([425, 600, 700, 875])"
504
+ ]
505
+ },
506
+ {
507
+ "cell_type": "code",
508
+ "execution_count": null,
509
+ "id": "b35a8814",
510
+ "metadata": {},
511
+ "outputs": [],
512
+ "source": [
513
+ "masks, scores, _ = model.predict_inst(\n",
514
+ " inference_state,\n",
515
+ " point_coords=None,\n",
516
+ " point_labels=None,\n",
517
+ " box=input_box[None, :],\n",
518
+ " multimask_output=False,\n",
519
+ ")"
520
+ ]
521
+ },
522
+ {
523
+ "cell_type": "code",
524
+ "execution_count": null,
525
+ "id": "3ffb4906",
526
+ "metadata": {},
527
+ "outputs": [],
528
+ "source": [
529
+ "show_masks(image, masks, scores, box_coords=input_box)"
530
+ ]
531
+ },
532
+ {
533
+ "cell_type": "markdown",
534
+ "id": "c1ed9f0a",
535
+ "metadata": {},
536
+ "source": [
537
+ "## Combining points and boxes"
538
+ ]
539
+ },
540
+ {
541
+ "cell_type": "markdown",
542
+ "id": "8455d1c5",
543
+ "metadata": {},
544
+ "source": [
545
+ "Points and boxes may be combined, just by including both types of prompts to the predictor. Here this can be used to select just the trucks's tire, instead of the entire wheel."
546
+ ]
547
+ },
548
+ {
549
+ "cell_type": "code",
550
+ "execution_count": null,
551
+ "id": "90e2e547",
552
+ "metadata": {},
553
+ "outputs": [],
554
+ "source": [
555
+ "input_box = np.array([425, 600, 700, 875])\n",
556
+ "input_point = np.array([[575, 750]])\n",
557
+ "input_label = np.array([0])"
558
+ ]
559
+ },
560
+ {
561
+ "cell_type": "code",
562
+ "execution_count": null,
563
+ "id": "6956d8c4",
564
+ "metadata": {},
565
+ "outputs": [],
566
+ "source": [
567
+ "masks, scores, logits = model.predict_inst(\n",
568
+ " inference_state,\n",
569
+ " point_coords=input_point,\n",
570
+ " point_labels=input_label,\n",
571
+ " box=input_box,\n",
572
+ " multimask_output=False,\n",
573
+ ")"
574
+ ]
575
+ },
576
+ {
577
+ "cell_type": "code",
578
+ "execution_count": null,
579
+ "id": "eb519a31",
580
+ "metadata": {},
581
+ "outputs": [],
582
+ "source": [
583
+ "show_masks(image, masks, scores, box_coords=input_box, point_coords=input_point, input_labels=input_label)"
584
+ ]
585
+ },
586
+ {
587
+ "cell_type": "markdown",
588
+ "id": "45ddbca3",
589
+ "metadata": {},
590
+ "source": [
591
+ "## Batched prompt inputs"
592
+ ]
593
+ },
594
+ {
595
+ "cell_type": "markdown",
596
+ "id": "df6f18a0",
597
+ "metadata": {},
598
+ "source": [
599
+ "`SAM3Image` can take multiple input prompts for the same image, using `predict_inst` method. For example, imagine we have several box outputs from an object detector."
600
+ ]
601
+ },
602
+ {
603
+ "cell_type": "code",
604
+ "execution_count": null,
605
+ "id": "0a06681b",
606
+ "metadata": {},
607
+ "outputs": [],
608
+ "source": [
609
+ "input_boxes = np.array([\n",
610
+ " [75, 275, 1725, 850],\n",
611
+ " [425, 600, 700, 875],\n",
612
+ " [1375, 550, 1650, 800],\n",
613
+ " [1240, 675, 1400, 750],\n",
614
+ "])"
615
+ ]
616
+ },
617
+ {
618
+ "cell_type": "code",
619
+ "execution_count": null,
620
+ "id": "117521a3",
621
+ "metadata": {},
622
+ "outputs": [],
623
+ "source": [
624
+ "masks, scores, _ = model.predict_inst(\n",
625
+ " inference_state,\n",
626
+ " point_coords=None,\n",
627
+ " point_labels=None,\n",
628
+ " box=input_boxes,\n",
629
+ " multimask_output=False,\n",
630
+ ")"
631
+ ]
632
+ },
633
+ {
634
+ "cell_type": "code",
635
+ "execution_count": null,
636
+ "id": "6a8f5d49",
637
+ "metadata": {},
638
+ "outputs": [],
639
+ "source": [
640
+ "masks.shape # (batch_size) x (num_predicted_masks_per_input) x H x W"
641
+ ]
642
+ },
643
+ {
644
+ "cell_type": "code",
645
+ "execution_count": null,
646
+ "id": "c00c3681",
647
+ "metadata": {},
648
+ "outputs": [],
649
+ "source": [
650
+ "plt.figure(figsize=(10, 10))\n",
651
+ "plt.imshow(image)\n",
652
+ "for mask in masks:\n",
653
+ " show_mask(mask.squeeze(0), plt.gca(), random_color=True)\n",
654
+ "for box in input_boxes:\n",
655
+ " show_box(box, plt.gca())\n",
656
+ "plt.axis('off')\n",
657
+ "plt.show()"
658
+ ]
659
+ },
660
+ {
661
+ "cell_type": "markdown",
662
+ "id": "b9a27b5d",
663
+ "metadata": {},
664
+ "source": [
665
+ "## End-to-end batched inference\n",
666
+ "If all prompts are available in advance, it is possible to run SAM 3 directly in an end-to-end fashion. This also allows batching over images."
667
+ ]
668
+ },
669
+ {
670
+ "cell_type": "code",
671
+ "execution_count": null,
672
+ "id": "d485f75b",
673
+ "metadata": {},
674
+ "outputs": [],
675
+ "source": [
676
+ "image1 = image # truck.jpg from above\n",
677
+ "image1_boxes = np.array([\n",
678
+ " [75, 275, 1725, 850],\n",
679
+ " [425, 600, 700, 875],\n",
680
+ " [1375, 550, 1650, 800],\n",
681
+ " [1240, 675, 1400, 750],\n",
682
+ "])\n",
683
+ "\n",
684
+ "image2 = Image.open(f\"{sam3_root}/assets/images/groceries.jpg\")\n",
685
+ "image2_boxes = np.array([\n",
686
+ " [450, 170, 520, 350],\n",
687
+ " [350, 190, 450, 350],\n",
688
+ " [500, 170, 580, 350],\n",
689
+ " [580, 170, 640, 350],\n",
690
+ "])\n",
691
+ "\n",
692
+ "img_batch = [image1, image2]\n",
693
+ "boxes_batch = [image1_boxes, image2_boxes]"
694
+ ]
695
+ },
696
+ {
697
+ "cell_type": "code",
698
+ "execution_count": null,
699
+ "id": "47932c99",
700
+ "metadata": {},
701
+ "outputs": [],
702
+ "source": [
703
+ "inference_state = processor.set_image_batch(img_batch)"
704
+ ]
705
+ },
706
+ {
707
+ "cell_type": "code",
708
+ "execution_count": null,
709
+ "id": "97af3c54",
710
+ "metadata": {},
711
+ "outputs": [],
712
+ "source": [
713
+ "masks_batch, scores_batch, _ = model.predict_inst_batch(\n",
714
+ " inference_state,\n",
715
+ " None,\n",
716
+ " None, \n",
717
+ " box_batch=boxes_batch, \n",
718
+ " multimask_output=False\n",
719
+ ")"
720
+ ]
721
+ },
722
+ {
723
+ "cell_type": "code",
724
+ "execution_count": null,
725
+ "id": "226df881",
726
+ "metadata": {},
727
+ "outputs": [],
728
+ "source": [
729
+ "for image, boxes, masks in zip(img_batch, boxes_batch, masks_batch):\n",
730
+ " plt.figure(figsize=(10, 10))\n",
731
+ " plt.imshow(image) \n",
732
+ " for mask in masks:\n",
733
+ " show_mask(mask.squeeze(0), plt.gca(), random_color=True)\n",
734
+ " for box in boxes:\n",
735
+ " show_box(box, plt.gca())"
736
+ ]
737
+ },
738
+ {
739
+ "cell_type": "markdown",
740
+ "id": "46f30085",
741
+ "metadata": {},
742
+ "source": [
743
+ "Similarly, we can have a batch of point prompts defined over a batch of images"
744
+ ]
745
+ },
746
+ {
747
+ "cell_type": "code",
748
+ "execution_count": null,
749
+ "id": "1ab929fc",
750
+ "metadata": {},
751
+ "outputs": [],
752
+ "source": [
753
+ "image1 = image # truck.jpg from above\n",
754
+ "image1_pts = np.array([\n",
755
+ " [[500, 375]],\n",
756
+ " [[650, 750]]\n",
757
+ " ]) # Bx1x2 where B corresponds to number of objects \n",
758
+ "image1_labels = np.array([[1], [1]])\n",
759
+ "\n",
760
+ "image2_pts = np.array([\n",
761
+ " [[400, 300]],\n",
762
+ " [[630, 300]],\n",
763
+ "])\n",
764
+ "image2_labels = np.array([[1], [1]])\n",
765
+ "\n",
766
+ "pts_batch = [image1_pts, image2_pts]\n",
767
+ "labels_batch = [image1_labels, image2_labels]"
768
+ ]
769
+ },
770
+ {
771
+ "cell_type": "code",
772
+ "execution_count": null,
773
+ "id": "848f8287",
774
+ "metadata": {},
775
+ "outputs": [],
776
+ "source": [
777
+ "masks_batch, scores_batch, _ = model.predict_inst_batch(inference_state, pts_batch, labels_batch, box_batch=None, multimask_output=True)\n",
778
+ "\n",
779
+ "# Select the best single mask per object\n",
780
+ "best_masks = []\n",
781
+ "for masks, scores in zip(masks_batch,scores_batch):\n",
782
+ " best_masks.append(masks[range(len(masks)), np.argmax(scores, axis=-1)])"
783
+ ]
784
+ },
785
+ {
786
+ "cell_type": "code",
787
+ "execution_count": null,
788
+ "id": "99b15c6c",
789
+ "metadata": {},
790
+ "outputs": [],
791
+ "source": [
792
+ "for image, points, labels, masks in zip(img_batch, pts_batch, labels_batch, best_masks):\n",
793
+ " plt.figure(figsize=(10, 10))\n",
794
+ " plt.imshow(image) \n",
795
+ " for mask in masks:\n",
796
+ " show_mask(mask, plt.gca(), random_color=True)\n",
797
+ " show_points(points, labels, plt.gca())"
798
+ ]
799
+ },
800
+ {
801
+ "cell_type": "code",
802
+ "execution_count": null,
803
+ "id": "4c1594a5-a0de-4477-91d4-db4504a78a83",
804
+ "metadata": {},
805
+ "outputs": [],
806
+ "source": []
807
+ },
808
+ {
809
+ "cell_type": "code",
810
+ "execution_count": null,
811
+ "id": "74e3d07e-b0de-48a5-9d29-d639a0dbcdfc",
812
+ "metadata": {},
813
+ "outputs": [],
814
+ "source": []
815
+ },
816
+ {
817
+ "cell_type": "code",
818
+ "execution_count": null,
819
+ "id": "d8b1de3a-a253-48ff-8a1c-d80742acbe86",
820
+ "metadata": {},
821
+ "outputs": [],
822
+ "source": []
823
+ }
824
+ ],
825
+ "metadata": {
826
+ "kernelspec": {
827
+ "display_name": "Python 3 (ipykernel)",
828
+ "language": "python",
829
+ "name": "python3"
830
+ },
831
+ "language_info": {
832
+ "codemirror_mode": {
833
+ "name": "ipython",
834
+ "version": 3
835
+ },
836
+ "file_extension": ".py",
837
+ "mimetype": "text/x-python",
838
+ "name": "python",
839
+ "nbconvert_exporter": "python",
840
+ "pygments_lexer": "ipython3",
841
+ "version": "3.12.11"
842
+ }
843
+ },
844
+ "nbformat": 4,
845
+ "nbformat_minor": 5
846
+ }
third_party/GraspGen/sam3/examples/sam3_for_sam2_video_task_example.ipynb ADDED
@@ -0,0 +1,979 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "3c3b1c46-9f5c-41c1-9101-85db8709ec0d",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "# Copyright (c) Meta Platforms, Inc. and affiliates."
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "markdown",
15
+ "id": "6e7a0db5-7f04-4845-8b11-684fe6e9f7f2",
16
+ "metadata": {},
17
+ "source": [
18
+ "# Video object segmentation with SAM 3"
19
+ ]
20
+ },
21
+ {
22
+ "cell_type": "markdown",
23
+ "id": "162d0b3c-4207-442d-969c-aa1cbb8fd4ad",
24
+ "metadata": {},
25
+ "source": [
26
+ "This notebook shows how to use SAM 3 for video object segmentation in videos, illustrating the use of the `Sam3TrackerPredictor` class.\n",
27
+ "\n",
28
+ "\n",
29
+ "This notebook follows the SAM 2 API for interactive video segmentation.\n",
30
+ "\n",
31
+ "<a target=\"_blank\" href=\"https://colab.research.google.com/github/facebookresearch/sam3/blob/main/notebooks/sam3_for_sam2_video_task_example.ipynb\">\n",
32
+ " <img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/>\n",
33
+ "</a>"
34
+ ]
35
+ },
36
+ {
37
+ "cell_type": "markdown",
38
+ "id": "26616201-06df-435b-98fd-ad17c373bb4a",
39
+ "metadata": {},
40
+ "source": [
41
+ "## Environment Set-up"
42
+ ]
43
+ },
44
+ {
45
+ "cell_type": "markdown",
46
+ "id": "8491a127-4c01-48f5-9dc5-f148a9417fdf",
47
+ "metadata": {},
48
+ "source": [
49
+ "First install `sam3` in your environment using the [installation instructions](https://github.com/facebookresearch/sam3?tab=readme-ov-file#installation) in the repository."
50
+ ]
51
+ },
52
+ {
53
+ "cell_type": "code",
54
+ "execution_count": null,
55
+ "id": "f74c53be-aab1-46b9-8c0b-068b52ef5948",
56
+ "metadata": {},
57
+ "outputs": [],
58
+ "source": [
59
+ "using_colab = False"
60
+ ]
61
+ },
62
+ {
63
+ "cell_type": "code",
64
+ "execution_count": null,
65
+ "id": "d824a4b2-71f3-4da3-bfc7-3249625e6730",
66
+ "metadata": {},
67
+ "outputs": [],
68
+ "source": [
69
+ "if using_colab:\n",
70
+ " import torch\n",
71
+ " import torchvision\n",
72
+ " print(\"PyTorch version:\", torch.__version__)\n",
73
+ " print(\"Torchvision version:\", torchvision.__version__)\n",
74
+ " print(\"CUDA is available:\", torch.cuda.is_available())\n",
75
+ " import sys\n",
76
+ " !{sys.executable} -m pip install opencv-python matplotlib scikit-learn\n",
77
+ " !{sys.executable} -m pip install 'git+https://github.com/facebookresearch/sam3.git'"
78
+ ]
79
+ },
80
+ {
81
+ "cell_type": "markdown",
82
+ "id": "22e6aa9d-487f-4207-b657-8cff0902343e",
83
+ "metadata": {},
84
+ "source": [
85
+ "## Set-up"
86
+ ]
87
+ },
88
+ {
89
+ "cell_type": "code",
90
+ "execution_count": null,
91
+ "id": "d3cae821",
92
+ "metadata": {},
93
+ "outputs": [],
94
+ "source": [
95
+ "import torch\n",
96
+ "\n",
97
+ "# select the device for computation\n",
98
+ "if torch.cuda.is_available():\n",
99
+ " device = torch.device(\"cuda\")\n",
100
+ "elif torch.backends.mps.is_available():\n",
101
+ " device = torch.device(\"mps\")\n",
102
+ "else:\n",
103
+ " device = torch.device(\"cpu\")\n",
104
+ "print(f\"using device: {device}\")\n",
105
+ "\n",
106
+ "if device.type == \"cuda\":\n",
107
+ " # use bfloat16 for the entire notebook\n",
108
+ " torch.autocast(\"cuda\", dtype=torch.bfloat16).__enter__()\n",
109
+ " # turn on tfloat32 for Ampere GPUs (https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices)\n",
110
+ " if torch.cuda.get_device_properties(0).major >= 8:\n",
111
+ " torch.backends.cuda.matmul.allow_tf32 = True\n",
112
+ " torch.backends.cudnn.allow_tf32 = True\n",
113
+ "\n",
114
+ "elif device.type == \"mps\":\n",
115
+ " print(\n",
116
+ " \"\\nSupport for MPS devices is preliminary. SAM 3 is trained with CUDA and might \"\n",
117
+ " \"give numerically different outputs and sometimes degraded performance on MPS. \"\n",
118
+ " \"See e.g. https://github.com/pytorch/pytorch/issues/84936 for a discussion.\"\n",
119
+ " )"
120
+ ]
121
+ },
122
+ {
123
+ "cell_type": "code",
124
+ "execution_count": null,
125
+ "id": "e5318a85-5bf7-4880-b2b3-15e4db24d796",
126
+ "metadata": {},
127
+ "outputs": [],
128
+ "source": [
129
+ "import glob\n",
130
+ "import os\n",
131
+ "\n",
132
+ "import cv2\n",
133
+ "import matplotlib.pyplot as plt\n",
134
+ "import numpy as np\n",
135
+ "\n",
136
+ "import sam3\n",
137
+ "import torch\n",
138
+ "from PIL import Image\n",
139
+ "from sam3.visualization_utils import show_box, show_mask, show_points\n",
140
+ "\n",
141
+ "# font size for axes titles\n",
142
+ "plt.rcParams[\"axes.titlesize\"] = 12\n",
143
+ "plt.rcParams[\"figure.titlesize\"] = 12\n",
144
+ "\n",
145
+ "sam3_root = os.path.join(os.path.dirname(sam3.__file__), \"..\")"
146
+ ]
147
+ },
148
+ {
149
+ "cell_type": "markdown",
150
+ "id": "ae8e0779-751f-4224-9b04-ed0f0b406500",
151
+ "metadata": {},
152
+ "source": [
153
+ "### Loading the SAM 3 tracking predictor"
154
+ ]
155
+ },
156
+ {
157
+ "cell_type": "code",
158
+ "execution_count": null,
159
+ "id": "f5f3245e-b4d6-418b-a42a-a67e0b3b5aec",
160
+ "metadata": {},
161
+ "outputs": [],
162
+ "source": [
163
+ "from sam3.model_builder import build_sam3_video_model\n",
164
+ "\n",
165
+ "sam3_model = build_sam3_video_model()\n",
166
+ "predictor = sam3_model.tracker\n",
167
+ "predictor.backbone = sam3_model.detector.backbone"
168
+ ]
169
+ },
170
+ {
171
+ "cell_type": "markdown",
172
+ "id": "dff46b10-c17a-4a26-8004-8c6d80806b0a",
173
+ "metadata": {},
174
+ "source": [
175
+ "#### Initialize the inference state"
176
+ ]
177
+ },
178
+ {
179
+ "cell_type": "markdown",
180
+ "id": "f594ac71-a6b9-461d-af27-500fa1d1a420",
181
+ "metadata": {},
182
+ "source": [
183
+ "Just like SAM 2, SAM 3 requires stateful inference for interactive video segmentation, so we need to initialize an **inference state** on this video.\n",
184
+ "\n",
185
+ "During initialization, it loads all the JPEG frames in `video_path` and stores their pixels in `inference_state` (as shown in the progress bar below)."
186
+ ]
187
+ },
188
+ {
189
+ "cell_type": "code",
190
+ "execution_count": null,
191
+ "id": "9baa05c9",
192
+ "metadata": {},
193
+ "outputs": [],
194
+ "source": [
195
+ "video_path = f\"{sam3_root}/assets/videos/bedroom.mp4\"\n",
196
+ "inference_state = predictor.init_state(video_path=video_path)"
197
+ ]
198
+ },
199
+ {
200
+ "cell_type": "markdown",
201
+ "id": "edb1f3f6-d74d-4016-934c-8d2a14d1a543",
202
+ "metadata": {},
203
+ "source": [
204
+ "### Example 1: Segment & track one object"
205
+ ]
206
+ },
207
+ {
208
+ "cell_type": "markdown",
209
+ "id": "aa2d3127-67b2-45d2-9f32-8fe3e10dc5eb",
210
+ "metadata": {},
211
+ "source": [
212
+ "Note: if you have run any previous tracking using this `inference_state`, please reset it first via `clear_all_points_in_video`.\n",
213
+ "\n",
214
+ "(The cell below is just for illustration; it's not needed to call `clear_all_points_in_video` here as this `inference_state` is just freshly initialized above.)"
215
+ ]
216
+ },
217
+ {
218
+ "cell_type": "code",
219
+ "execution_count": null,
220
+ "id": "d2646a1d-3401-438c-a653-55e0e56b7d9d",
221
+ "metadata": {},
222
+ "outputs": [],
223
+ "source": [
224
+ "predictor.clear_all_points_in_video(inference_state)"
225
+ ]
226
+ },
227
+ {
228
+ "cell_type": "markdown",
229
+ "id": "26aeb04d-8cba-4f57-95da-6e5a1796003e",
230
+ "metadata": {},
231
+ "source": [
232
+ "#### Step 1: Add a first click on a frame"
233
+ ]
234
+ },
235
+ {
236
+ "cell_type": "markdown",
237
+ "id": "695c7749-b523-4691-aad0-7558c5d1d68c",
238
+ "metadata": {},
239
+ "source": [
240
+ "To get started, let's try to segment the child on the left.\n",
241
+ "\n",
242
+ "Here we make a **positive click** at (x, y) = (210, 350) with label `1`, by sending their coordinates and labels into the `add_new_points` API.\n",
243
+ "\n",
244
+ "Note: label `1` indicates a *positive click (to add a region)* while label `0` indicates a *negative click (to remove a region)*."
245
+ ]
246
+ },
247
+ {
248
+ "cell_type": "code",
249
+ "execution_count": null,
250
+ "id": "dd6778a1",
251
+ "metadata": {},
252
+ "outputs": [],
253
+ "source": [
254
+ "# load the frames for visualization\n",
255
+ "cap = cv2.VideoCapture(video_path)\n",
256
+ "video_frames_for_vis = []\n",
257
+ "while True:\n",
258
+ " ret, frame = cap.read()\n",
259
+ " if not ret:\n",
260
+ " break\n",
261
+ " video_frames_for_vis.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))\n",
262
+ "cap.release()\n",
263
+ "frame0 = video_frames_for_vis[0]\n",
264
+ "\n",
265
+ "width, height = frame0.shape[1], frame0.shape[0]"
266
+ ]
267
+ },
268
+ {
269
+ "cell_type": "code",
270
+ "execution_count": null,
271
+ "id": "3e749bab-0f36-4173-bf8d-0c20cd5214b3",
272
+ "metadata": {},
273
+ "outputs": [],
274
+ "source": [
275
+ "ann_frame_idx = 0 # the frame index we interact with\n",
276
+ "ann_obj_id = 1 # give a unique id to each object we interact with (it can be any integers)\n",
277
+ "\n",
278
+ "# Let's add a positive click at (x, y) = (210, 350) to get started\n",
279
+ "points = np.array([[210, 350]], dtype=np.float32)\n",
280
+ "# for labels, `1` means positive click and `0` means negative click\n",
281
+ "labels = np.array([1], np.int32)\n",
282
+ "\n",
283
+ "rel_points = [[x / width, y / height] for x, y in points]\n",
284
+ "\n",
285
+ "points_tensor = torch.tensor(rel_points, dtype=torch.float32)\n",
286
+ "points_labels_tensor = torch.tensor(labels, dtype=torch.int32)\n",
287
+ "\n",
288
+ "_, out_obj_ids, low_res_masks, video_res_masks = predictor.add_new_points(\n",
289
+ " inference_state=inference_state,\n",
290
+ " frame_idx=ann_frame_idx,\n",
291
+ " obj_id=ann_obj_id,\n",
292
+ " points=points_tensor,\n",
293
+ " labels=points_labels_tensor,\n",
294
+ " clear_old_points=False,\n",
295
+ ")\n",
296
+ "\n",
297
+ "# show the results on the current (interacted) frame\n",
298
+ "plt.figure(figsize=(9, 6))\n",
299
+ "plt.title(f\"frame {ann_frame_idx}\")\n",
300
+ "plt.imshow(frame0)\n",
301
+ "show_points(points, labels, plt.gca())\n",
302
+ "show_mask((video_res_masks[0] > 0.0).cpu().numpy(), plt.gca(), obj_id=out_obj_ids[0])"
303
+ ]
304
+ },
305
+ {
306
+ "cell_type": "markdown",
307
+ "id": "89457875-93fa-40ed-b6dc-4e1c971a27f9",
308
+ "metadata": {},
309
+ "source": [
310
+ "#### Step 2: Add a second click to refine the prediction"
311
+ ]
312
+ },
313
+ {
314
+ "cell_type": "markdown",
315
+ "id": "a75eb21b-1413-452c-827b-a04093c30c78",
316
+ "metadata": {},
317
+ "source": [
318
+ "Hmm, it seems that although we wanted to segment the child on the left, the model predicts the mask for only the shorts -- this can happen since there is ambiguity from a single click about what the target object should be. We can refine the mask on this frame via another positive click on the child's shirt.\n",
319
+ "\n",
320
+ "Here we make a **second positive click** at (x, y) = (250, 220) with label `1` to expand the mask.\n",
321
+ "\n",
322
+ "Note: we need to send **all the clicks and their labels** (i.e. not just the last click) when calling `add_new_points`."
323
+ ]
324
+ },
325
+ {
326
+ "cell_type": "code",
327
+ "execution_count": null,
328
+ "id": "e1ab3ec7-2537-4158-bf98-3d0977d8908d",
329
+ "metadata": {},
330
+ "outputs": [],
331
+ "source": [
332
+ "ann_frame_idx = 0 # the frame index we interact with\n",
333
+ "ann_obj_id = 1 # give a unique id to each object we interact with (it can be any integers)\n",
334
+ "\n",
335
+ "# Let's add a 2nd positive click at (x, y) = (250, 220) to refine the mask\n",
336
+ "# sending all clicks (and their labels) to `add_new_points_or_box`\n",
337
+ "points = np.array([[210, 350], [250, 220]], dtype=np.float32)\n",
338
+ "# for labels, `1` means positive click and `0` means negative click\n",
339
+ "labels = np.array([1, 1], np.int32)\n",
340
+ "\n",
341
+ "rel_points = [[x / width, y / height] for x, y in points]\n",
342
+ "\n",
343
+ "points_tensor = torch.tensor(rel_points, dtype=torch.float32)\n",
344
+ "points_labels_tensor = torch.tensor(labels, dtype=torch.int32)\n",
345
+ "\n",
346
+ "_, out_obj_ids, low_res_masks, video_res_masks = predictor.add_new_points(\n",
347
+ " inference_state=inference_state,\n",
348
+ " frame_idx=ann_frame_idx,\n",
349
+ " obj_id=ann_obj_id,\n",
350
+ " points=points_tensor,\n",
351
+ " labels=points_labels_tensor,\n",
352
+ " clear_old_points=False,\n",
353
+ ")\n",
354
+ "\n",
355
+ "# show the results on the current (interacted) frame\n",
356
+ "plt.figure(figsize=(9, 6))\n",
357
+ "plt.title(f\"frame {ann_frame_idx}\")\n",
358
+ "plt.imshow(frame0)\n",
359
+ "show_points(points, labels, plt.gca())\n",
360
+ "show_mask((video_res_masks[0] > 0.0).cpu().numpy(), plt.gca(), obj_id=out_obj_ids[0])"
361
+ ]
362
+ },
363
+ {
364
+ "cell_type": "markdown",
365
+ "id": "df4ab457-d91d-4ac8-b350-fbcd549fd3fd",
366
+ "metadata": {},
367
+ "source": [
368
+ "With this 2nd refinement click, now we get a segmentation mask of the entire child on frame 0."
369
+ ]
370
+ },
371
+ {
372
+ "cell_type": "markdown",
373
+ "id": "f52015ac-1b7b-4c59-bca3-c2b28484cf46",
374
+ "metadata": {},
375
+ "source": [
376
+ "#### Step 3: Propagate the prompts to get the masklet across the video"
377
+ ]
378
+ },
379
+ {
380
+ "cell_type": "markdown",
381
+ "id": "30b025bd-cd58-4bfb-9572-c8d2fd0a02ef",
382
+ "metadata": {},
383
+ "source": [
384
+ "To get the masklet throughout the entire video, we propagate the prompts using the `propagate_in_video` API."
385
+ ]
386
+ },
387
+ {
388
+ "cell_type": "code",
389
+ "execution_count": null,
390
+ "id": "ab45e932-b0d5-4983-9718-6ee77d1ac31b",
391
+ "metadata": {},
392
+ "outputs": [],
393
+ "source": [
394
+ "# run propagation throughout the video and collect the results in a dict\n",
395
+ "video_segments = {} # video_segments contains the per-frame segmentation results\n",
396
+ "for frame_idx, obj_ids, low_res_masks, video_res_masks, obj_scores in predictor.propagate_in_video(inference_state, start_frame_idx=0, max_frame_num_to_track=240, reverse=False, propagate_preflight=True):\n",
397
+ " video_segments[frame_idx] = {\n",
398
+ " out_obj_id: (video_res_masks[i] > 0.0).cpu().numpy()\n",
399
+ " for i, out_obj_id in enumerate(out_obj_ids)\n",
400
+ " }\n",
401
+ "\n",
402
+ "# render the segmentation results every few frames\n",
403
+ "vis_frame_stride = 30\n",
404
+ "plt.close(\"all\")\n",
405
+ "for out_frame_idx in range(0, len(video_frames_for_vis), vis_frame_stride):\n",
406
+ " plt.figure(figsize=(6, 4))\n",
407
+ " plt.title(f\"frame {out_frame_idx}\")\n",
408
+ " plt.imshow(video_frames_for_vis[out_frame_idx])\n",
409
+ " for out_obj_id, out_mask in video_segments[out_frame_idx].items():\n",
410
+ " show_mask(out_mask, plt.gca(), obj_id=out_obj_id)"
411
+ ]
412
+ },
413
+ {
414
+ "cell_type": "markdown",
415
+ "id": "3e801b70-72df-4a72-b3fe-84f145e5e3f6",
416
+ "metadata": {},
417
+ "source": [
418
+ "#### Step 4: Add new prompts to further refine the masklet"
419
+ ]
420
+ },
421
+ {
422
+ "cell_type": "markdown",
423
+ "id": "478958ab-29b4-4a75-bba4-adb1b03d0a2b",
424
+ "metadata": {},
425
+ "source": [
426
+ "It appears that in the output masklet above, there are some small imperfections in boundary details on frame 150.\n",
427
+ "\n",
428
+ "With SAM 3 we can fix the model predictions interactively. We can add a **negative click** at (x, y) = (82, 415) on this frame with label `0` to refine the masklet. Here we call the `add_new_points_or_box` API with a different `frame_idx` argument to indicate the frame index we want to refine."
429
+ ]
430
+ },
431
+ {
432
+ "cell_type": "code",
433
+ "execution_count": null,
434
+ "id": "1a572ea9-5b7e-479c-b30c-93c38b121131",
435
+ "metadata": {},
436
+ "outputs": [],
437
+ "source": [
438
+ "ann_frame_idx = 150 # further refine some details on this frame\n",
439
+ "ann_obj_id = 1 # give a unique id to the object we interact with (it can be any integers)\n",
440
+ "\n",
441
+ "# show the segment before further refinement\n",
442
+ "plt.figure(figsize=(9, 6))\n",
443
+ "plt.title(f\"frame {ann_frame_idx} -- before refinement\")\n",
444
+ "plt.imshow(video_frames_for_vis[ann_frame_idx])\n",
445
+ "show_mask(video_segments[ann_frame_idx][ann_obj_id], plt.gca(), obj_id=ann_obj_id)\n",
446
+ "\n",
447
+ "# Let's add a negative click on this frame at (x, y) = (82, 415) to refine the segment\n",
448
+ "points = np.array([[82, 410]], dtype=np.float32)\n",
449
+ "# for labels, `1` means positive click and `0` means negative click\n",
450
+ "labels = np.array([0], np.int32)\n",
451
+ "\n",
452
+ "rel_points = [[x / width, y / height] for x, y in points]\n",
453
+ "\n",
454
+ "points_tensor = torch.tensor(rel_points, dtype=torch.float32)\n",
455
+ "points_labels_tensor = torch.tensor(labels, dtype=torch.int32)\n",
456
+ "\n",
457
+ "_, out_obj_ids, low_res_masks, video_res_masks = predictor.add_new_points(\n",
458
+ " inference_state=inference_state,\n",
459
+ " frame_idx=ann_frame_idx,\n",
460
+ " obj_id=ann_obj_id,\n",
461
+ " points=points_tensor,\n",
462
+ " labels=points_labels_tensor,\n",
463
+ " clear_old_points=False,\n",
464
+ ")\n",
465
+ "\n",
466
+ "\n",
467
+ "# show the segment after the further refinement\n",
468
+ "plt.figure(figsize=(9, 6))\n",
469
+ "plt.title(f\"frame {ann_frame_idx} -- after refinement\")\n",
470
+ "plt.imshow(video_frames_for_vis[ann_frame_idx])\n",
471
+ "show_points(points, labels, plt.gca())\n",
472
+ "show_mask((video_res_masks > 0.0).cpu().numpy(), plt.gca(), obj_id=ann_obj_id)"
473
+ ]
474
+ },
475
+ {
476
+ "cell_type": "markdown",
477
+ "id": "50a3950a-acf1-435c-bd64-94297267b5e9",
478
+ "metadata": {},
479
+ "source": [
480
+ "#### Step 5: Propagate the prompts (again) to get the masklet across the video"
481
+ ]
482
+ },
483
+ {
484
+ "cell_type": "markdown",
485
+ "id": "b1954ecf-c2ec-4f9c-8d10-c4f527a10cd2",
486
+ "metadata": {},
487
+ "source": [
488
+ "Let's get an updated masklet for the entire video. Here we call `propagate_in_video` again to propagate all the prompts after adding the new refinement click above."
489
+ ]
490
+ },
491
+ {
492
+ "cell_type": "code",
493
+ "execution_count": null,
494
+ "id": "baa96690-4a38-4a24-aa17-fd2f4db0e232",
495
+ "metadata": {},
496
+ "outputs": [],
497
+ "source": [
498
+ "# run propagation throughout the video and collect the results in a dict\n",
499
+ "video_segments = {} # video_segments contains the per-frame segmentation results\n",
500
+ "for frame_idx, obj_ids, low_res_masks, video_res_masks, obj_scores in predictor.propagate_in_video(inference_state, start_frame_idx=0, max_frame_num_to_track=300, reverse=False, propagate_preflight=True):\n",
501
+ " video_segments[frame_idx] = {\n",
502
+ " out_obj_id: (video_res_masks[i] > 0.0).cpu().numpy()\n",
503
+ " for i, out_obj_id in enumerate(out_obj_ids)\n",
504
+ " }\n",
505
+ "\n",
506
+ "# render the segmentation results every few frames\n",
507
+ "vis_frame_stride = 30\n",
508
+ "plt.close(\"all\")\n",
509
+ "for out_frame_idx in range(0, len(video_frames_for_vis), vis_frame_stride):\n",
510
+ " plt.figure(figsize=(6, 4))\n",
511
+ " plt.title(f\"frame {out_frame_idx}\")\n",
512
+ " plt.imshow(video_frames_for_vis[out_frame_idx])\n",
513
+ " for out_obj_id, out_mask in video_segments[out_frame_idx].items():\n",
514
+ " show_mask(out_mask, plt.gca(), obj_id=out_obj_id)"
515
+ ]
516
+ },
517
+ {
518
+ "cell_type": "markdown",
519
+ "id": "607507e3-6a2b-4fd7-944c-2371bdab9d01",
520
+ "metadata": {},
521
+ "source": [
522
+ "The segments now look good on all frames."
523
+ ]
524
+ },
525
+ {
526
+ "cell_type": "markdown",
527
+ "id": "2502bb5a-3e1f-43d0-9f58-33f8676fff0d",
528
+ "metadata": {},
529
+ "source": [
530
+ "### Example 2: Segment an object using box prompt"
531
+ ]
532
+ },
533
+ {
534
+ "cell_type": "markdown",
535
+ "id": "8e2d26c8-0432-48c6-997e-4a3b77bb5f6d",
536
+ "metadata": {},
537
+ "source": [
538
+ "Note: if you have run any previous tracking using this `inference_state`, please reset it first via `clear_all_points_in_video`."
539
+ ]
540
+ },
541
+ {
542
+ "cell_type": "code",
543
+ "execution_count": null,
544
+ "id": "6dbe9183-abbb-4283-b0cb-d24f3d7beb34",
545
+ "metadata": {},
546
+ "outputs": [],
547
+ "source": [
548
+ "predictor.clear_all_points_in_video(inference_state)"
549
+ ]
550
+ },
551
+ {
552
+ "cell_type": "markdown",
553
+ "id": "ceb6eae9-0f4c-434f-8089-a46c9ca59da5",
554
+ "metadata": {},
555
+ "source": [
556
+ "In addition to using clicks as inputs, SAM 3 also supports segmenting and tracking objects in a video via **bounding boxes**.\n",
557
+ "\n",
558
+ "In the example below, we segment the child on the right using a **box prompt** of (x_min, y_min, x_max, y_max) = (300, 0, 500, 400) on frame 0 as input into the `add_new_points_or_box` API."
559
+ ]
560
+ },
561
+ {
562
+ "cell_type": "code",
563
+ "execution_count": null,
564
+ "id": "1cbfb273-4e14-495b-bd89-87a8baf52ae7",
565
+ "metadata": {},
566
+ "outputs": [],
567
+ "source": [
568
+ "ann_frame_idx = 0 # the frame index we interact with\n",
569
+ "ann_obj_id = 4 # give a unique id to each object we interact with (it can be any integers)\n",
570
+ "\n",
571
+ "# Let's add a box at (x_min, y_min, x_max, y_max) = (300, 0, 500, 400) to get started\n",
572
+ "box = np.array([[300, 0, 500, 400]], dtype=np.float32)\n",
573
+ "\n",
574
+ "rel_box = [[xmin / width, ymin / height, xmax / width, ymax / height] for xmin, ymin, xmax, ymax in box]\n",
575
+ "rel_box = np.array(rel_box, dtype=np.float32)\n",
576
+ "\n",
577
+ "_, out_obj_ids, low_res_masks, video_res_masks = predictor.add_new_points_or_box(\n",
578
+ " inference_state=inference_state,\n",
579
+ " frame_idx=ann_frame_idx,\n",
580
+ " obj_id=ann_obj_id,\n",
581
+ " box=rel_box,\n",
582
+ ")\n",
583
+ "\n",
584
+ "# show the results on the current (interacted) frame\n",
585
+ "plt.figure(figsize=(9, 6))\n",
586
+ "plt.title(f\"frame {ann_frame_idx}\")\n",
587
+ "plt.imshow(video_frames_for_vis[ann_frame_idx])\n",
588
+ "show_box(box[0], plt.gca())\n",
589
+ "show_mask((video_res_masks[0] > 0.0).cpu().numpy(), plt.gca(), obj_id=ann_obj_id)"
590
+ ]
591
+ },
592
+ {
593
+ "cell_type": "markdown",
594
+ "id": "bd3f9ba7-bf4d-47e5-9b02-8a424cab42cc",
595
+ "metadata": {},
596
+ "source": [
597
+ "Here, SAM 3 gets a pretty good segmentation mask of the entire child, even though the input bounding box is not perfectly tight around the object.\n",
598
+ "\n",
599
+ "Similar to the previous example, if the returned mask from is not perfect when using a box prompt, we can also further **refine** the output using positive or negative clicks. To illustrate this, here we make a **positive click** at (x, y) = (460, 60) with label `1` to expand the segment around the child's hair.\n",
600
+ "\n",
601
+ "Note: to refine the segmentation mask from a box prompt, we need to send **both the original box input and all subsequent refinement clicks and their labels** when calling `add_new_points_or_box`."
602
+ ]
603
+ },
604
+ {
605
+ "cell_type": "code",
606
+ "execution_count": null,
607
+ "id": "54906315-ab4c-4088-b866-4c22134d5b66",
608
+ "metadata": {},
609
+ "outputs": [],
610
+ "source": [
611
+ "ann_frame_idx = 0 # the frame index we interact with\n",
612
+ "ann_obj_id = 4 # give a unique id to each object we interact with (it can be any integers)\n",
613
+ "\n",
614
+ "# Let's add a positive click at (x, y) = (460, 60) to refine the mask\n",
615
+ "points = np.array([[460, 60]], dtype=np.float32)\n",
616
+ "# for labels, `1` means positive click and `0` means negative click\n",
617
+ "labels = np.array([1], np.int32)\n",
618
+ "# note that we also need to send the original box input along with\n",
619
+ "# the new refinement click together into `add_new_points_or_box`\n",
620
+ "box = np.array([[300, 0, 500, 400]], dtype=np.float32)\n",
621
+ "\n",
622
+ "rel_box = [[xmin / width, ymin / height, xmax / width, ymax / height] for xmin, ymin, xmax, ymax in box]\n",
623
+ "rel_box = np.array(rel_box, dtype=np.float32)\n",
624
+ "\n",
625
+ "rel_points = [[x / width, y / height] for x, y in points]\n",
626
+ "\n",
627
+ "points_tensor = torch.tensor(rel_points, dtype=torch.float32)\n",
628
+ "points_labels_tensor = torch.tensor(labels, dtype=torch.int32)\n",
629
+ "\n",
630
+ "_, out_obj_ids, low_res_masks, video_res_masks = predictor.add_new_points_or_box(\n",
631
+ " inference_state=inference_state,\n",
632
+ " frame_idx=ann_frame_idx,\n",
633
+ " obj_id=ann_obj_id,\n",
634
+ " points=points_tensor,\n",
635
+ " labels=points_labels_tensor,\n",
636
+ " box=rel_box,\n",
637
+ ")\n",
638
+ "\n",
639
+ "# show the results on the current (interacted) frame\n",
640
+ "plt.figure(figsize=(9, 6))\n",
641
+ "plt.title(f\"frame {ann_frame_idx}\")\n",
642
+ "plt.imshow(video_frames_for_vis[ann_frame_idx])\n",
643
+ "show_box(box[0], plt.gca())\n",
644
+ "show_points(points, labels, plt.gca())\n",
645
+ "show_mask((video_res_masks[0][0] > 0.0).cpu().numpy(), plt.gca(), obj_id=out_obj_ids[0])"
646
+ ]
647
+ },
648
+ {
649
+ "cell_type": "markdown",
650
+ "id": "73128cd6-dbfa-49f7-8d79-1a8e19835f7f",
651
+ "metadata": {},
652
+ "source": [
653
+ "Then, to get the masklet throughout the entire video, we propagate the prompts using the `propagate_in_video` API."
654
+ ]
655
+ },
656
+ {
657
+ "cell_type": "code",
658
+ "execution_count": null,
659
+ "id": "9cd90557-a0dc-442e-b091-9c74c831bef8",
660
+ "metadata": {},
661
+ "outputs": [],
662
+ "source": [
663
+ "# run propagation throughout the video and collect the results in a dict\n",
664
+ "video_segments = {} # video_segments contains the per-frame segmentation results\n",
665
+ "for frame_idx, obj_ids, low_res_masks, video_res_masks, obj_scores in predictor.propagate_in_video(inference_state, start_frame_idx=0, max_frame_num_to_track=300, reverse=False, propagate_preflight=True):\n",
666
+ " video_segments[frame_idx] = {\n",
667
+ " out_obj_id: (video_res_masks[i] > 0.0).cpu().numpy()\n",
668
+ " for i, out_obj_id in enumerate(out_obj_ids)\n",
669
+ " }\n",
670
+ "\n",
671
+ "# render the segmentation results every few frames\n",
672
+ "vis_frame_stride = 30\n",
673
+ "plt.close(\"all\")\n",
674
+ "for out_frame_idx in range(0, len(video_frames_for_vis), vis_frame_stride):\n",
675
+ " plt.figure(figsize=(6, 4))\n",
676
+ " plt.title(f\"frame {out_frame_idx}\")\n",
677
+ " plt.imshow(video_frames_for_vis[out_frame_idx])\n",
678
+ " for out_obj_id, out_mask in video_segments[out_frame_idx].items():\n",
679
+ " show_mask(out_mask, plt.gca(), obj_id=out_obj_id)"
680
+ ]
681
+ },
682
+ {
683
+ "cell_type": "markdown",
684
+ "id": "e023f91f-0cc5-4980-ae8e-a13c5749112b",
685
+ "metadata": {},
686
+ "source": [
687
+ "Note that in addition to clicks or boxes, SAM 3 also supports directly using a **mask prompt** as input via the `add_new_mask` method in the `Sam3TrackerPredictor` class. This can be helpful in e.g. semi-supervised VOS evaluations (see [tools/vos_inference.py](https://github.com/facebookresearch/sam2/blob/main/tools/vos_inference.py) for an example)."
688
+ ]
689
+ },
690
+ {
691
+ "cell_type": "markdown",
692
+ "id": "da018be8-a4ae-4943-b1ff-702c2b89cb68",
693
+ "metadata": {},
694
+ "source": [
695
+ "### Example 3: Segment multiple objects simultaneously"
696
+ ]
697
+ },
698
+ {
699
+ "cell_type": "markdown",
700
+ "id": "dea6c04c-3072-4876-b394-879321a48c4a",
701
+ "metadata": {},
702
+ "source": [
703
+ "Note: if you have run any previous tracking using this `inference_state`, please reset it first via `clear_all_points_in_video`."
704
+ ]
705
+ },
706
+ {
707
+ "cell_type": "code",
708
+ "execution_count": null,
709
+ "id": "29b874c8-9f39-42d3-a667-54a0bd696410",
710
+ "metadata": {},
711
+ "outputs": [],
712
+ "source": [
713
+ "predictor.clear_all_points_in_video(inference_state)"
714
+ ]
715
+ },
716
+ {
717
+ "cell_type": "markdown",
718
+ "id": "48f3f7e6-4821-468c-84e4-f3a0435c9149",
719
+ "metadata": {},
720
+ "source": [
721
+ "#### Step 1: Add two objects on a frame"
722
+ ]
723
+ },
724
+ {
725
+ "cell_type": "markdown",
726
+ "id": "95158714-86d7-48a9-8365-b213f97cc9ca",
727
+ "metadata": {},
728
+ "source": [
729
+ "SAM 3 can also segment and track two or more objects at the same time. One way, of course, is to do them one by one. However, it would be more efficient to batch them together (e.g. so that we can share the image features between objects to reduce computation costs).\n",
730
+ "\n",
731
+ "This time, let's focus on object parts and segment **the shirts of both childen** in this video. Here we add prompts for these two objects and assign each of them a unique object id."
732
+ ]
733
+ },
734
+ {
735
+ "cell_type": "code",
736
+ "execution_count": null,
737
+ "id": "e22d896d-3cd5-4fa0-9230-f33e217035dc",
738
+ "metadata": {},
739
+ "outputs": [],
740
+ "source": [
741
+ "prompts = {} # hold all the clicks we add for visualization"
742
+ ]
743
+ },
744
+ {
745
+ "cell_type": "markdown",
746
+ "id": "59d9ac57-b14a-4237-828d-927e422c518b",
747
+ "metadata": {},
748
+ "source": [
749
+ "Add the first object (the left child's shirt) with a **positive click** at (x, y) = (200, 300) on frame 0.\n",
750
+ "\n",
751
+ "We assign it to object id `2` (it can be arbitrary integers, and only needs to be unique for each object to track), which is passed to the `add_new_points_or_box` API to distinguish the object we are clicking upon."
752
+ ]
753
+ },
754
+ {
755
+ "cell_type": "code",
756
+ "execution_count": null,
757
+ "id": "d13432fc-f467-44d8-adfe-3e0c488046b7",
758
+ "metadata": {},
759
+ "outputs": [],
760
+ "source": [
761
+ "ann_frame_idx = 0 # the frame index we interact with\n",
762
+ "ann_obj_id = 2 # give a unique id to each object we interact with (it can be any integers)\n",
763
+ "\n",
764
+ "# Let's add a positive click at (x, y) = (200, 300) to get started on the first object\n",
765
+ "points = np.array([[200, 300]], dtype=np.float32)\n",
766
+ "# for labels, `1` means positive click and `0` means negative click\n",
767
+ "labels = np.array([1], np.int32)\n",
768
+ "prompts[ann_obj_id] = points, labels\n",
769
+ "\n",
770
+ "rel_points = [[x / width, y / height] for x, y in points]\n",
771
+ "points_tensor = torch.tensor(rel_points, dtype=torch.float32)\n",
772
+ "points_labels_tensor = torch.tensor(labels, dtype=torch.int32)\n",
773
+ "\n",
774
+ "_, out_obj_ids, low_res_masks, video_res_masks = predictor.add_new_points_or_box(\n",
775
+ " inference_state=inference_state,\n",
776
+ " frame_idx=ann_frame_idx,\n",
777
+ " obj_id=ann_obj_id,\n",
778
+ " points=points_tensor,\n",
779
+ " labels=points_labels_tensor,\n",
780
+ ")\n",
781
+ "\n",
782
+ "\n",
783
+ "# show the results on the current (interacted) frame\n",
784
+ "plt.figure(figsize=(9, 6))\n",
785
+ "plt.title(f\"frame {ann_frame_idx}\")\n",
786
+ "plt.imshow(video_frames_for_vis[ann_frame_idx])\n",
787
+ "for i, out_obj_id in enumerate(out_obj_ids):\n",
788
+ " show_points(points, labels, plt.gca())\n",
789
+ " show_points(*prompts[out_obj_id], plt.gca())\n",
790
+ " show_mask((video_res_masks[i][0] > 0.0).cpu().numpy(), plt.gca(), obj_id=out_obj_id)"
791
+ ]
792
+ },
793
+ {
794
+ "cell_type": "markdown",
795
+ "id": "1bbbd51b-e1e2-4c36-99ec-1d9a1b49b0cd",
796
+ "metadata": {},
797
+ "source": [
798
+ "Hmm, this time we just want to select the child's shirt, but the model predicts the mask for the entire child. Let's refine the prediction with a **negative click** at (x, y) = (275, 175)."
799
+ ]
800
+ },
801
+ {
802
+ "cell_type": "code",
803
+ "execution_count": null,
804
+ "id": "95ecf61d-662b-4f98-ae62-46557b219842",
805
+ "metadata": {},
806
+ "outputs": [],
807
+ "source": [
808
+ "# add the first object\n",
809
+ "ann_frame_idx = 0 # the frame index we interact with\n",
810
+ "ann_obj_id = 2 # give a unique id to each object we interact with (it can be any integers)\n",
811
+ "\n",
812
+ "# Let's add a 2nd negative click at (x, y) = (275, 175) to refine the first object\n",
813
+ "# sending all clicks (and their labels) to `add_new_points_or_box`\n",
814
+ "points = np.array([[200, 300], [275, 175]], dtype=np.float32)\n",
815
+ "# for labels, `1` means positive click and `0` means negative click\n",
816
+ "labels = np.array([1, 0], np.int32)\n",
817
+ "prompts[ann_obj_id] = points, labels\n",
818
+ "\n",
819
+ "rel_points = [[x / width, y / height] for x, y in points]\n",
820
+ "points_tensor = torch.tensor(rel_points, dtype=torch.float32)\n",
821
+ "points_labels_tensor = torch.tensor(labels, dtype=torch.int32)\n",
822
+ "\n",
823
+ "\n",
824
+ "_, out_obj_ids, low_res_masks, video_res_masks = predictor.add_new_points_or_box(\n",
825
+ " inference_state=inference_state,\n",
826
+ " frame_idx=ann_frame_idx,\n",
827
+ " obj_id=ann_obj_id,\n",
828
+ " points=rel_points,\n",
829
+ " labels=points_labels_tensor,\n",
830
+ ")\n",
831
+ "\n",
832
+ "# show the results on the current (interacted) frame\n",
833
+ "plt.figure(figsize=(9, 6))\n",
834
+ "plt.title(f\"frame {ann_frame_idx}\")\n",
835
+ "plt.imshow(video_frames_for_vis[ann_frame_idx])\n",
836
+ "for i, out_obj_id in enumerate(out_obj_ids):\n",
837
+ " show_points(points, labels, plt.gca())\n",
838
+ " show_points(*prompts[out_obj_id], plt.gca())\n",
839
+ " show_mask((video_res_masks[i][0] > 0.0).cpu().numpy(), plt.gca(), obj_id=out_obj_id)"
840
+ ]
841
+ },
842
+ {
843
+ "cell_type": "markdown",
844
+ "id": "194718c1-734d-446c-a3ef-361057de2f31",
845
+ "metadata": {},
846
+ "source": [
847
+ "After the 2nd negative click, now we get the left child's shirt as our first object.\n",
848
+ "\n",
849
+ "Let's move on to the second object (the right child's shirt) with a positive click at (x, y) = (400, 150) on frame 0. Here we assign object id `3` to this second object (it can be arbitrary integers, and only needs to be unique for each object to track).\n",
850
+ "\n",
851
+ "Note: when there are multiple objects, the `add_new_points_or_box` API will return a list of masks for each object."
852
+ ]
853
+ },
854
+ {
855
+ "cell_type": "code",
856
+ "execution_count": null,
857
+ "id": "86ca1bde-62a4-40e6-98e4-15606441e52f",
858
+ "metadata": {},
859
+ "outputs": [],
860
+ "source": [
861
+ "ann_frame_idx = 0 # the frame index we interact with\n",
862
+ "ann_obj_id = 3 # give a unique id to each object we interact with (it can be any integers)\n",
863
+ "\n",
864
+ "# Let's now move on to the second object we want to track (giving it object id `3`)\n",
865
+ "# with a positive click at (x, y) = (400, 150)\n",
866
+ "points = np.array([[400, 150]], dtype=np.float32)\n",
867
+ "# for labels, `1` means positive click and `0` means negative click\n",
868
+ "labels = np.array([1], np.int32)\n",
869
+ "prompts[ann_obj_id] = points, labels\n",
870
+ "\n",
871
+ "rel_points = [[x / width, y / height] for x, y in points]\n",
872
+ "points_tensor = torch.tensor(rel_points, dtype=torch.float32)\n",
873
+ "points_labels_tensor = torch.tensor(labels, dtype=torch.int32)\n",
874
+ "\n",
875
+ "\n",
876
+ "# `add_new_points_or_box` returns masks for all objects added so far on this interacted frame\n",
877
+ "_, out_obj_ids, low_res_masks, video_res_masks = predictor.add_new_points_or_box(\n",
878
+ " inference_state=inference_state,\n",
879
+ " frame_idx=ann_frame_idx,\n",
880
+ " obj_id=ann_obj_id,\n",
881
+ " points=points_tensor,\n",
882
+ " labels=points_labels_tensor,\n",
883
+ ")\n",
884
+ "\n",
885
+ "# show the results on the current (interacted) frame on all objects\n",
886
+ "plt.figure(figsize=(9, 6))\n",
887
+ "plt.title(f\"frame {ann_frame_idx}\")\n",
888
+ "plt.imshow(video_frames_for_vis[ann_frame_idx])\n",
889
+ "for i, out_obj_id in enumerate(out_obj_ids):\n",
890
+ " show_points(points, labels, plt.gca())\n",
891
+ " show_points(*prompts[out_obj_id], plt.gca())\n",
892
+ " show_mask((video_res_masks[i][0] > 0.0).cpu().numpy(), plt.gca(), obj_id=out_obj_id)"
893
+ ]
894
+ },
895
+ {
896
+ "cell_type": "markdown",
897
+ "id": "a1f7add8-d577-4597-ae2f-654b8c7b05e0",
898
+ "metadata": {},
899
+ "source": [
900
+ "This time the model predicts the mask of the shirt we want to track in just one click. Nice!"
901
+ ]
902
+ },
903
+ {
904
+ "cell_type": "markdown",
905
+ "id": "448733b8-ea8b-4078-995f-b676c3b558ba",
906
+ "metadata": {},
907
+ "source": [
908
+ "#### Step 2: Propagate the prompts to get masklets across the video"
909
+ ]
910
+ },
911
+ {
912
+ "cell_type": "markdown",
913
+ "id": "60bd73de-d669-41c8-b6ba-943883f0caa2",
914
+ "metadata": {},
915
+ "source": [
916
+ "Now, we propagate the prompts for both objects to get their masklets throughout the video.\n",
917
+ "\n",
918
+ "Note: when there are multiple objects, the `propagate_in_video` API will return a list of masks for each object."
919
+ ]
920
+ },
921
+ {
922
+ "cell_type": "code",
923
+ "execution_count": null,
924
+ "id": "17737191-d62b-4611-b2c6-6d0418a9ab74",
925
+ "metadata": {},
926
+ "outputs": [],
927
+ "source": [
928
+ "# run propagation throughout the video and collect the results in a dict\n",
929
+ "video_segments = {} # video_segments contains the per-frame segmentation results\n",
930
+ "for frame_idx, obj_ids, low_res_masks, video_res_masks, obj_scores in predictor.propagate_in_video(inference_state, start_frame_idx=0, max_frame_num_to_track=300, reverse=False, propagate_preflight=True):\n",
931
+ " video_segments[frame_idx] = {\n",
932
+ " out_obj_id: (video_res_masks[i] > 0.0).cpu().numpy()\n",
933
+ " for i, out_obj_id in enumerate(out_obj_ids)\n",
934
+ " }\n",
935
+ "\n",
936
+ "# render the segmentation results every few frames\n",
937
+ "vis_frame_stride = 30\n",
938
+ "plt.close(\"all\")\n",
939
+ "for out_frame_idx in range(0, len(video_frames_for_vis), vis_frame_stride):\n",
940
+ " plt.figure(figsize=(6, 4))\n",
941
+ " plt.title(f\"frame {out_frame_idx}\")\n",
942
+ " plt.imshow(video_frames_for_vis[out_frame_idx])\n",
943
+ " for out_obj_id, out_mask in video_segments[out_frame_idx].items():\n",
944
+ " show_mask(out_mask, plt.gca(), obj_id=out_obj_id)"
945
+ ]
946
+ },
947
+ {
948
+ "cell_type": "markdown",
949
+ "id": "18a0b9d7-c78f-432b-afb0-11f2ea5b652a",
950
+ "metadata": {},
951
+ "source": [
952
+ "Looks like both children's shirts are well segmented in this video.\n",
953
+ "\n",
954
+ "Now you can try SAM 3 on your own videos and use cases! "
955
+ ]
956
+ }
957
+ ],
958
+ "metadata": {
959
+ "kernelspec": {
960
+ "display_name": "Python 3 (ipykernel)",
961
+ "language": "python",
962
+ "name": "python3"
963
+ },
964
+ "language_info": {
965
+ "codemirror_mode": {
966
+ "name": "ipython",
967
+ "version": 3
968
+ },
969
+ "file_extension": ".py",
970
+ "mimetype": "text/x-python",
971
+ "name": "python",
972
+ "nbconvert_exporter": "python",
973
+ "pygments_lexer": "ipython3",
974
+ "version": "3.12.11"
975
+ }
976
+ },
977
+ "nbformat": 4,
978
+ "nbformat_minor": 5
979
+ }
third_party/GraspGen/sam3/examples/sam3_image_batched_inference.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
third_party/GraspGen/sam3/examples/sam3_image_interactive.ipynb ADDED
@@ -0,0 +1,757 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "5d0e0b69",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "# Copyright (c) Meta Platforms, Inc. and affiliates."
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "markdown",
15
+ "id": "11912666",
16
+ "metadata": {},
17
+ "source": [
18
+ "# <a target=\"_blank\" href=\"https://colab.research.google.com/github/facebookresearch/sam3/blob/main/notebooks/sam3_image_interactive.ipynb\">\n",
19
+ "# <img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/>\n",
20
+ "# </a>"
21
+ ]
22
+ },
23
+ {
24
+ "cell_type": "code",
25
+ "execution_count": 2,
26
+ "id": "8517f5f6",
27
+ "metadata": {},
28
+ "outputs": [],
29
+ "source": [
30
+ "using_colab = False"
31
+ ]
32
+ },
33
+ {
34
+ "cell_type": "code",
35
+ "execution_count": 3,
36
+ "id": "2540e376",
37
+ "metadata": {},
38
+ "outputs": [],
39
+ "source": [
40
+ "if using_colab:\n",
41
+ " import torch\n",
42
+ " import torchvision\n",
43
+ " print(\"PyTorch version:\", torch.__version__)\n",
44
+ " print(\"Torchvision version:\", torchvision.__version__)\n",
45
+ " print(\"CUDA is available:\", torch.cuda.is_available())\n",
46
+ " import sys\n",
47
+ " !{sys.executable} -m pip install opencv-python matplotlib scikit-learn\n",
48
+ " !{sys.executable} -m pip install 'git+https://github.com/facebookresearch/sam3.git'"
49
+ ]
50
+ },
51
+ {
52
+ "cell_type": "code",
53
+ "execution_count": 4,
54
+ "id": "90073483-58f6-404e-90ac-c22efcd76216",
55
+ "metadata": {},
56
+ "outputs": [],
57
+ "source": [
58
+ "%matplotlib widget"
59
+ ]
60
+ },
61
+ {
62
+ "cell_type": "code",
63
+ "execution_count": 5,
64
+ "id": "13325376-658b-48d6-8528-2a006f223d44",
65
+ "metadata": {},
66
+ "outputs": [],
67
+ "source": [
68
+ "import torch\n",
69
+ "# turn on tfloat32 for Ampere GPUs\n",
70
+ "# https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices\n",
71
+ "torch.backends.cuda.matmul.allow_tf32 = True\n",
72
+ "torch.backends.cudnn.allow_tf32 = True\n",
73
+ "\n",
74
+ "# use bfloat16 for the entire notebook. If your card doesn't support it, try float16 instead\n",
75
+ "torch.autocast(\"cuda\", dtype=torch.bfloat16).__enter__()\n",
76
+ "\n",
77
+ "# inference mode for the whole notebook. Disable if you need gradients\n",
78
+ "torch.inference_mode().__enter__()"
79
+ ]
80
+ },
81
+ {
82
+ "cell_type": "markdown",
83
+ "id": "fb863772-56a9-4ee2-be52-5d8933066519",
84
+ "metadata": {},
85
+ "source": [
86
+ "# Load the model"
87
+ ]
88
+ },
89
+ {
90
+ "cell_type": "code",
91
+ "execution_count": 6,
92
+ "id": "f84b4ccc-9db2-4d88-ac8f-4c272694d25a",
93
+ "metadata": {},
94
+ "outputs": [],
95
+ "source": [
96
+ "import sam3\n",
97
+ "from sam3 import build_sam3_image_model\n",
98
+ "import os\n",
99
+ "sam3_root = os.path.join(os.path.dirname(sam3.__file__), \"..\")\n",
100
+ "bpe_path = f\"{sam3_root}/assets/bpe_simple_vocab_16e6.txt.gz\""
101
+ ]
102
+ },
103
+ {
104
+ "cell_type": "code",
105
+ "execution_count": 7,
106
+ "id": "de01a36e-1221-4497-a5ab-e6c796689480",
107
+ "metadata": {},
108
+ "outputs": [],
109
+ "source": [
110
+ "model = build_sam3_image_model(bpe_path=bpe_path)"
111
+ ]
112
+ },
113
+ {
114
+ "cell_type": "code",
115
+ "execution_count": 8,
116
+ "id": "b01ec8a9-d9f6-4baf-96ac-1e5d21fd90b8",
117
+ "metadata": {},
118
+ "outputs": [],
119
+ "source": [
120
+ "from sam3.model.sam3_image_processor import Sam3Processor\n",
121
+ "processor = Sam3Processor(model)"
122
+ ]
123
+ },
124
+ {
125
+ "cell_type": "markdown",
126
+ "id": "e6172a69-35ca-487c-bd67-6f1f1ecb20d5",
127
+ "metadata": {},
128
+ "source": [
129
+ "# Jupyter widget"
130
+ ]
131
+ },
132
+ {
133
+ "cell_type": "code",
134
+ "execution_count": 9,
135
+ "id": "2a4ac22f-5d5c-4272-a5a1-dfe0c04253a7",
136
+ "metadata": {},
137
+ "outputs": [],
138
+ "source": [
139
+ "import io\n",
140
+ "\n",
141
+ "import ipywidgets as widgets\n",
142
+ "import matplotlib.pyplot as plt\n",
143
+ "import numpy as np\n",
144
+ "import PIL.Image\n",
145
+ "import requests\n",
146
+ "from IPython.display import clear_output, display, HTML\n",
147
+ "from matplotlib.patches import Rectangle\n",
148
+ "\n",
149
+ "\n",
150
+ "class Sam3SegmentationWidget:\n",
151
+ " \"\"\"Interactive Jupyter widget for SAM3 segmentation with text and box prompts.\"\"\"\n",
152
+ "\n",
153
+ " def __init__(self, processor):\n",
154
+ " \"\"\"\n",
155
+ " Initialize the segmentation widget.\n",
156
+ "\n",
157
+ " Args:\n",
158
+ " processor: Sam3Processor instance\n",
159
+ " \"\"\"\n",
160
+ " self.processor = processor\n",
161
+ " self.state = None\n",
162
+ " self.current_image = None\n",
163
+ " self.current_image_array = None\n",
164
+ " self.box_mode = \"positive\"\n",
165
+ " self.drawing_box = False\n",
166
+ " self.box_start = None\n",
167
+ " self.current_rect = None\n",
168
+ "\n",
169
+ " self._setup_ui()\n",
170
+ " self._setup_plot()\n",
171
+ "\n",
172
+ " def _setup_ui(self):\n",
173
+ " \"\"\"Set up the UI components.\"\"\"\n",
174
+ " self.upload_widget = widgets.FileUpload(\n",
175
+ " accept=\"image/*\", multiple=False, description=\"Upload Image\"\n",
176
+ " )\n",
177
+ " self.upload_widget.observe(self._on_image_upload, names=\"value\")\n",
178
+ "\n",
179
+ " self.url_input = widgets.Text(\n",
180
+ " placeholder=\"Or enter image URL\",\n",
181
+ " )\n",
182
+ " self.url_button = widgets.Button(description=\"Load URL\", button_style=\"info\")\n",
183
+ " self.url_button.on_click(self._on_load_url)\n",
184
+ " url_box = widgets.HBox(\n",
185
+ " [self.url_input, self.url_button],\n",
186
+ " layout=widgets.Layout(width=\"100%\", justify_content=\"space-between\"),\n",
187
+ " )\n",
188
+ "\n",
189
+ " self.text_input = widgets.Text(\n",
190
+ " placeholder='Enter segmentation prompt (e.g., \"person\", \"dog\")',\n",
191
+ " continuous_update=False,\n",
192
+ " )\n",
193
+ " self.text_input.observe(self._on_text_submit, names=\"value\")\n",
194
+ " self.text_button = widgets.Button(description=\"Segment\", button_style=\"success\")\n",
195
+ " self.text_button.on_click(self._on_text_prompt)\n",
196
+ " text_box = widgets.HBox(\n",
197
+ " [self.text_input, self.text_button],\n",
198
+ " layout=widgets.Layout(width=\"100%\", justify_content=\"space-between\"),\n",
199
+ " )\n",
200
+ "\n",
201
+ " self.box_mode_buttons = widgets.ToggleButtons(\n",
202
+ " options=[\"Positive Boxes\", \"Negative Boxes\"],\n",
203
+ " description=\"Box Mode:\",\n",
204
+ " button_style=\"\",\n",
205
+ " tooltips=[\n",
206
+ " \"Draw boxes around objects to include\",\n",
207
+ " \"Draw boxes around objects to exclude\",\n",
208
+ " ],\n",
209
+ " )\n",
210
+ " self.box_mode_buttons.observe(self._on_box_mode_change, names=\"value\")\n",
211
+ "\n",
212
+ " self.clear_button = widgets.Button(\n",
213
+ " description=\"Clear All Prompts\", button_style=\"warning\"\n",
214
+ " )\n",
215
+ " self.clear_button.on_click(self._on_clear_prompts)\n",
216
+ "\n",
217
+ " self.confidence_slider = widgets.FloatSlider(\n",
218
+ " value=0.5,\n",
219
+ " min=0.0,\n",
220
+ " max=1.0,\n",
221
+ " step=0.01,\n",
222
+ " description=\"Confidence:\",\n",
223
+ " continuous_update=False,\n",
224
+ " style={\"description_width\": \"initial\"},\n",
225
+ " )\n",
226
+ " self.confidence_slider.observe(self._on_confidence_change, names=\"value\")\n",
227
+ "\n",
228
+ " self.size_slider = widgets.IntSlider(\n",
229
+ " value=960,\n",
230
+ " min=300,\n",
231
+ " max=2000,\n",
232
+ " step=10,\n",
233
+ " description=\"Image Size:\",\n",
234
+ " continuous_update=False,\n",
235
+ " style={\"description_width\": \"initial\"},\n",
236
+ " )\n",
237
+ " self.size_slider.observe(self._on_size_change, names=\"value\")\n",
238
+ "\n",
239
+ " slider_box = widgets.HBox(\n",
240
+ " [self.confidence_slider, self.size_slider],\n",
241
+ " layout=widgets.Layout(justify_content=\"space-between\"),\n",
242
+ " )\n",
243
+ "\n",
244
+ " self.output = widgets.Output()\n",
245
+ " self.status_label = widgets.Label(value=\"Upload an image to begin\")\n",
246
+ "\n",
247
+ " # This box will hold our matplotlib output and we can target it with CSS.\n",
248
+ " self.plot_container = widgets.Box([self.output])\n",
249
+ " self.plot_container.add_class(\"no-drag\")\n",
250
+ "\n",
251
+ " # CSS to make the cursor a crosshair over the matplotlib canvas\n",
252
+ " css_style = widgets.HTML(\n",
253
+ " \"\"\"\n",
254
+ " <style>\n",
255
+ " .jupyter-matplotlib-canvas, canvas {\n",
256
+ " cursor: crosshair !important;\n",
257
+ " }\n",
258
+ " </style>\n",
259
+ " \"\"\"\n",
260
+ " )\n",
261
+ " # Create VBoxes for each accordion pane\n",
262
+ " source_pane = widgets.VBox([self.upload_widget, url_box])\n",
263
+ " prompt_pane = widgets.VBox(\n",
264
+ " [\n",
265
+ " widgets.Label(\"Text Prompt:\"),\n",
266
+ " text_box,\n",
267
+ " self.box_mode_buttons,\n",
268
+ " self.confidence_slider,\n",
269
+ " self.clear_button,\n",
270
+ " ]\n",
271
+ " )\n",
272
+ " display_pane = widgets.VBox([self.size_slider])\n",
273
+ "\n",
274
+ " # Create the Accordion to hold the control panes\n",
275
+ " self.accordion = widgets.Accordion(\n",
276
+ " children=[source_pane, prompt_pane, display_pane]\n",
277
+ " )\n",
278
+ " self.accordion.set_title(0, \"Image Source\")\n",
279
+ " self.accordion.set_title(1, \"Segmentation Prompts\")\n",
280
+ " self.accordion.set_title(2, \"Display Settings\")\n",
281
+ " self.accordion.selected_index = 0 # Start with the first pane open\n",
282
+ "\n",
283
+ " # Create the left sidebar for controls\n",
284
+ " sidebar = widgets.VBox(\n",
285
+ " [self.status_label, widgets.HTML(\"<h4>Controls</h4>\"), self.accordion]\n",
286
+ " )\n",
287
+ " sidebar.layout = widgets.Layout(\n",
288
+ " width=\"380px\",\n",
289
+ " min_width=\"380px\",\n",
290
+ " max_width=\"380px\",\n",
291
+ " border=\"1px solid #e0e0e0\",\n",
292
+ " padding=\"10px\",\n",
293
+ " margin=\"0 15px 0 0\",\n",
294
+ " flex=\"0 0 auto\",\n",
295
+ " )\n",
296
+ "\n",
297
+ " # Create the main area for the image display\n",
298
+ " main_area = widgets.VBox([self.plot_container])\n",
299
+ " main_area.layout = widgets.Layout(flex=\"1\", min_width=\"500px\", overflow=\"auto\")\n",
300
+ "\n",
301
+ " # Combine sidebar and main area into the final app layout\n",
302
+ " app_layout = widgets.HBox([sidebar, main_area])\n",
303
+ " app_layout.layout = widgets.Layout(\n",
304
+ " width=\"100%\",\n",
305
+ " display=\"flex\",\n",
306
+ " flex_flow=\"row\",\n",
307
+ " align_items=\"stretch\",\n",
308
+ " )\n",
309
+ "\n",
310
+ " # Set the main container\n",
311
+ " self.container = widgets.VBox(\n",
312
+ " [\n",
313
+ " css_style,\n",
314
+ " widgets.HTML(\"<h3>🖼️ SAM3 Interactive Segmentation</h3>\"),\n",
315
+ " app_layout,\n",
316
+ " ]\n",
317
+ " )\n",
318
+ "\n",
319
+ " def _setup_plot(self):\n",
320
+ " \"\"\"Set up the matplotlib figure.\"\"\"\n",
321
+ " # plt.ioff()\n",
322
+ " self.fig, self.ax = plt.subplots(figsize=(12, 8))\n",
323
+ " # plt.ion()\n",
324
+ " self.ax.axis(\"off\")\n",
325
+ " self.fig.subplots_adjust(left=0, right=1, top=1, bottom=0)\n",
326
+ " self.fig.canvas.toolbar_visible = False\n",
327
+ " self.fig.canvas.header_visible = False\n",
328
+ " self.fig.canvas.footer_visible = False\n",
329
+ " self.fig.canvas.resizable = False\n",
330
+ "\n",
331
+ " # plt.close(self.fig)\n",
332
+ "\n",
333
+ " def _set_loading(self, is_loading, message=\"Processing...\"):\n",
334
+ " \"\"\"Show/hide loading state and disable/enable controls.\"\"\"\n",
335
+ " if is_loading:\n",
336
+ " self.status_label.value = f\"⏳ {message}\"\n",
337
+ " self.upload_widget.disabled = True\n",
338
+ " self.url_button.disabled = True\n",
339
+ " self.text_button.disabled = True\n",
340
+ " self.clear_button.disabled = True\n",
341
+ " self.box_mode_buttons.disabled = True\n",
342
+ " self.confidence_slider.disabled = True\n",
343
+ " else:\n",
344
+ " self.upload_widget.disabled = False\n",
345
+ " self.url_button.disabled = False\n",
346
+ " self.text_button.disabled = False\n",
347
+ " self.clear_button.disabled = False\n",
348
+ " self.box_mode_buttons.disabled = False\n",
349
+ " self.confidence_slider.disabled = False\n",
350
+ "\n",
351
+ " def _on_image_upload(self, change):\n",
352
+ " \"\"\"Handle image upload.\"\"\"\n",
353
+ " if change[\"new\"]:\n",
354
+ " uploaded_file = change[\"new\"][0]\n",
355
+ " image = PIL.Image.open(io.BytesIO(uploaded_file[\"content\"])).convert(\"RGB\")\n",
356
+ " self._set_image(image)\n",
357
+ "\n",
358
+ " def _on_load_url(self, button):\n",
359
+ " \"\"\"Handle loading image from URL.\"\"\"\n",
360
+ " url = self.url_input.value.strip()\n",
361
+ " if not url:\n",
362
+ " self.status_label.value = \"Please enter a URL\"\n",
363
+ " return\n",
364
+ "\n",
365
+ " self._set_loading(True, \"Downloading image from URL...\")\n",
366
+ "\n",
367
+ " try:\n",
368
+ " response = requests.get(url, timeout=10)\n",
369
+ " response.raise_for_status()\n",
370
+ " image = PIL.Image.open(io.BytesIO(response.content)).convert(\"RGB\")\n",
371
+ " self._set_image(image)\n",
372
+ " except Exception as e:\n",
373
+ " self._set_loading(False)\n",
374
+ " self.status_label.value = f\"Error loading image: {str(e)}\"\n",
375
+ "\n",
376
+ " def _set_image(self, image):\n",
377
+ " \"\"\"Set the current image, adjust figure size, and initialize state.\"\"\"\n",
378
+ " self._set_loading(True, \"Processing image through model...\")\n",
379
+ "\n",
380
+ " try:\n",
381
+ "\n",
382
+ " self.current_image = image\n",
383
+ " self.current_image_array = np.array(image)\n",
384
+ " self.state = self.processor.set_image(image)\n",
385
+ " self._set_loading(False)\n",
386
+ " self.status_label.value = (\n",
387
+ " f\"Image loaded: {image.size[0]}x{image.size[1]} pixels\"\n",
388
+ " )\n",
389
+ " self._resize_figure()\n",
390
+ " self._update_display()\n",
391
+ " self._connect_plot_events()\n",
392
+ " self.accordion.selected_index = 1\n",
393
+ " except Exception as e:\n",
394
+ " self._set_loading(False)\n",
395
+ " self.status_label.value = f\"Error processing image: {str(e)}\"\n",
396
+ "\n",
397
+ " def _on_text_submit(self, change):\n",
398
+ " \"\"\"Handle text prompt submission via Enter key.\"\"\"\n",
399
+ " # Call the same handler as the button click\n",
400
+ " self._on_text_prompt(None)\n",
401
+ "\n",
402
+ " def _on_text_prompt(self, button):\n",
403
+ " \"\"\"Handle text prompt submission.\"\"\"\n",
404
+ " if self.state is None:\n",
405
+ " self.status_label.value = \"Please load an image first\"\n",
406
+ " return\n",
407
+ "\n",
408
+ " prompt = self.text_input.value.strip()\n",
409
+ " if not prompt:\n",
410
+ " self.status_label.value = \"Please enter a prompt\"\n",
411
+ " return\n",
412
+ "\n",
413
+ " self._set_loading(True, f'Segmenting with prompt: \"{prompt}\"...')\n",
414
+ "\n",
415
+ " try:\n",
416
+ " self.state = self.processor.set_text_prompt(prompt, self.state)\n",
417
+ " self._set_loading(False)\n",
418
+ " self.status_label.value = f'Segmented with prompt: \"{prompt}\"'\n",
419
+ " self._update_display()\n",
420
+ " except Exception as e:\n",
421
+ " self._set_loading(False)\n",
422
+ " self.status_label.value = f\"Error: {str(e)}\"\n",
423
+ "\n",
424
+ " def _on_box_mode_change(self, change):\n",
425
+ " \"\"\"Handle box mode toggle.\"\"\"\n",
426
+ " self.box_mode = \"positive\" if change[\"new\"] == \"Positive Boxes\" else \"negative\"\n",
427
+ "\n",
428
+ " def _on_clear_prompts(self, button):\n",
429
+ " \"\"\"Clear all prompts and reset to image only.\"\"\"\n",
430
+ " if self.current_image is not None:\n",
431
+ " try:\n",
432
+ " self._set_loading(True, \"Clearing prompts and resetting...\")\n",
433
+ " self.state = self.processor.reset_all_prompts(self.state)\n",
434
+ " if \"prompted_boxes\" in self.state:\n",
435
+ " del self.state[\"prompted_boxes\"]\n",
436
+ " self.text_input.value = \"\"\n",
437
+ " self._set_loading(False)\n",
438
+ " self.status_label.value = \"Cleared all prompts\"\n",
439
+ " self._update_display()\n",
440
+ " except Exception as e:\n",
441
+ " self._set_loading(False)\n",
442
+ " import traceback\n",
443
+ "\n",
444
+ " self.status_label.value = f\"Error: {str(e)} {traceback.format_exc()}\"\n",
445
+ "\n",
446
+ " def _on_confidence_change(self, change):\n",
447
+ " \"\"\"Handle confidence threshold change.\"\"\"\n",
448
+ " if self.state is not None:\n",
449
+ " self.state = self.processor.set_confidence_threshold(\n",
450
+ " change[\"new\"], self.state\n",
451
+ " )\n",
452
+ " self._update_display()\n",
453
+ "\n",
454
+ " def _connect_plot_events(self):\n",
455
+ " \"\"\"Connect matplotlib event handlers for box drawing.\"\"\"\n",
456
+ " # Disable matplotlib's toolbar navigation to allow custom box drawing\n",
457
+ " if hasattr(self.fig.canvas, \"toolbar\") and self.fig.canvas.toolbar is not None:\n",
458
+ " self.fig.canvas.toolbar.pan()\n",
459
+ " self.fig.canvas.toolbar.pan()\n",
460
+ "\n",
461
+ " self.fig.canvas.mpl_connect(\"button_press_event\", self._on_press)\n",
462
+ " self.fig.canvas.mpl_connect(\"button_release_event\", self._on_release)\n",
463
+ " self.fig.canvas.mpl_connect(\"motion_notify_event\", self._on_motion)\n",
464
+ "\n",
465
+ " def _on_press(self, event):\n",
466
+ " \"\"\"Handle mouse press for box drawing.\"\"\"\n",
467
+ " if event.inaxes != self.ax:\n",
468
+ " return\n",
469
+ " self.drawing_box = True\n",
470
+ " self.box_start = (event.xdata, event.ydata)\n",
471
+ "\n",
472
+ " def _on_motion(self, event):\n",
473
+ " \"\"\"Handle mouse motion for box preview.\"\"\"\n",
474
+ " if not self.drawing_box or event.inaxes != self.ax or self.box_start is None:\n",
475
+ " return\n",
476
+ "\n",
477
+ " if self.current_rect is not None:\n",
478
+ " self.current_rect.remove()\n",
479
+ "\n",
480
+ " x0, y0 = self.box_start\n",
481
+ " x1, y1 = event.xdata, event.ydata\n",
482
+ " width = x1 - x0\n",
483
+ " height = y1 - y0\n",
484
+ "\n",
485
+ " color = \"green\" if self.box_mode == \"positive\" else \"red\"\n",
486
+ " self.current_rect = Rectangle(\n",
487
+ " (x0, y0),\n",
488
+ " width,\n",
489
+ " height,\n",
490
+ " fill=False,\n",
491
+ " edgecolor=color,\n",
492
+ " linewidth=2,\n",
493
+ " linestyle=\"--\",\n",
494
+ " )\n",
495
+ " self.ax.add_patch(self.current_rect)\n",
496
+ " self.fig.canvas.draw_idle()\n",
497
+ "\n",
498
+ " def _on_release(self, event):\n",
499
+ " \"\"\"Handle mouse release to finalize box.\"\"\"\n",
500
+ " if not self.drawing_box or event.inaxes != self.ax or self.box_start is None:\n",
501
+ " self.drawing_box = False\n",
502
+ " return\n",
503
+ "\n",
504
+ " self.drawing_box = False\n",
505
+ "\n",
506
+ " if self.current_rect is not None:\n",
507
+ " self.current_rect.remove()\n",
508
+ " self.current_rect = None\n",
509
+ "\n",
510
+ " if self.state is None:\n",
511
+ " return\n",
512
+ "\n",
513
+ " x0, y0 = self.box_start\n",
514
+ " x1, y1 = event.xdata, event.ydata\n",
515
+ "\n",
516
+ " x_min = min(x0, x1)\n",
517
+ " x_max = max(x0, x1)\n",
518
+ " y_min = min(y0, y1)\n",
519
+ " y_max = max(y0, y1)\n",
520
+ "\n",
521
+ " if abs(x_max - x_min) < 5 or abs(y_max - y_min) < 5:\n",
522
+ " return\n",
523
+ "\n",
524
+ " # Get image dimensions\n",
525
+ " img_h = self.state[\"original_height\"]\n",
526
+ " img_w = self.state[\"original_width\"]\n",
527
+ "\n",
528
+ " # Convert from xyxy pixel coordinates to cxcywh normalized format\n",
529
+ " center_x = (x_min + x_max) / 2.0 / img_w\n",
530
+ " center_y = (y_min + y_max) / 2.0 / img_h\n",
531
+ " width = (x_max - x_min) / img_w\n",
532
+ " height = (y_max - y_min) / img_h\n",
533
+ "\n",
534
+ " box = [center_x, center_y, width, height]\n",
535
+ " label = self.box_mode == \"positive\"\n",
536
+ " mode_str = \"positive\" if label else \"negative\"\n",
537
+ "\n",
538
+ " # Store the prompted box in pixel coordinates for display\n",
539
+ " if \"prompted_boxes\" not in self.state:\n",
540
+ " self.state[\"prompted_boxes\"] = []\n",
541
+ " self.state[\"prompted_boxes\"].append(\n",
542
+ " {\"box\": [x_min, y_min, x_max, y_max], \"label\": label}\n",
543
+ " )\n",
544
+ "\n",
545
+ " self._set_loading(True, f\"Adding {mode_str} box and re-segmenting...\")\n",
546
+ "\n",
547
+ " try:\n",
548
+ " self.state = self.processor.add_geometric_prompt(box, label, self.state)\n",
549
+ " self._set_loading(False)\n",
550
+ " self.status_label.value = f\"Added {mode_str} box\"\n",
551
+ " self._update_display()\n",
552
+ " except Exception as e:\n",
553
+ " self._set_loading(False)\n",
554
+ " self.status_label.value = f\"Error adding box: {str(e)}\"\n",
555
+ "\n",
556
+ " def _resize_figure(self):\n",
557
+ " \"\"\"Calculate and apply new figure size based on image and slider value.\"\"\"\n",
558
+ " if self.current_image is None:\n",
559
+ " return\n",
560
+ "\n",
561
+ " # 1. Get original image dimensions\n",
562
+ " img_w, img_h = self.current_image.size\n",
563
+ "\n",
564
+ " # 2. The slider's value is now the direct target width for the display\n",
565
+ " display_w = float(self.size_slider.value)\n",
566
+ "\n",
567
+ " # 3. Calculate the corresponding height to maintain the original aspect ratio\n",
568
+ " aspect_ratio = img_h / img_w\n",
569
+ " display_h = int(display_w * aspect_ratio)\n",
570
+ "\n",
571
+ " # 4. Convert pixel dimensions to inches for Matplotlib and apply\n",
572
+ " dpi = self.fig.dpi\n",
573
+ " new_figsize = (display_w / dpi, display_h / dpi)\n",
574
+ " self.fig.set_size_inches(new_figsize, forward=True)\n",
575
+ "\n",
576
+ " def _on_size_change(self, change):\n",
577
+ " \"\"\"Handle a change from the image size slider.\"\"\"\n",
578
+ " if self.current_image is not None:\n",
579
+ " self._resize_figure()\n",
580
+ " # After resizing the canvas, we must redraw the content\n",
581
+ " self._update_display()\n",
582
+ "\n",
583
+ " def _update_display(self):\n",
584
+ " \"\"\"Update the display with current results.\"\"\"\n",
585
+ " if self.current_image_array is None:\n",
586
+ " return\n",
587
+ "\n",
588
+ " with self.output:\n",
589
+ " clear_output(wait=True)\n",
590
+ "\n",
591
+ " self.ax.clear()\n",
592
+ " self.ax.axis(\"off\")\n",
593
+ " self.ax.imshow(self.current_image_array)\n",
594
+ "\n",
595
+ " if self.state is not None and \"masks\" in self.state:\n",
596
+ " masks = self.state.get(\"masks\", [])\n",
597
+ " boxes = self.state.get(\"boxes\", [])\n",
598
+ " scores = self.state.get(\"scores\", [])\n",
599
+ "\n",
600
+ " if len(masks) > 0:\n",
601
+ " mask_overlay = np.zeros((*self.current_image_array.shape[:2], 4))\n",
602
+ "\n",
603
+ " for i, (mask, box, score) in enumerate(zip(masks, boxes, scores)):\n",
604
+ " mask_np = mask[0].cpu().numpy()\n",
605
+ "\n",
606
+ " color = plt.cm.tab10(i % 10)[:3]\n",
607
+ " mask_overlay[mask_np > 0.5] = (*color, 0.5)\n",
608
+ "\n",
609
+ " x0, y0, x1, y1 = box.cpu().numpy()\n",
610
+ " rect = Rectangle(\n",
611
+ " (x0, y0),\n",
612
+ " x1 - x0,\n",
613
+ " y1 - y0,\n",
614
+ " fill=False,\n",
615
+ " edgecolor=color,\n",
616
+ " linewidth=2,\n",
617
+ " )\n",
618
+ " self.ax.add_patch(rect)\n",
619
+ "\n",
620
+ " self.ax.text(\n",
621
+ " x0,\n",
622
+ " y0 - 5,\n",
623
+ " f\"{score:.2f}\",\n",
624
+ " color=\"white\",\n",
625
+ " fontsize=10,\n",
626
+ " bbox=dict(\n",
627
+ " facecolor=color, alpha=0.7, edgecolor=\"none\", pad=2\n",
628
+ " ),\n",
629
+ " )\n",
630
+ "\n",
631
+ " self.ax.imshow(mask_overlay)\n",
632
+ " self.status_label.value = f\"Found {len(masks)} object(s)\"\n",
633
+ " else:\n",
634
+ " self.status_label.value = (\n",
635
+ " \"No objects found above confidence threshold\"\n",
636
+ " )\n",
637
+ "\n",
638
+ " # Display prompted boxes with dashed lines\n",
639
+ " if self.state is not None and \"prompted_boxes\" in self.state:\n",
640
+ " for prompted_box in self.state[\"prompted_boxes\"]:\n",
641
+ " box_coords = prompted_box[\"box\"]\n",
642
+ " is_positive = prompted_box[\"label\"]\n",
643
+ "\n",
644
+ " x0, y0, x1, y1 = box_coords\n",
645
+ " color = \"green\" if is_positive else \"red\"\n",
646
+ "\n",
647
+ " rect = Rectangle(\n",
648
+ " (x0, y0),\n",
649
+ " x1 - x0,\n",
650
+ " y1 - y0,\n",
651
+ " fill=False,\n",
652
+ " edgecolor=color,\n",
653
+ " linewidth=2,\n",
654
+ " linestyle=\"--\",\n",
655
+ " )\n",
656
+ " self.ax.add_patch(rect)\n",
657
+ "\n",
658
+ " # display(self.fig.canvas)\n",
659
+ "\n",
660
+ " def display(self):\n",
661
+ " display(self.container)\n",
662
+ "\n",
663
+ " # Add this for more convenient display in notebooks\n",
664
+ " def _ipython_display_(self):\n",
665
+ " self.display()\n"
666
+ ]
667
+ },
668
+ {
669
+ "cell_type": "markdown",
670
+ "id": "1b9bda74-b455-4957-9767-2a46a041b50f",
671
+ "metadata": {},
672
+ "source": [
673
+ "# Run!"
674
+ ]
675
+ },
676
+ {
677
+ "cell_type": "code",
678
+ "execution_count": 10,
679
+ "id": "ebfb9b85-2318-4328-bb0e-e93e4a57fefe",
680
+ "metadata": {},
681
+ "outputs": [
682
+ {
683
+ "data": {
684
+ "application/vnd.jupyter.widget-view+json": {
685
+ "model_id": "ea0e04a1bfd7486b93baae650d87e0b2",
686
+ "version_major": 2,
687
+ "version_minor": 0
688
+ },
689
+ "text/plain": [
690
+ "VBox(children=(HTML(value='\\n <style>\\n .jupyter-matplotlib-canvas, canvas {\\n …"
691
+ ]
692
+ },
693
+ "metadata": {},
694
+ "output_type": "display_data"
695
+ },
696
+ {
697
+ "data": {
698
+ "application/vnd.jupyter.widget-view+json": {
699
+ "model_id": "bbdcb3374c29461bb379d4bf9c319a49",
700
+ "version_major": 2,
701
+ "version_minor": 0
702
+ },
703
+ "image/png": "iVBORw0KGgoAAAANSUhEUgAABLAAAAMgCAYAAAAz4JsCAAAAOnRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjEwLjYsIGh0dHBzOi8vbWF0cGxvdGxpYi5vcmcvq6yFwwAAAAlwSFlzAAAPYQAAD2EBqD+naQAAFf1JREFUeJzt2DEBACAMwDDAv+fhgJceiYLe3TMzCwAAAACizu8AAAAAAHgxsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEi710EKPFzQ9BwAAAAASUVORK5CYII=",
704
+ "text/html": [
705
+ "\n",
706
+ " <div style=\"display: inline-block;\">\n",
707
+ " <div class=\"jupyter-widgets widget-label\" style=\"text-align: center;\">\n",
708
+ " Figure\n",
709
+ " </div>\n",
710
+ " <img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABLAAAAMgCAYAAAAz4JsCAAAAOnRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjEwLjYsIGh0dHBzOi8vbWF0cGxvdGxpYi5vcmcvq6yFwwAAAAlwSFlzAAAPYQAAD2EBqD+naQAAFf1JREFUeJzt2DEBACAMwDDAv+fhgJceiYLe3TMzCwAAAACizu8AAAAAAHgxsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEi710EKPFzQ9BwAAAAASUVORK5CYII=' width=1200.0/>\n",
711
+ " </div>\n",
712
+ " "
713
+ ],
714
+ "text/plain": [
715
+ "Canvas(footer_visible=False, header_visible=False, resizable=False, toolbar=Toolbar(toolitems=[('Home', 'Reset…"
716
+ ]
717
+ },
718
+ "metadata": {},
719
+ "output_type": "display_data"
720
+ }
721
+ ],
722
+ "source": [
723
+ "widget = Sam3SegmentationWidget(processor)\n",
724
+ "widget.display()"
725
+ ]
726
+ },
727
+ {
728
+ "cell_type": "code",
729
+ "execution_count": null,
730
+ "id": "50a14560-573a-4784-9f55-689fda9147be",
731
+ "metadata": {},
732
+ "outputs": [],
733
+ "source": []
734
+ }
735
+ ],
736
+ "metadata": {
737
+ "kernelspec": {
738
+ "display_name": "Python 3 (ipykernel)",
739
+ "language": "python",
740
+ "name": "python3"
741
+ },
742
+ "language_info": {
743
+ "codemirror_mode": {
744
+ "name": "ipython",
745
+ "version": 3
746
+ },
747
+ "file_extension": ".py",
748
+ "mimetype": "text/x-python",
749
+ "name": "python",
750
+ "nbconvert_exporter": "python",
751
+ "pygments_lexer": "ipython3",
752
+ "version": "3.12.11"
753
+ }
754
+ },
755
+ "nbformat": 4,
756
+ "nbformat_minor": 5
757
+ }
third_party/GraspGen/sam3/examples/sam3_image_predictor_example.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
third_party/GraspGen/sam3/examples/sam3_video_predictor_example.ipynb ADDED
@@ -0,0 +1,1603 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "metadata": {
7
+ "bentoAICellStatus": "none",
8
+ "bentoCellName": {
9
+ "name": "License Information",
10
+ "origin": "ai"
11
+ },
12
+ "collapsed": false,
13
+ "customOutput": null,
14
+ "executionStartTime": 1762496606600,
15
+ "executionStopTime": 1762496607864,
16
+ "isCommentPanelOpen": false,
17
+ "jupyter": {
18
+ "outputs_hidden": false
19
+ },
20
+ "language": "python",
21
+ "metadata": {
22
+ "bentoAICellStatus": "none",
23
+ "bentoCellName": {
24
+ "name": "Copyright Notice",
25
+ "origin": "ai"
26
+ },
27
+ "collapsed": false,
28
+ "customInput": null,
29
+ "customOutput": null,
30
+ "executionStartTime": 1761950741027,
31
+ "executionStopTime": 1761950741468,
32
+ "isCommentPanelOpen": false,
33
+ "language": "python",
34
+ "originalKey": "49a54601-c2fe-47f2-a436-9a1f91503520",
35
+ "outputsInitialized": true,
36
+ "requestMsgId": "da31cd52-f746-4a69-bfae-b2037e84d00c",
37
+ "serverExecutionDuration": 2.3454379988834,
38
+ "showInput": true
39
+ },
40
+ "originalKey": "913d6f63-449f-4836-ae81-7d55a42ccf8c",
41
+ "output": {
42
+ "id": 863592039347424,
43
+ "loadingStatus": "loaded"
44
+ },
45
+ "outputsInitialized": false,
46
+ "requestMsgId": "913d6f63-449f-4836-ae81-7d55a42ccf8c",
47
+ "serverExecutionDuration": 2.4641010004416
48
+ },
49
+ "outputs": [],
50
+ "source": [
51
+ "# Copyright (c) Meta Platforms, Inc. and affiliates."
52
+ ]
53
+ },
54
+ {
55
+ "cell_type": "markdown",
56
+ "metadata": {
57
+ "attachments": [],
58
+ "bentoAICellStatus": "none",
59
+ "isCommentPanelOpen": false,
60
+ "language": "markdown",
61
+ "metadata": {
62
+ "bentoAICellStatus": "none",
63
+ "customInput": null,
64
+ "isCommentPanelOpen": false,
65
+ "language": "markdown",
66
+ "originalKey": "50280cd0-12eb-4f23-a78d-c37f5bda1fe6",
67
+ "outputsInitialized": false,
68
+ "showInput": false
69
+ },
70
+ "originalKey": "9e88cae8-b006-498d-9a02-c1c369a95f57",
71
+ "outputsInitialized": false,
72
+ "showInput": true
73
+ },
74
+ "source": [
75
+ "## Video segmentation and tracking with SAM 3\n",
76
+ "\n",
77
+ "This notebook demonstrates how to use SAM 3 for interactive video segmentation and dense tracking. It covers the following capabilities:\n",
78
+ "\n",
79
+ "- **Text prompts**: Using natural language descriptions to segment objects (e.g., \"person\", \"shoe\")\n",
80
+ "- **Point prompts**: Adding positive/negative clicks to segment and refine objects\n",
81
+ "\n",
82
+ "We use the terms _segment_ or _mask_ to refer to the model prediction for an object on a single frame, and _masklet_ to refer to the spatio-temporal masks across the entire video. "
83
+ ]
84
+ },
85
+ {
86
+ "cell_type": "markdown",
87
+ "metadata": {},
88
+ "source": [
89
+ "# <a target=\"_blank\" href=\"https://colab.research.google.com/github/facebookresearch/sam3/blob/main/notebooks/sam3_video_predictor_example.ipynb\">\n",
90
+ "# <img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/>\n",
91
+ "# </a>"
92
+ ]
93
+ },
94
+ {
95
+ "cell_type": "code",
96
+ "execution_count": null,
97
+ "metadata": {},
98
+ "outputs": [],
99
+ "source": [
100
+ "using_colab = False"
101
+ ]
102
+ },
103
+ {
104
+ "cell_type": "code",
105
+ "execution_count": null,
106
+ "metadata": {},
107
+ "outputs": [],
108
+ "source": [
109
+ "if using_colab:\n",
110
+ " import torch\n",
111
+ " import torchvision\n",
112
+ " print(\"PyTorch version:\", torch.__version__)\n",
113
+ " print(\"Torchvision version:\", torchvision.__version__)\n",
114
+ " print(\"CUDA is available:\", torch.cuda.is_available())\n",
115
+ " import sys\n",
116
+ " !{sys.executable} -m pip install opencv-python matplotlib scikit-learn\n",
117
+ " !{sys.executable} -m pip install 'git+https://github.com/facebookresearch/sam3.git'"
118
+ ]
119
+ },
120
+ {
121
+ "cell_type": "code",
122
+ "execution_count": null,
123
+ "metadata": {
124
+ "bentoAICellStatus": "none",
125
+ "bentoCellName": {
126
+ "name": "Display GPU Status",
127
+ "origin": "ai"
128
+ },
129
+ "customOutput": null,
130
+ "executionStartTime": 1762496607874,
131
+ "executionStopTime": 1762496609713,
132
+ "isCommentPanelOpen": false,
133
+ "language": "python",
134
+ "metadata": {
135
+ "bentoAICellStatus": "none",
136
+ "bentoCellName": {
137
+ "name": "Check GPU Status",
138
+ "origin": "ai"
139
+ },
140
+ "collapsed": false,
141
+ "customInput": null,
142
+ "customOutput": null,
143
+ "executionStartTime": 1761950741471,
144
+ "executionStopTime": 1761950742878,
145
+ "isCommentPanelOpen": false,
146
+ "language": "python",
147
+ "originalKey": "c3f5a31b-c8df-45db-ae6d-0d219ee60382",
148
+ "outputsInitialized": true,
149
+ "requestMsgId": "cea571e0-345b-461d-b2ee-8f95e0ea4b4e",
150
+ "serverExecutionDuration": 1091.9901590096,
151
+ "showInput": true
152
+ },
153
+ "originalKey": "fb0eb6a0-acd2-4c80-bacd-bafd09669e7e",
154
+ "output": {
155
+ "id": "794918370206651",
156
+ "loadingStatus": "before loading"
157
+ },
158
+ "outputsInitialized": true,
159
+ "requestMsgId": "fb0eb6a0-acd2-4c80-bacd-bafd09669e7e",
160
+ "serverExecutionDuration": 1123.5525669999
161
+ },
162
+ "outputs": [],
163
+ "source": [
164
+ "!nvidia-smi"
165
+ ]
166
+ },
167
+ {
168
+ "cell_type": "markdown",
169
+ "metadata": {
170
+ "attachments": [],
171
+ "bentoAICellStatus": "none",
172
+ "isCommentPanelOpen": false,
173
+ "language": "markdown",
174
+ "metadata": {
175
+ "bentoAICellStatus": "none",
176
+ "collapsed": false,
177
+ "customInput": null,
178
+ "executionStartTime": 1761927188199,
179
+ "executionStopTime": 1761927188659,
180
+ "isCommentPanelOpen": false,
181
+ "language": "markdown",
182
+ "originalKey": "8304fc58-e145-4f5f-8bdc-a6d2dfba8a04",
183
+ "outputsInitialized": false,
184
+ "requestMsgId": "8304fc58-e145-4f5f-8bdc-a6d2dfba8a04",
185
+ "serverExecutionDuration": 3.739742009202,
186
+ "showInput": false
187
+ },
188
+ "originalKey": "6702b9f4-54e9-46be-aca8-82ad9f96e9cc",
189
+ "outputsInitialized": false,
190
+ "showInput": false
191
+ },
192
+ "source": [
193
+ "## Set-up\n",
194
+ "\n",
195
+ "In this example, we allow running inference either on a single GPU or multiple GPUs."
196
+ ]
197
+ },
198
+ {
199
+ "cell_type": "code",
200
+ "execution_count": null,
201
+ "metadata": {
202
+ "bentoAICellStatus": "none",
203
+ "bentoCellName": {
204
+ "name": "Configure GPU Usage",
205
+ "origin": "ai"
206
+ },
207
+ "collapsed": false,
208
+ "customOutput": null,
209
+ "executionStartTime": 1762496609726,
210
+ "executionStopTime": 1762496617098,
211
+ "isCommentPanelOpen": false,
212
+ "jupyter": {
213
+ "outputs_hidden": false
214
+ },
215
+ "language": "python",
216
+ "metadata": {
217
+ "bentoAICellStatus": "none",
218
+ "bentoCellName": {
219
+ "name": "Import iopath library",
220
+ "origin": "ai"
221
+ },
222
+ "collapsed": false,
223
+ "customOutput": null,
224
+ "executionStartTime": 1761950742885,
225
+ "executionStopTime": 1761950745386,
226
+ "isCommentPanelOpen": false,
227
+ "language": "python",
228
+ "originalKey": "5faf15c7-5bbb-4b86-a9a8-70abbc76cba2",
229
+ "outputsInitialized": true,
230
+ "requestMsgId": "e63f2826-d537-4849-82ac-fe7280cc9de0",
231
+ "serverExecutionDuration": 2117.1291570063
232
+ },
233
+ "originalKey": "5d0ad6b6-0225-4371-9455-e6291e92604c",
234
+ "output": {
235
+ "id": "1459804151757142",
236
+ "loadingStatus": "before loading"
237
+ },
238
+ "outputsInitialized": true,
239
+ "requestMsgId": "5d0ad6b6-0225-4371-9455-e6291e92604c",
240
+ "serverExecutionDuration": 6628.1851309996
241
+ },
242
+ "outputs": [],
243
+ "source": [
244
+ "import os\n",
245
+ "import sam3\n",
246
+ "import torch\n",
247
+ "\n",
248
+ "sam3_root = os.path.join(os.path.dirname(sam3.__file__), \"..\")\n",
249
+ "\n",
250
+ "# use all available GPUs on the machine\n",
251
+ "gpus_to_use = range(torch.cuda.device_count())\n",
252
+ "# # use only a single GPU\n",
253
+ "# gpus_to_use = [torch.cuda.current_device()]"
254
+ ]
255
+ },
256
+ {
257
+ "cell_type": "code",
258
+ "execution_count": null,
259
+ "metadata": {
260
+ "bentoAICellStatus": "none",
261
+ "bentoCellName": {
262
+ "name": "Initialize Video Predictor",
263
+ "origin": "ai"
264
+ },
265
+ "collapsed": false,
266
+ "customOutput": null,
267
+ "executionStartTime": 1762496617103,
268
+ "executionStopTime": 1762496677439,
269
+ "isCommentPanelOpen": false,
270
+ "jupyter": {
271
+ "outputs_hidden": false
272
+ },
273
+ "language": "python",
274
+ "metadata": {
275
+ "bentoAICellStatus": "none",
276
+ "bentoCellName": {
277
+ "name": "Import Video Predictor",
278
+ "origin": "ai"
279
+ },
280
+ "collapsed": false,
281
+ "customInput": null,
282
+ "customOutput": null,
283
+ "executionStartTime": 1761950750102,
284
+ "executionStopTime": 1761950806603,
285
+ "isCommentPanelOpen": false,
286
+ "language": "python",
287
+ "originalKey": "01683eda-e85f-4af6-9d91-86b3f1822170",
288
+ "outputsInitialized": true,
289
+ "requestMsgId": "822fb211-d78e-4d1c-92fa-848e0e755100",
290
+ "serverExecutionDuration": 55998.664824001,
291
+ "showInput": true
292
+ },
293
+ "originalKey": "aea5a4b9-de9f-46ed-9fd1-20928ab60d2e",
294
+ "output": {
295
+ "id": "1581259049706846",
296
+ "loadingStatus": "before loading"
297
+ },
298
+ "outputsInitialized": true,
299
+ "requestMsgId": "aea5a4b9-de9f-46ed-9fd1-20928ab60d2e",
300
+ "serverExecutionDuration": 59514.871851999
301
+ },
302
+ "outputs": [],
303
+ "source": [
304
+ "from sam3.model_builder import build_sam3_video_predictor\n",
305
+ "\n",
306
+ "predictor = build_sam3_video_predictor(gpus_to_use=gpus_to_use)"
307
+ ]
308
+ },
309
+ {
310
+ "attachments": {},
311
+ "cell_type": "markdown",
312
+ "metadata": {
313
+ "bentoAICellStatus": "none",
314
+ "collapsed": false,
315
+ "customInput": null,
316
+ "executionStartTime": 1762140878760,
317
+ "executionStopTime": 1762140879318,
318
+ "isCommentPanelOpen": false,
319
+ "jupyter": {
320
+ "outputs_hidden": false
321
+ },
322
+ "language": "markdown",
323
+ "originalKey": "2cb37dda-a58c-46ae-85ff-118bb3ff4c02",
324
+ "outputsInitialized": false,
325
+ "requestMsgId": "2cb37dda-a58c-46ae-85ff-118bb3ff4c02",
326
+ "serverExecutionDuration": 3.7622059462592,
327
+ "showInput": false
328
+ },
329
+ "source": [
330
+ "#### Inference and visualization utils"
331
+ ]
332
+ },
333
+ {
334
+ "cell_type": "code",
335
+ "execution_count": null,
336
+ "metadata": {
337
+ "bentoAICellStatus": "none",
338
+ "bentoCellName": {
339
+ "name": "Set Up Video Processing",
340
+ "origin": "ai"
341
+ },
342
+ "collapsed": false,
343
+ "customInput": null,
344
+ "customOutput": null,
345
+ "executionStartTime": 1762496677450,
346
+ "executionStopTime": 1762496679879,
347
+ "isCommentPanelOpen": false,
348
+ "jupyter": {
349
+ "outputs_hidden": false
350
+ },
351
+ "language": "python",
352
+ "originalKey": "10d98ae4-dd65-4824-8469-960a9801ec72",
353
+ "output": {
354
+ "id": "1183417547004803",
355
+ "loadingStatus": "before loading"
356
+ },
357
+ "outputsInitialized": true,
358
+ "requestMsgId": "10d98ae4-dd65-4824-8469-960a9801ec72",
359
+ "serverExecutionDuration": 1535.9860829994,
360
+ "showInput": true
361
+ },
362
+ "outputs": [],
363
+ "source": [
364
+ "import glob\n",
365
+ "import os\n",
366
+ "\n",
367
+ "import cv2\n",
368
+ "import matplotlib.pyplot as plt\n",
369
+ "import numpy as np\n",
370
+ "from PIL import Image\n",
371
+ "from sam3.visualization_utils import (\n",
372
+ " load_frame,\n",
373
+ " prepare_masks_for_visualization,\n",
374
+ " visualize_formatted_frame_output,\n",
375
+ ")\n",
376
+ "\n",
377
+ "# font size for axes titles\n",
378
+ "plt.rcParams[\"axes.titlesize\"] = 12\n",
379
+ "plt.rcParams[\"figure.titlesize\"] = 12\n",
380
+ "\n",
381
+ "\n",
382
+ "def propagate_in_video(predictor, session_id):\n",
383
+ " # we will just propagate from frame 0 to the end of the video\n",
384
+ " outputs_per_frame = {}\n",
385
+ " for response in predictor.handle_stream_request(\n",
386
+ " request=dict(\n",
387
+ " type=\"propagate_in_video\",\n",
388
+ " session_id=session_id,\n",
389
+ " )\n",
390
+ " ):\n",
391
+ " outputs_per_frame[response[\"frame_index\"]] = response[\"outputs\"]\n",
392
+ "\n",
393
+ " return outputs_per_frame\n",
394
+ "\n",
395
+ "\n",
396
+ "def abs_to_rel_coords(coords, IMG_WIDTH, IMG_HEIGHT, coord_type=\"point\"):\n",
397
+ " \"\"\"Convert absolute coordinates to relative coordinates (0-1 range)\n",
398
+ "\n",
399
+ " Args:\n",
400
+ " coords: List of coordinates\n",
401
+ " coord_type: 'point' for [x, y] or 'box' for [x, y, w, h]\n",
402
+ " \"\"\"\n",
403
+ " if coord_type == \"point\":\n",
404
+ " return [[x / IMG_WIDTH, y / IMG_HEIGHT] for x, y in coords]\n",
405
+ " elif coord_type == \"box\":\n",
406
+ " return [\n",
407
+ " [x / IMG_WIDTH, y / IMG_HEIGHT, w / IMG_WIDTH, h / IMG_HEIGHT]\n",
408
+ " for x, y, w, h in coords\n",
409
+ " ]\n",
410
+ " else:\n",
411
+ " raise ValueError(f\"Unknown coord_type: {coord_type}\")"
412
+ ]
413
+ },
414
+ {
415
+ "cell_type": "markdown",
416
+ "metadata": {
417
+ "attachments": [],
418
+ "bentoAICellStatus": "none",
419
+ "isCommentPanelOpen": false,
420
+ "language": "markdown",
421
+ "metadata": {
422
+ "bentoAICellStatus": "none",
423
+ "customInput": null,
424
+ "isCommentPanelOpen": false,
425
+ "language": "markdown",
426
+ "originalKey": "2e38c5fe-1aa7-4000-9778-25e240daf5e5",
427
+ "outputsInitialized": false,
428
+ "showInput": false
429
+ },
430
+ "originalKey": "7f803ec4-a343-43c9-9be3-5d3b9b66ae9a",
431
+ "outputsInitialized": false,
432
+ "showInput": false
433
+ },
434
+ "source": [
435
+ "### Loading an example video\n",
436
+ "\n",
437
+ "We assume that the video is stored as either **a list of JPEG frames with filenames like `<frame_index>.jpg`** or **an MP4 video**.\n",
438
+ "\n",
439
+ "Note that you can extract their JPEG frames using ffmpeg (https://ffmpeg.org/) as follows:\n",
440
+ "```\n",
441
+ "ffmpeg -i <your_video>.mp4 -q:v 2 -start_number 0 <output_dir>/'%05d.jpg'\n",
442
+ "```\n",
443
+ "where `-q:v` generates high-quality JPEG frames and `-start_number 0` asks ffmpeg to start the JPEG file from `00000.jpg`."
444
+ ]
445
+ },
446
+ {
447
+ "cell_type": "code",
448
+ "execution_count": null,
449
+ "metadata": {
450
+ "bentoAICellStatus": "none",
451
+ "bentoCellName": {
452
+ "name": "Set video path",
453
+ "origin": "ai"
454
+ },
455
+ "collapsed": false,
456
+ "customOutput": null,
457
+ "executionStartTime": 1762496679887,
458
+ "executionStopTime": 1762496680687,
459
+ "isCommentPanelOpen": false,
460
+ "jupyter": {
461
+ "outputs_hidden": false
462
+ },
463
+ "language": "python",
464
+ "metadata": {
465
+ "bentoAICellStatus": "none",
466
+ "bentoCellName": {
467
+ "name": "Print SAM3 Directory Path",
468
+ "origin": "ai"
469
+ },
470
+ "collapsed": false,
471
+ "customInput": null,
472
+ "customOutput": null,
473
+ "executionStartTime": 1761950806610,
474
+ "executionStopTime": 1761950807097,
475
+ "isCommentPanelOpen": false,
476
+ "language": "python",
477
+ "originalKey": "59540fba-3749-4498-bd14-c28fb7d61dbc",
478
+ "outputsInitialized": true,
479
+ "requestMsgId": "2807b3b8-a4fb-41e9-9976-67e2cd1f2ca2",
480
+ "serverExecutionDuration": 5.3407719824463,
481
+ "showInput": true
482
+ },
483
+ "originalKey": "92d7b964-a3e4-4efb-98d4-202344994413",
484
+ "outputsInitialized": false,
485
+ "requestMsgId": "92d7b964-a3e4-4efb-98d4-202344994413",
486
+ "serverExecutionDuration": 3.5114740003337
487
+ },
488
+ "outputs": [],
489
+ "source": [
490
+ "# \"video_path\" needs to be either a JPEG folder or a MP4 video file\n",
491
+ "video_path = f\"{sam3_root}/assets/videos/0001\""
492
+ ]
493
+ },
494
+ {
495
+ "cell_type": "code",
496
+ "execution_count": null,
497
+ "metadata": {
498
+ "bentoAICellStatus": "none",
499
+ "bentoCellName": {
500
+ "name": "Load Video Frames for Visualization",
501
+ "origin": "ai"
502
+ },
503
+ "collapsed": false,
504
+ "customOutput": null,
505
+ "executionStartTime": 1762496680695,
506
+ "executionStopTime": 1762496681428,
507
+ "isCommentPanelOpen": false,
508
+ "jupyter": {
509
+ "outputs_hidden": false
510
+ },
511
+ "language": "python",
512
+ "metadata": {
513
+ "bentoAICellStatus": "none",
514
+ "bentoCellName": {
515
+ "name": "Load Video Frames for Visualization",
516
+ "origin": "ai"
517
+ },
518
+ "collapsed": false,
519
+ "customInput": null,
520
+ "customOutput": null,
521
+ "executionStartTime": 1761950807101,
522
+ "executionStopTime": 1761950807480,
523
+ "isCommentPanelOpen": false,
524
+ "language": "python",
525
+ "originalKey": "86f88968-93c4-4ca1-81fc-7fad55ccd566",
526
+ "outputsInitialized": true,
527
+ "requestMsgId": "96b17a72-b889-4a1f-af98-b40c773780f7",
528
+ "serverExecutionDuration": 7.6176410075277,
529
+ "showInput": true
530
+ },
531
+ "originalKey": "10fe83fd-eb12-4400-a8ac-b6e137819136",
532
+ "outputsInitialized": false,
533
+ "requestMsgId": "10fe83fd-eb12-4400-a8ac-b6e137819136",
534
+ "serverExecutionDuration": 8.1744140006776
535
+ },
536
+ "outputs": [],
537
+ "source": [
538
+ "# load \"video_frames_for_vis\" for visualization purposes (they are not used by the model)\n",
539
+ "if isinstance(video_path, str) and video_path.endswith(\".mp4\"):\n",
540
+ " cap = cv2.VideoCapture(video_path)\n",
541
+ " video_frames_for_vis = []\n",
542
+ " while True:\n",
543
+ " ret, frame = cap.read()\n",
544
+ " if not ret:\n",
545
+ " break\n",
546
+ " video_frames_for_vis.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))\n",
547
+ " cap.release()\n",
548
+ "else:\n",
549
+ " video_frames_for_vis = glob.glob(os.path.join(video_path, \"*.jpg\"))\n",
550
+ " try:\n",
551
+ " # integer sort instead of string sort (so that e.g. \"2.jpg\" is before \"11.jpg\")\n",
552
+ " video_frames_for_vis.sort(\n",
553
+ " key=lambda p: int(os.path.splitext(os.path.basename(p))[0])\n",
554
+ " )\n",
555
+ " except ValueError:\n",
556
+ " # fallback to lexicographic sort if the format is not \"<frame_index>.jpg\"\n",
557
+ " print(\n",
558
+ " f'frame names are not in \"<frame_index>.jpg\" format: {video_frames_for_vis[:5]=}, '\n",
559
+ " f\"falling back to lexicographic sort.\"\n",
560
+ " )\n",
561
+ " video_frames_for_vis.sort()"
562
+ ]
563
+ },
564
+ {
565
+ "cell_type": "markdown",
566
+ "metadata": {
567
+ "attachments": [],
568
+ "bentoAICellStatus": "none",
569
+ "isCommentPanelOpen": false,
570
+ "language": "markdown",
571
+ "metadata": {
572
+ "bentoAICellStatus": "none",
573
+ "customInput": null,
574
+ "isCommentPanelOpen": false,
575
+ "language": "markdown",
576
+ "originalKey": "2f67df56-df50-470d-bb6d-f736a592dd47",
577
+ "outputsInitialized": false,
578
+ "showInput": false
579
+ },
580
+ "originalKey": "552fbb00-7387-4014-9161-7f9c32418701",
581
+ "outputsInitialized": false,
582
+ "showInput": false
583
+ },
584
+ "source": [
585
+ "### Opening an inference session on this video\n",
586
+ "\n",
587
+ "SAM 3 requires stateful inference for interactive video segmentation, so we need to initialize an **inference session** on this video.\n",
588
+ "\n",
589
+ "During initialization, it loads all the video frames and stores their pixels in the session state."
590
+ ]
591
+ },
592
+ {
593
+ "cell_type": "code",
594
+ "execution_count": null,
595
+ "metadata": {
596
+ "bentoAICellStatus": "none",
597
+ "bentoCellName": {
598
+ "name": "Start Video Session",
599
+ "origin": "ai"
600
+ },
601
+ "collapsed": false,
602
+ "customOutput": null,
603
+ "executionStartTime": 1762496681434,
604
+ "executionStopTime": 1762496694273,
605
+ "isCommentPanelOpen": false,
606
+ "jupyter": {
607
+ "outputs_hidden": false
608
+ },
609
+ "language": "python",
610
+ "metadata": {
611
+ "bentoAICellStatus": "none",
612
+ "bentoCellName": {
613
+ "name": "Start Video Session",
614
+ "origin": "ai"
615
+ },
616
+ "collapsed": false,
617
+ "customInput": null,
618
+ "customOutput": null,
619
+ "executionStartTime": 1761950807485,
620
+ "executionStopTime": 1761950821459,
621
+ "isCommentPanelOpen": false,
622
+ "language": "python",
623
+ "originalKey": "eec3ee85-e95a-4fa7-8401-921fba35d6ee",
624
+ "outputsInitialized": true,
625
+ "requestMsgId": "262d936d-486c-4a75-8f25-ad2a2832c3f8",
626
+ "serverExecutionDuration": 13503.750298987,
627
+ "showInput": true
628
+ },
629
+ "originalKey": "2b5917e0-95da-409a-b2c6-4868fe5ff88e",
630
+ "output": {
631
+ "id": "816533627765185",
632
+ "loadingStatus": "before loading"
633
+ },
634
+ "outputsInitialized": true,
635
+ "requestMsgId": "2b5917e0-95da-409a-b2c6-4868fe5ff88e",
636
+ "serverExecutionDuration": 11971.027362999
637
+ },
638
+ "outputs": [],
639
+ "source": [
640
+ "response = predictor.handle_request(\n",
641
+ " request=dict(\n",
642
+ " type=\"start_session\",\n",
643
+ " resource_path=video_path,\n",
644
+ " )\n",
645
+ ")\n",
646
+ "session_id = response[\"session_id\"]"
647
+ ]
648
+ },
649
+ {
650
+ "cell_type": "markdown",
651
+ "metadata": {
652
+ "attachments": [],
653
+ "bentoAICellStatus": "none",
654
+ "isCommentPanelOpen": false,
655
+ "language": "markdown",
656
+ "metadata": {
657
+ "bentoAICellStatus": "none",
658
+ "customInput": null,
659
+ "isCommentPanelOpen": false,
660
+ "language": "markdown",
661
+ "originalKey": "4d26ec1b-d78f-4054-879a-cbf06b84a79f",
662
+ "outputsInitialized": false,
663
+ "showInput": false
664
+ },
665
+ "originalKey": "1da36b65-5759-4803-be41-ec6d2ec8c5d9",
666
+ "outputsInitialized": false,
667
+ "showInput": false
668
+ },
669
+ "source": [
670
+ "### Video promptable concept segmentation with text\n",
671
+ "\n",
672
+ "Using SAM 3 you can describe objects using natural language, and the model will automatically detect and track all instances of that object throughout the video.\n",
673
+ "\n",
674
+ "In the example below, we add a text prompt on frame 0 and propagation throughout the video. Here we use the text prompt \"person\" to detect all people in the video. SAM 3 will automatically identify multiple person instances and assign each a unique object ID.\n",
675
+ "\n",
676
+ "Note that the first call might be slower due to setting up buffers. **You can rerun all the cells below when measuring speed.**"
677
+ ]
678
+ },
679
+ {
680
+ "cell_type": "code",
681
+ "execution_count": null,
682
+ "metadata": {
683
+ "bentoAICellStatus": "none",
684
+ "bentoCellName": {
685
+ "name": "Reset Session",
686
+ "origin": "ai"
687
+ },
688
+ "collapsed": false,
689
+ "customOutput": null,
690
+ "executionStartTime": 1762496694278,
691
+ "executionStopTime": 1762496694675,
692
+ "isCommentPanelOpen": false,
693
+ "jupyter": {
694
+ "outputs_hidden": false
695
+ },
696
+ "language": "python",
697
+ "metadata": {
698
+ "bentoAICellStatus": "none",
699
+ "bentoCellName": {
700
+ "name": "Reset Prediction Session",
701
+ "origin": "ai"
702
+ },
703
+ "collapsed": false,
704
+ "customInput": null,
705
+ "customOutput": null,
706
+ "executionStartTime": 1761950821467,
707
+ "executionStopTime": 1761950821992,
708
+ "isCommentPanelOpen": false,
709
+ "language": "python",
710
+ "originalKey": "be47ff32-7721-43c2-a1ad-b9d1689cf1c1",
711
+ "outputsInitialized": true,
712
+ "requestMsgId": "c5eb2442-0530-4408-9ace-ba74e7441cf6",
713
+ "serverExecutionDuration": 10.527236998314,
714
+ "showInput": true
715
+ },
716
+ "originalKey": "f61b9bc5-5ec7-4c72-9071-e50bedb89f0a",
717
+ "output": {
718
+ "id": "4255598051433217",
719
+ "loadingStatus": "before loading"
720
+ },
721
+ "outputsInitialized": true,
722
+ "requestMsgId": "f61b9bc5-5ec7-4c72-9071-e50bedb89f0a",
723
+ "serverExecutionDuration": 9.9740919995384
724
+ },
725
+ "outputs": [],
726
+ "source": [
727
+ "# note: in case you already ran one text prompt and now want to switch to another text prompt\n",
728
+ "# it's required to reset the session first (otherwise the results would be wrong)\n",
729
+ "_ = predictor.handle_request(\n",
730
+ " request=dict(\n",
731
+ " type=\"reset_session\",\n",
732
+ " session_id=session_id,\n",
733
+ " )\n",
734
+ ")"
735
+ ]
736
+ },
737
+ {
738
+ "cell_type": "code",
739
+ "execution_count": null,
740
+ "metadata": {
741
+ "bentoAICellStatus": "none",
742
+ "bentoCellName": {
743
+ "name": "Add Text Prompt",
744
+ "origin": "ai"
745
+ },
746
+ "collapsed": false,
747
+ "customOutput": null,
748
+ "executionStartTime": 1762496694678,
749
+ "executionStopTime": 1762496699791,
750
+ "isCommentPanelOpen": false,
751
+ "jupyter": {
752
+ "outputs_hidden": false
753
+ },
754
+ "language": "python",
755
+ "metadata": {
756
+ "bentoAICellStatus": "none",
757
+ "bentoCellName": {
758
+ "name": "Add Prompt to Frame",
759
+ "origin": "ai"
760
+ },
761
+ "collapsed": false,
762
+ "customInput": null,
763
+ "customOutput": null,
764
+ "executionStartTime": 1761950821995,
765
+ "executionStopTime": 1761950825751,
766
+ "isCommentPanelOpen": false,
767
+ "language": "python",
768
+ "originalKey": "ca780545-a450-4ed8-a192-f6033e0288ba",
769
+ "outputsInitialized": true,
770
+ "requestMsgId": "d784487d-5758-40a4-8a66-1ea26ad3bcfd",
771
+ "serverExecutionDuration": 3358.8370049838,
772
+ "showInput": true
773
+ },
774
+ "originalKey": "55538638-8336-4b1c-9daf-517c0dc31806",
775
+ "output": {
776
+ "id": "2083947459075035",
777
+ "loadingStatus": "before loading"
778
+ },
779
+ "outputsInitialized": true,
780
+ "requestMsgId": "55538638-8336-4b1c-9daf-517c0dc31806",
781
+ "serverExecutionDuration": 3957.4137909985
782
+ },
783
+ "outputs": [],
784
+ "source": [
785
+ "prompt_text_str = \"person\"\n",
786
+ "frame_idx = 0 # add a text prompt on frame 0\n",
787
+ "response = predictor.handle_request(\n",
788
+ " request=dict(\n",
789
+ " type=\"add_prompt\",\n",
790
+ " session_id=session_id,\n",
791
+ " frame_index=frame_idx,\n",
792
+ " text=prompt_text_str,\n",
793
+ " )\n",
794
+ ")\n",
795
+ "out = response[\"outputs\"]\n",
796
+ "\n",
797
+ "plt.close(\"all\")\n",
798
+ "visualize_formatted_frame_output(\n",
799
+ " frame_idx,\n",
800
+ " video_frames_for_vis,\n",
801
+ " outputs_list=[prepare_masks_for_visualization({frame_idx: out})],\n",
802
+ " titles=[\"SAM 3 Dense Tracking outputs\"],\n",
803
+ " figsize=(6, 4),\n",
804
+ ")"
805
+ ]
806
+ },
807
+ {
808
+ "cell_type": "code",
809
+ "execution_count": null,
810
+ "metadata": {
811
+ "bentoAICellStatus": "none",
812
+ "bentoCellName": {
813
+ "name": "Visualize Video Outputs",
814
+ "origin": "ai"
815
+ },
816
+ "collapsed": false,
817
+ "customOutput": null,
818
+ "executionStartTime": 1762496699796,
819
+ "executionStopTime": 1762496734325,
820
+ "isCommentPanelOpen": false,
821
+ "jupyter": {
822
+ "outputs_hidden": false
823
+ },
824
+ "language": "python",
825
+ "metadata": {
826
+ "bentoAICellStatus": "none",
827
+ "bentoCellName": {
828
+ "name": "Visualize Video Outputs",
829
+ "origin": "ai"
830
+ },
831
+ "collapsed": false,
832
+ "customInput": null,
833
+ "customOutput": null,
834
+ "executionStartTime": 1761950827402,
835
+ "executionStopTime": 1761950861260,
836
+ "isCommentPanelOpen": false,
837
+ "language": "python",
838
+ "originalKey": "06edc7da-9dd1-42e8-b502-0afdbfbaddc2",
839
+ "outputsInitialized": true,
840
+ "requestMsgId": "33659e9c-a817-40fe-b3b7-727b7a344d74",
841
+ "serverExecutionDuration": 33374.819626013,
842
+ "showInput": true
843
+ },
844
+ "originalKey": "41e1b095-80a4-4997-9b3e-2baa28dba05f",
845
+ "output": {
846
+ "id": "2605449593181328",
847
+ "loadingStatus": "before loading"
848
+ },
849
+ "outputsInitialized": true,
850
+ "requestMsgId": "41e1b095-80a4-4997-9b3e-2baa28dba05f",
851
+ "serverExecutionDuration": 33588.144188001
852
+ },
853
+ "outputs": [],
854
+ "source": [
855
+ "# now we propagate the outputs from frame 0 to the end of the video and collect all outputs\n",
856
+ "outputs_per_frame = propagate_in_video(predictor, session_id)\n",
857
+ "\n",
858
+ "# finally, we reformat the outputs for visualization and plot the outputs every 60 frames\n",
859
+ "outputs_per_frame = prepare_masks_for_visualization(outputs_per_frame)\n",
860
+ "\n",
861
+ "vis_frame_stride = 60\n",
862
+ "plt.close(\"all\")\n",
863
+ "for frame_idx in range(0, len(outputs_per_frame), vis_frame_stride):\n",
864
+ " visualize_formatted_frame_output(\n",
865
+ " frame_idx,\n",
866
+ " video_frames_for_vis,\n",
867
+ " outputs_list=[outputs_per_frame],\n",
868
+ " titles=[\"SAM 3 Dense Tracking outputs\"],\n",
869
+ " figsize=(6, 4),\n",
870
+ " )"
871
+ ]
872
+ },
873
+ {
874
+ "attachments": {},
875
+ "cell_type": "markdown",
876
+ "metadata": {
877
+ "bentoAICellStatus": "none",
878
+ "customInput": null,
879
+ "isCommentPanelOpen": false,
880
+ "language": "markdown",
881
+ "originalKey": "e341c66f-6083-4731-b8e1-ebc7b4177a43",
882
+ "outputsInitialized": false,
883
+ "showInput": false
884
+ },
885
+ "source": [
886
+ "### Removing objects\n",
887
+ "\n",
888
+ "We can remove individual objects using their id.\n",
889
+ "\n",
890
+ "As an example, let's remove object 2 (which is the dancer in the front)."
891
+ ]
892
+ },
893
+ {
894
+ "cell_type": "code",
895
+ "execution_count": null,
896
+ "metadata": {
897
+ "bentoAICellStatus": "none",
898
+ "bentoCellName": {
899
+ "name": "Remove Front Dancer",
900
+ "origin": "ai"
901
+ },
902
+ "collapsed": false,
903
+ "customInput": null,
904
+ "customOutput": null,
905
+ "executionStartTime": 1762496734333,
906
+ "executionStopTime": 1762496735487,
907
+ "isCommentPanelOpen": false,
908
+ "jupyter": {
909
+ "outputs_hidden": false
910
+ },
911
+ "language": "python",
912
+ "originalKey": "cf97330e-68f5-4f4e-931f-bc5b6faa77ff",
913
+ "output": {
914
+ "id": "1345936250272478",
915
+ "loadingStatus": "before loading"
916
+ },
917
+ "outputsInitialized": true,
918
+ "requestMsgId": "cf97330e-68f5-4f4e-931f-bc5b6faa77ff",
919
+ "serverExecutionDuration": 127.66883199947,
920
+ "showInput": true
921
+ },
922
+ "outputs": [],
923
+ "source": [
924
+ "# we pick id 2, which is the dancer in the front\n",
925
+ "obj_id = 2\n",
926
+ "response = predictor.handle_request(\n",
927
+ " request=dict(\n",
928
+ " type=\"remove_object\",\n",
929
+ " session_id=session_id,\n",
930
+ " obj_id=obj_id,\n",
931
+ " )\n",
932
+ ")"
933
+ ]
934
+ },
935
+ {
936
+ "cell_type": "code",
937
+ "execution_count": null,
938
+ "metadata": {
939
+ "bentoAICellStatus": "none",
940
+ "bentoCellName": {
941
+ "name": "Visualize Video Outputs",
942
+ "origin": "ai"
943
+ },
944
+ "collapsed": false,
945
+ "customInput": null,
946
+ "customOutput": null,
947
+ "executionStartTime": 1762496735493,
948
+ "executionStopTime": 1762496742056,
949
+ "isCommentPanelOpen": false,
950
+ "jupyter": {
951
+ "outputs_hidden": false
952
+ },
953
+ "language": "python",
954
+ "originalKey": "a4552ab0-1b08-42b6-b90d-bfd1814c9398",
955
+ "output": {
956
+ "id": "1747332999309403",
957
+ "loadingStatus": "before loading"
958
+ },
959
+ "outputsInitialized": true,
960
+ "requestMsgId": "a4552ab0-1b08-42b6-b90d-bfd1814c9398",
961
+ "serverExecutionDuration": 5491.8713629995,
962
+ "showInput": true
963
+ },
964
+ "outputs": [],
965
+ "source": [
966
+ "# now we propagate the outputs from frame 0 to the end of the video and collect all outputs\n",
967
+ "outputs_per_frame = propagate_in_video(predictor, session_id)\n",
968
+ "\n",
969
+ "# finally, we reformat the outputs for visualization and plot the outputs every 60 frames\n",
970
+ "outputs_per_frame = prepare_masks_for_visualization(outputs_per_frame)\n",
971
+ "\n",
972
+ "vis_frame_stride = 60\n",
973
+ "plt.close(\"all\")\n",
974
+ "for frame_idx in range(0, len(outputs_per_frame), vis_frame_stride):\n",
975
+ " visualize_formatted_frame_output(\n",
976
+ " frame_idx,\n",
977
+ " video_frames_for_vis,\n",
978
+ " outputs_list=[outputs_per_frame],\n",
979
+ " titles=[\"SAM 3 Dense Tracking outputs\"],\n",
980
+ " figsize=(6, 4),\n",
981
+ " )"
982
+ ]
983
+ },
984
+ {
985
+ "attachments": {},
986
+ "cell_type": "markdown",
987
+ "metadata": {
988
+ "bentoAICellStatus": "none",
989
+ "customInput": null,
990
+ "isCommentPanelOpen": false,
991
+ "language": "markdown",
992
+ "originalKey": "4606cb85-5007-4b11-baa6-41ce9017de8e",
993
+ "outputsInitialized": false,
994
+ "showInput": false
995
+ },
996
+ "source": [
997
+ "### Adding new objects with point prompts\n",
998
+ "\n",
999
+ "We can add new objects through point prompts.\n",
1000
+ "\n",
1001
+ "Assuming that we've changed our mind, and now that we want to add back the dancer in the front (whom we just removed in the step above). We can use interactive clicks to add her back."
1002
+ ]
1003
+ },
1004
+ {
1005
+ "cell_type": "code",
1006
+ "execution_count": null,
1007
+ "metadata": {
1008
+ "bentoAICellStatus": "none",
1009
+ "bentoCellName": {
1010
+ "name": "Get image dimensions",
1011
+ "origin": "ai"
1012
+ },
1013
+ "collapsed": false,
1014
+ "customInput": null,
1015
+ "customOutput": null,
1016
+ "executionStartTime": 1762496742064,
1017
+ "executionStopTime": 1762496743435,
1018
+ "isCommentPanelOpen": false,
1019
+ "jupyter": {
1020
+ "outputs_hidden": false
1021
+ },
1022
+ "language": "python",
1023
+ "originalKey": "2ad8f8e9-49d8-4003-ad2f-f289ab5befc8",
1024
+ "outputsInitialized": false,
1025
+ "requestMsgId": "2ad8f8e9-49d8-4003-ad2f-f289ab5befc8",
1026
+ "serverExecutionDuration": 15.222899999571,
1027
+ "showInput": true
1028
+ },
1029
+ "outputs": [],
1030
+ "source": [
1031
+ "sample_img = Image.fromarray(load_frame(video_frames_for_vis[0]))\n",
1032
+ "\n",
1033
+ "IMG_WIDTH, IMG_HEIGHT = sample_img.size"
1034
+ ]
1035
+ },
1036
+ {
1037
+ "cell_type": "code",
1038
+ "execution_count": null,
1039
+ "metadata": {
1040
+ "bentoAICellStatus": "none",
1041
+ "bentoCellName": {
1042
+ "name": "Convert Absolute to Relative Coordinates",
1043
+ "origin": "ai"
1044
+ },
1045
+ "collapsed": false,
1046
+ "customInput": null,
1047
+ "customOutput": null,
1048
+ "executionStartTime": 1762496743442,
1049
+ "executionStopTime": 1762496744333,
1050
+ "isCommentPanelOpen": false,
1051
+ "jupyter": {
1052
+ "outputs_hidden": false
1053
+ },
1054
+ "language": "python",
1055
+ "originalKey": "3baca8f9-8e19-46da-a320-29524ddbf950",
1056
+ "outputsInitialized": false,
1057
+ "requestMsgId": "3baca8f9-8e19-46da-a320-29524ddbf950",
1058
+ "serverExecutionDuration": 3.9295850001508,
1059
+ "showInput": true
1060
+ },
1061
+ "outputs": [],
1062
+ "source": [
1063
+ "# let's add back the dancer via point prompts.\n",
1064
+ "# we will use a single positive click to add the dancer back.\n",
1065
+ "\n",
1066
+ "frame_idx = 0\n",
1067
+ "obj_id = 2\n",
1068
+ "points_abs = np.array(\n",
1069
+ " [\n",
1070
+ " [760, 550], # positive click\n",
1071
+ " ]\n",
1072
+ ")\n",
1073
+ "# positive clicks have label 1, while negative clicks have label 0\n",
1074
+ "labels = np.array([1])"
1075
+ ]
1076
+ },
1077
+ {
1078
+ "cell_type": "code",
1079
+ "execution_count": null,
1080
+ "metadata": {
1081
+ "bentoAICellStatus": "none",
1082
+ "bentoCellName": {
1083
+ "name": "Display Data Points",
1084
+ "origin": "ai"
1085
+ },
1086
+ "collapsed": false,
1087
+ "customInput": null,
1088
+ "customOutput": null,
1089
+ "executionStartTime": 1762496744337,
1090
+ "executionStopTime": 1762496748117,
1091
+ "isCommentPanelOpen": false,
1092
+ "jupyter": {
1093
+ "outputs_hidden": false
1094
+ },
1095
+ "language": "python",
1096
+ "originalKey": "865e951f-8d0a-41bf-8d51-72092703e3cf",
1097
+ "output": {
1098
+ "id": "1240547311311464",
1099
+ "loadingStatus": "before loading"
1100
+ },
1101
+ "outputsInitialized": true,
1102
+ "requestMsgId": "865e951f-8d0a-41bf-8d51-72092703e3cf",
1103
+ "serverExecutionDuration": 1224.9363859992,
1104
+ "showInput": true
1105
+ },
1106
+ "outputs": [],
1107
+ "source": [
1108
+ "# convert points and labels to tensors; also convert to relative coordinates\n",
1109
+ "points_tensor = torch.tensor(\n",
1110
+ " abs_to_rel_coords(points_abs, IMG_WIDTH, IMG_HEIGHT, coord_type=\"point\"),\n",
1111
+ " dtype=torch.float32,\n",
1112
+ ")\n",
1113
+ "points_labels_tensor = torch.tensor(labels, dtype=torch.int32)\n",
1114
+ "\n",
1115
+ "response = predictor.handle_request(\n",
1116
+ " request=dict(\n",
1117
+ " type=\"add_prompt\",\n",
1118
+ " session_id=session_id,\n",
1119
+ " frame_index=frame_idx,\n",
1120
+ " points=points_tensor,\n",
1121
+ " point_labels=points_labels_tensor,\n",
1122
+ " obj_id=obj_id,\n",
1123
+ " )\n",
1124
+ ")\n",
1125
+ "out = response[\"outputs\"]\n",
1126
+ "\n",
1127
+ "plt.close(\"all\")\n",
1128
+ "visualize_formatted_frame_output(\n",
1129
+ " frame_idx,\n",
1130
+ " video_frames_for_vis,\n",
1131
+ " outputs_list=[prepare_masks_for_visualization({frame_idx: out})],\n",
1132
+ " titles=[\"SAM 3 Dense Tracking outputs\"],\n",
1133
+ " figsize=(6, 4),\n",
1134
+ " points_list=[points_abs],\n",
1135
+ " points_labels_list=[labels],\n",
1136
+ ")"
1137
+ ]
1138
+ },
1139
+ {
1140
+ "cell_type": "code",
1141
+ "execution_count": null,
1142
+ "metadata": {
1143
+ "bentoAICellStatus": "none",
1144
+ "bentoCellName": {
1145
+ "name": "Process Video Frames",
1146
+ "origin": "ai"
1147
+ },
1148
+ "collapsed": false,
1149
+ "customInput": null,
1150
+ "customOutput": null,
1151
+ "executionStartTime": 1762496748120,
1152
+ "executionStopTime": 1762496774486,
1153
+ "isCommentPanelOpen": false,
1154
+ "jupyter": {
1155
+ "outputs_hidden": false
1156
+ },
1157
+ "language": "python",
1158
+ "originalKey": "cf1d2dda-464b-4a6a-aff3-d729aa486ec3",
1159
+ "output": {
1160
+ "id": "824678093489712",
1161
+ "loadingStatus": "before loading"
1162
+ },
1163
+ "outputsInitialized": true,
1164
+ "requestMsgId": "cf1d2dda-464b-4a6a-aff3-d729aa486ec3",
1165
+ "serverExecutionDuration": 25528.605932001,
1166
+ "showInput": true
1167
+ },
1168
+ "outputs": [],
1169
+ "source": [
1170
+ "# now we propagate the outputs from frame 0 to the end of the video and collect all outputs\n",
1171
+ "outputs_per_frame = propagate_in_video(predictor, session_id)\n",
1172
+ "\n",
1173
+ "# finally, we reformat the outputs for visualization and plot the outputs every 60 frames\n",
1174
+ "outputs_per_frame = prepare_masks_for_visualization(outputs_per_frame)\n",
1175
+ "\n",
1176
+ "vis_frame_stride = 60\n",
1177
+ "plt.close(\"all\")\n",
1178
+ "for frame_idx in range(0, len(outputs_per_frame), vis_frame_stride):\n",
1179
+ " visualize_formatted_frame_output(\n",
1180
+ " frame_idx,\n",
1181
+ " video_frames_for_vis,\n",
1182
+ " outputs_list=[outputs_per_frame],\n",
1183
+ " titles=[\"SAM 3 Dense Tracking outputs\"],\n",
1184
+ " figsize=(6, 4),\n",
1185
+ " )"
1186
+ ]
1187
+ },
1188
+ {
1189
+ "attachments": {},
1190
+ "cell_type": "markdown",
1191
+ "metadata": {
1192
+ "bentoAICellStatus": "none",
1193
+ "customInput": null,
1194
+ "isCommentPanelOpen": false,
1195
+ "language": "markdown",
1196
+ "originalKey": "79b12d4e-cdf0-41b8-9939-bcc1d5422115",
1197
+ "outputsInitialized": false,
1198
+ "showInput": false
1199
+ },
1200
+ "source": [
1201
+ "### Refining an existing object with point prompts\n",
1202
+ "\n",
1203
+ "We can also refine the segmentation mask of an existing object through point prompts.\n",
1204
+ "\n",
1205
+ "Assuming that we've changed our mind (again) -- for Object ID 2 (the dancer in the front whom we just added back in the step above), now we only want to segment her T-shirt instead of her whole body. We can adjust the segmentation mask with a few more positive and negative clicks."
1206
+ ]
1207
+ },
1208
+ {
1209
+ "cell_type": "code",
1210
+ "execution_count": null,
1211
+ "metadata": {
1212
+ "bentoAICellStatus": "none",
1213
+ "bentoCellName": {
1214
+ "name": "Segment T-shirt with Clicks",
1215
+ "origin": "ai"
1216
+ },
1217
+ "collapsed": false,
1218
+ "customInput": null,
1219
+ "customOutput": null,
1220
+ "executionStartTime": 1762496774494,
1221
+ "executionStopTime": 1762496775380,
1222
+ "isCommentPanelOpen": false,
1223
+ "jupyter": {
1224
+ "outputs_hidden": false
1225
+ },
1226
+ "language": "python",
1227
+ "originalKey": "8114fb12-386d-45e0-b875-f74eee630d96",
1228
+ "outputsInitialized": false,
1229
+ "requestMsgId": "8114fb12-386d-45e0-b875-f74eee630d96",
1230
+ "serverExecutionDuration": 4.0469909999956,
1231
+ "showInput": true
1232
+ },
1233
+ "outputs": [],
1234
+ "source": [
1235
+ "# For the dancer in the front, suppose now we only want to segment her T-shirt instead of her whole body\n",
1236
+ "# we will use 2 positive clicks and 2 negative clicks to select her shirt.\n",
1237
+ "\n",
1238
+ "frame_idx = 0\n",
1239
+ "obj_id = 2\n",
1240
+ "points_abs = np.array(\n",
1241
+ " [\n",
1242
+ " [740, 450], # positive click\n",
1243
+ " [760, 630], # negative click\n",
1244
+ " [840, 640], # negative click\n",
1245
+ " [760, 550], # positive click\n",
1246
+ " ]\n",
1247
+ ")\n",
1248
+ "# positive clicks have label 1, while negative clicks have label 0\n",
1249
+ "labels = np.array([1, 0, 0, 1])"
1250
+ ]
1251
+ },
1252
+ {
1253
+ "cell_type": "code",
1254
+ "execution_count": null,
1255
+ "metadata": {
1256
+ "bentoAICellStatus": "none",
1257
+ "bentoCellName": {
1258
+ "name": "Process and Visualize Frame Outputs",
1259
+ "origin": "ai"
1260
+ },
1261
+ "collapsed": false,
1262
+ "customInput": null,
1263
+ "customOutput": null,
1264
+ "executionStartTime": 1762496775385,
1265
+ "executionStopTime": 1762496777685,
1266
+ "isCommentPanelOpen": false,
1267
+ "jupyter": {
1268
+ "outputs_hidden": false
1269
+ },
1270
+ "language": "python",
1271
+ "originalKey": "5e66f671-aa71-42d7-a68d-8dc6430df8fe",
1272
+ "output": {
1273
+ "id": "25486291537675748",
1274
+ "loadingStatus": "before loading"
1275
+ },
1276
+ "outputsInitialized": true,
1277
+ "requestMsgId": "5e66f671-aa71-42d7-a68d-8dc6430df8fe",
1278
+ "serverExecutionDuration": 1227.9235379992,
1279
+ "showInput": true
1280
+ },
1281
+ "outputs": [],
1282
+ "source": [
1283
+ "# convert points and labels to tensors; also convert to relative coordinates\n",
1284
+ "points_tensor = torch.tensor(\n",
1285
+ " abs_to_rel_coords(points_abs, IMG_WIDTH, IMG_HEIGHT, coord_type=\"point\"),\n",
1286
+ " dtype=torch.float32,\n",
1287
+ ")\n",
1288
+ "points_labels_tensor = torch.tensor(labels, dtype=torch.int32)\n",
1289
+ "\n",
1290
+ "response = predictor.handle_request(\n",
1291
+ " request=dict(\n",
1292
+ " type=\"add_prompt\",\n",
1293
+ " session_id=session_id,\n",
1294
+ " frame_index=frame_idx,\n",
1295
+ " points=points_tensor,\n",
1296
+ " point_labels=points_labels_tensor,\n",
1297
+ " obj_id=obj_id,\n",
1298
+ " )\n",
1299
+ ")\n",
1300
+ "out = response[\"outputs\"]\n",
1301
+ "\n",
1302
+ "plt.close(\"all\")\n",
1303
+ "visualize_formatted_frame_output(\n",
1304
+ " frame_idx,\n",
1305
+ " video_frames_for_vis,\n",
1306
+ " outputs_list=[prepare_masks_for_visualization({frame_idx: out})],\n",
1307
+ " titles=[\"SAM 3 Dense Tracking outputs\"],\n",
1308
+ " figsize=(6, 4),\n",
1309
+ " points_list=[points_abs],\n",
1310
+ " points_labels_list=[labels],\n",
1311
+ ")"
1312
+ ]
1313
+ },
1314
+ {
1315
+ "cell_type": "code",
1316
+ "execution_count": null,
1317
+ "metadata": {
1318
+ "bentoAICellStatus": "none",
1319
+ "bentoCellName": {
1320
+ "name": "Visualize Video Tracking Outputs",
1321
+ "origin": "ai"
1322
+ },
1323
+ "collapsed": false,
1324
+ "customInput": null,
1325
+ "customOutput": null,
1326
+ "executionStartTime": 1762496777688,
1327
+ "executionStopTime": 1762496803927,
1328
+ "isCommentPanelOpen": false,
1329
+ "jupyter": {
1330
+ "outputs_hidden": false
1331
+ },
1332
+ "language": "python",
1333
+ "originalKey": "5c4a35a7-e5cc-4c7d-ba05-25540665d125",
1334
+ "output": {
1335
+ "id": "1222230279729631",
1336
+ "loadingStatus": "before loading"
1337
+ },
1338
+ "outputsInitialized": true,
1339
+ "requestMsgId": "5c4a35a7-e5cc-4c7d-ba05-25540665d125",
1340
+ "serverExecutionDuration": 25325.393453,
1341
+ "showInput": true
1342
+ },
1343
+ "outputs": [],
1344
+ "source": [
1345
+ "# now we propagate the outputs from frame 0 to the end of the video and collect all outputs\n",
1346
+ "outputs_per_frame = propagate_in_video(predictor, session_id)\n",
1347
+ "\n",
1348
+ "# finally, we reformat the outputs for visualization and plot the outputs every 60 frames\n",
1349
+ "outputs_per_frame = prepare_masks_for_visualization(outputs_per_frame)\n",
1350
+ "\n",
1351
+ "vis_frame_stride = 60\n",
1352
+ "plt.close(\"all\")\n",
1353
+ "for frame_idx in range(0, len(outputs_per_frame), vis_frame_stride):\n",
1354
+ " visualize_formatted_frame_output(\n",
1355
+ " frame_idx,\n",
1356
+ " video_frames_for_vis,\n",
1357
+ " outputs_list=[outputs_per_frame],\n",
1358
+ " titles=[\"SAM 3 Dense Tracking outputs\"],\n",
1359
+ " figsize=(6, 4),\n",
1360
+ " )"
1361
+ ]
1362
+ },
1363
+ {
1364
+ "cell_type": "markdown",
1365
+ "metadata": {
1366
+ "attachments": [],
1367
+ "bentoAICellStatus": "none",
1368
+ "isCommentPanelOpen": false,
1369
+ "language": "markdown",
1370
+ "metadata": {
1371
+ "bentoAICellStatus": "none",
1372
+ "customInput": null,
1373
+ "isCommentPanelOpen": false,
1374
+ "language": "markdown",
1375
+ "originalKey": "3f8d998b-4585-4956-b15d-1d4078cf8927",
1376
+ "outputsInitialized": false,
1377
+ "showInput": false
1378
+ },
1379
+ "originalKey": "b1d99d9b-c26e-4d5a-a4a2-70aab345fd77",
1380
+ "outputsInitialized": false,
1381
+ "showInput": false
1382
+ },
1383
+ "source": [
1384
+ "### Close session\n",
1385
+ "\n",
1386
+ "Each session is tied to a single video. We can close the session after inference to free up its resources.\n",
1387
+ "\n",
1388
+ "(Then, you may start a new session on another video.)"
1389
+ ]
1390
+ },
1391
+ {
1392
+ "cell_type": "code",
1393
+ "execution_count": null,
1394
+ "metadata": {
1395
+ "bentoAICellStatus": "none",
1396
+ "bentoCellName": {
1397
+ "name": "Close inference session",
1398
+ "origin": "ai"
1399
+ },
1400
+ "collapsed": false,
1401
+ "customOutput": null,
1402
+ "executionStartTime": 1762496803937,
1403
+ "executionStopTime": 1762496805854,
1404
+ "isCommentPanelOpen": false,
1405
+ "jupyter": {
1406
+ "outputs_hidden": false
1407
+ },
1408
+ "language": "python",
1409
+ "metadata": {
1410
+ "bentoAICellStatus": "none",
1411
+ "bentoCellName": {
1412
+ "name": "Reset Session Request",
1413
+ "origin": "ai"
1414
+ },
1415
+ "collapsed": false,
1416
+ "customInput": null,
1417
+ "customOutput": null,
1418
+ "executionStartTime": 1761950861264,
1419
+ "executionStopTime": 1761950863082,
1420
+ "isCommentPanelOpen": false,
1421
+ "language": "python",
1422
+ "originalKey": "d08a9e5f-3563-4aa1-ba8a-9f94615e4d7e",
1423
+ "outputsInitialized": true,
1424
+ "requestMsgId": "6e872e9a-3803-418f-827d-f1d817ef9cb9",
1425
+ "serverExecutionDuration": 926.3133899949,
1426
+ "showInput": true
1427
+ },
1428
+ "originalKey": "4f94819e-de3c-49bc-a25f-0790b2fa2cfb",
1429
+ "output": {
1430
+ "id": "1532190008092267",
1431
+ "loadingStatus": "before loading"
1432
+ },
1433
+ "outputsInitialized": true,
1434
+ "requestMsgId": "4f94819e-de3c-49bc-a25f-0790b2fa2cfb",
1435
+ "serverExecutionDuration": 941.08029199924
1436
+ },
1437
+ "outputs": [],
1438
+ "source": [
1439
+ "# finally, close the inference session to free its GPU resources\n",
1440
+ "# (you may start a new session on another video)\n",
1441
+ "_ = predictor.handle_request(\n",
1442
+ " request=dict(\n",
1443
+ " type=\"close_session\",\n",
1444
+ " session_id=session_id,\n",
1445
+ " )\n",
1446
+ ")"
1447
+ ]
1448
+ },
1449
+ {
1450
+ "cell_type": "markdown",
1451
+ "metadata": {
1452
+ "attachments": [],
1453
+ "bentoAICellStatus": "none",
1454
+ "isCommentPanelOpen": false,
1455
+ "language": "markdown",
1456
+ "metadata": {
1457
+ "bentoAICellStatus": "none",
1458
+ "customInput": null,
1459
+ "isCommentPanelOpen": false,
1460
+ "language": "markdown",
1461
+ "originalKey": "d79e36cd-a691-420d-8061-ad5222913770",
1462
+ "outputsInitialized": false,
1463
+ "showInput": false
1464
+ },
1465
+ "originalKey": "5f1ced4a-7f9b-4a3f-88bb-77fd601466eb",
1466
+ "outputsInitialized": false,
1467
+ "showInput": false
1468
+ },
1469
+ "source": [
1470
+ "### Clean-up\n",
1471
+ "\n",
1472
+ "After all inference is done, we can shutdown the predictor to free up the multi-GPU process group."
1473
+ ]
1474
+ },
1475
+ {
1476
+ "cell_type": "code",
1477
+ "execution_count": null,
1478
+ "metadata": {
1479
+ "bentoAICellStatus": "none",
1480
+ "bentoCellName": {
1481
+ "name": "Shutdown Predictor",
1482
+ "origin": "ai"
1483
+ },
1484
+ "collapsed": false,
1485
+ "customOutput": null,
1486
+ "executionStartTime": 1762496805866,
1487
+ "executionStopTime": 1762496807085,
1488
+ "isCommentPanelOpen": false,
1489
+ "jupyter": {
1490
+ "outputs_hidden": false
1491
+ },
1492
+ "language": "python",
1493
+ "metadata": {
1494
+ "bentoAICellStatus": "none",
1495
+ "bentoCellName": {
1496
+ "name": "Shutdown Predictor",
1497
+ "origin": "ai"
1498
+ },
1499
+ "collapsed": false,
1500
+ "customInput": null,
1501
+ "customOutput": null,
1502
+ "executionStartTime": 1761950863090,
1503
+ "executionStopTime": 1761950863987,
1504
+ "isCommentPanelOpen": false,
1505
+ "language": "python",
1506
+ "originalKey": "2de9666e-d888-4b2b-955a-82727363fc59",
1507
+ "outputsInitialized": true,
1508
+ "requestMsgId": "59e250c1-3d4c-436d-aa6e-fc0429fe4d8f",
1509
+ "serverExecutionDuration": 282.37027197611,
1510
+ "showInput": true
1511
+ },
1512
+ "originalKey": "bb5f6b72-d945-4193-8988-2490e9168882",
1513
+ "output": {
1514
+ "id": "1866958724222293",
1515
+ "loadingStatus": "before loading"
1516
+ },
1517
+ "outputsInitialized": true,
1518
+ "requestMsgId": "bb5f6b72-d945-4193-8988-2490e9168882",
1519
+ "serverExecutionDuration": 284.71523799999
1520
+ },
1521
+ "outputs": [],
1522
+ "source": [
1523
+ "# after all inference is done, we can shutdown the predictor\n",
1524
+ "# to free up the multi-GPU process group\n",
1525
+ "predictor.shutdown()"
1526
+ ]
1527
+ },
1528
+ {
1529
+ "cell_type": "code",
1530
+ "execution_count": null,
1531
+ "metadata": {
1532
+ "bentoAICellStatus": "none",
1533
+ "bentoCellName": {
1534
+ "name": "Cell 33",
1535
+ "origin": "initial"
1536
+ },
1537
+ "collapsed": false,
1538
+ "customInput": null,
1539
+ "customOutput": null,
1540
+ "executionStartTime": 1762496807093,
1541
+ "executionStopTime": 1762496807812,
1542
+ "isCommentPanelOpen": false,
1543
+ "jupyter": {
1544
+ "outputs_hidden": false
1545
+ },
1546
+ "language": "python",
1547
+ "originalKey": "e4ad9f5f-c0df-4e30-97a2-40d389ba92ac",
1548
+ "outputsInitialized": false,
1549
+ "requestMsgId": "e4ad9f5f-c0df-4e30-97a2-40d389ba92ac",
1550
+ "serverExecutionDuration": 3.5742059990298,
1551
+ "showInput": true
1552
+ },
1553
+ "outputs": [],
1554
+ "source": []
1555
+ },
1556
+ {
1557
+ "cell_type": "code",
1558
+ "execution_count": null,
1559
+ "metadata": {},
1560
+ "outputs": [],
1561
+ "source": []
1562
+ }
1563
+ ],
1564
+ "metadata": {
1565
+ "bento_stylesheets": {
1566
+ "bento/extensions/flow/main.css": true,
1567
+ "bento/extensions/kernel_selector/main.css": true,
1568
+ "bento/extensions/kernel_ui/main.css": true,
1569
+ "bento/extensions/new_kernel/main.css": true,
1570
+ "bento/extensions/system_usage/main.css": true,
1571
+ "bento/extensions/theme/main.css": true
1572
+ },
1573
+ "captumWidgetMessage": [],
1574
+ "fileHeader": "",
1575
+ "fileUid": "8685c221-c143-4b84-98ec-b1f023cedd6c",
1576
+ "isAdHoc": false,
1577
+ "kernelspec": {
1578
+ "display_name": "Python 3 (ipykernel)",
1579
+ "language": "python",
1580
+ "name": "python3"
1581
+ },
1582
+ "language_info": {
1583
+ "codemirror_mode": {
1584
+ "name": "ipython",
1585
+ "version": 3
1586
+ },
1587
+ "file_extension": ".py",
1588
+ "mimetype": "text/x-python",
1589
+ "name": "python",
1590
+ "nbconvert_exporter": "python",
1591
+ "pygments_lexer": "ipython3",
1592
+ "version": "3.12.11"
1593
+ },
1594
+ "last_base_url": "https://bento.edge.x2p.facebook.net/",
1595
+ "last_kernel_id": "b57809cb-57de-4b58-a47a-2cd14cd7dc51",
1596
+ "last_msg_id": "be2245fc-daa1cc5649ef79144c475c5d_1965",
1597
+ "last_server_session_id": "4fb65252-bdbd-4eea-b3c3-4a9f2995ad48",
1598
+ "notebookId": "825823386977069",
1599
+ "notebookNumber": "N8482762"
1600
+ },
1601
+ "nbformat": 4,
1602
+ "nbformat_minor": 2
1603
+ }
third_party/GraspGen/sam3/pyproject.toml ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=61", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "sam3"
7
+ dynamic = ["version"]
8
+ description = "SAM3 (Segment Anything Model 3) implementation"
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = {file = "LICENSE"}
12
+ authors = [
13
+ {name = "Meta AI Research"}
14
+ ]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Intended Audience :: Science/Research",
18
+ "License :: OSI Approved :: MIT License",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.8",
21
+ "Programming Language :: Python :: 3.9",
22
+ "Programming Language :: Python :: 3.10",
23
+ "Programming Language :: Python :: 3.11",
24
+ "Programming Language :: Python :: 3.12",
25
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
26
+ ]
27
+ dependencies = [
28
+ "timm>=1.0.17",
29
+ "numpy>=1.26,<2",
30
+ "tqdm",
31
+ "ftfy==6.1.1",
32
+ "regex",
33
+ "iopath>=0.1.10",
34
+ "typing_extensions",
35
+ "huggingface_hub",
36
+ ]
37
+
38
+ [project.optional-dependencies]
39
+ dev = [
40
+ "pytest",
41
+ "pytest-cov",
42
+ "black==24.2.0",
43
+ "ufmt==2.8.0",
44
+ "ruff-api==0.1.0",
45
+ "usort==1.0.2",
46
+ "gitpython==3.1.31",
47
+ "yt-dlp",
48
+ "pandas",
49
+ "opencv-python",
50
+ "pycocotools",
51
+ "numba",
52
+ "python-rapidjson",
53
+ ]
54
+ notebooks = [
55
+ "matplotlib",
56
+ "jupyter",
57
+ "notebook",
58
+ "ipywidgets",
59
+ "ipycanvas",
60
+ "ipympl",
61
+ "pycocotools",
62
+ "decord",
63
+ "opencv-python",
64
+ "einops",
65
+ "scikit-image",
66
+ "scikit-learn",
67
+ ]
68
+ train = [
69
+ "hydra-core",
70
+ "submitit",
71
+ "tensorboard",
72
+ "zstandard",
73
+ "scipy",
74
+ "torchmetrics",
75
+ "fvcore",
76
+ "fairscale",
77
+ "scikit-image",
78
+ "scikit-learn",
79
+ ]
80
+
81
+ [project.urls]
82
+ "Homepage" = "https://github.com/facebookresearch/sam3"
83
+ "Bug Tracker" = "https://github.com/facebookresearch/sam3/issues"
84
+
85
+ [tool.setuptools.packages.find]
86
+ include = ["sam3*"]
87
+ exclude = ["build*", "scripts*", "examples*"]
88
+
89
+ [tool.setuptools.package-data]
90
+ sam3 = ["assets/*.txt.gz"]
91
+
92
+ [tool.setuptools.dynamic]
93
+ version = {attr = "sam3.__version__"}
94
+
95
+ [tool.black]
96
+ line-length = 88
97
+ target-version = ['py38', 'py39', 'py310', 'py311', 'py312']
98
+ include = '\.pyi?$'
99
+
100
+ [tool.isort]
101
+ profile = "black"
102
+ multi_line_output = 3
103
+
104
+ [tool.usort]
105
+ first_party_detection = false
106
+
107
+ [tool.ufmt]
108
+ formatter = "ruff-api"
109
+
110
+ [tool.mypy]
111
+ python_version = "3.12"
112
+ warn_return_any = true
113
+ warn_unused_configs = true
114
+ disallow_untyped_defs = true
115
+ disallow_incomplete_defs = true
116
+
117
+ [[tool.mypy.overrides]]
118
+ module = [
119
+ "timm.*",
120
+ "numpy.*",
121
+ "PIL.*",
122
+ "tqdm.*",
123
+ "ftfy.*",
124
+ "regex.*",
125
+ "iopath.*",
126
+ ]
127
+ ignore_missing_imports = true
128
+
129
+ [tool.pytest.ini_options]
130
+ testpaths = ["tests"]
131
+ python_files = "test_*.py"
132
+ python_classes = "Test*"
133
+ python_functions = "test_*"
third_party/GraspGen/sam3/realsense-sam.py ADDED
@@ -0,0 +1,1771 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import multiprocessing as mp
4
+ import os
5
+ import queue
6
+ import signal
7
+ import subprocess
8
+ import sys
9
+ import time
10
+
11
+ import cv2
12
+ import numpy as np
13
+
14
+ # ROS2 TF & 图像(可选:未安装 ROS2 时仅跳过 TF/相机)
15
+ try:
16
+ import rclpy
17
+ from rclpy.node import Node
18
+ from geometry_msgs.msg import TransformStamped, PoseStamped
19
+ from tf2_ros import TransformBroadcaster
20
+ from sensor_msgs.msg import Image, CameraInfo, PointCloud2, PointField
21
+ from std_msgs.msg import Header
22
+ from visualization_msgs.msg import Marker, MarkerArray
23
+ from builtin_interfaces.msg import Duration as BuiltinDuration
24
+ from cv_bridge import CvBridge
25
+
26
+ _ROS_AVAILABLE = True
27
+ except ImportError:
28
+ _ROS_AVAILABLE = False
29
+ rclpy = None
30
+ Node = None
31
+ TransformStamped = None
32
+ TransformBroadcaster = None
33
+ Image = None
34
+ CameraInfo = None
35
+ CvBridge = None
36
+ import open3d as o3d
37
+ import pyrealsense2 as rs
38
+ import torch
39
+ from PIL import Image as PILImage
40
+
41
+ # ------------------- 机械臂相关配置(与 heihei.py 一致)-------------------
42
+ ROBOT_TYPE = "piper"
43
+ CAN_CHANNEL = "can0"
44
+ TCP_OFFSET = [0.0, 0.0, 0.10, 0.0, 0.0, 0.0] # TCP Z 轴 +14cm
45
+ SPEED_PERCENT = 30
46
+ MOTION_TIMEOUT = 15.0
47
+ POSE_SAVE_FILE = "/home/agilex/.nanobot/workspace/skills/grab_skill/sam3/recorded_j6_pose.json" # J6 法兰位姿保存路径(与 heihei 共用)
48
+ GRIPPER_MAX_WIDTH = 0.1 # 夹爪最大开口 (m)
49
+ GRIPPER_MIN_WIDTH = 0.0 # 夹爪最小开口 (m)
50
+ GRIPPER_FORCE = 2.0 # 夹爪夹持力 (N)
51
+
52
+ # 使用 RealSense ROS2 驱动时,深度图单位通常为毫米(uint16)
53
+ DEPTH_SCALE_ROS = 0.001 # 每个深度单位对应的米数(mm -> m)
54
+
55
+ # J6 到相机坐标系的变换 [x, y, z, qx, qy, qz, qw](与 j6_pose_tf_node.py 一致)
56
+ # 即 T_j6_to_camera,用于 T_result = T_j6 @ T_j6_to_camera(相机在基座系下)
57
+ J6_TO_CAMERA = [
58
+ -0.06657143797304754,
59
+ -0.007181201910632633,
60
+ 0.033259474804825814,
61
+ -0.1665998530,
62
+ 0.1479507149,
63
+ -0.6490963521,
64
+ 0.7273437981,
65
+ ]
66
+
67
+ # ROS TF 坐标系名称
68
+ TF_FRAME_BASE = "base_link"
69
+ TF_FRAME_J6_FLANGE = "piper_j6_flange"
70
+ TF_FRAME_CAMERA = "camera_link"
71
+ TF_FRAME_GRASP_TARGET = "grasp_target"
72
+
73
+ # RealSense 自身 TF:camera_link -> camera_color_optical_frame
74
+ # 来源:ros2 run tf2_ros tf2_echo camera_link camera_color_optical_frame
75
+ T_CAMLINK_TO_COLOR_OPTICAL = [
76
+ 0.0,
77
+ 0.015,
78
+ 0.0,
79
+ 0.5,
80
+ -0.5,
81
+ 0.501,
82
+ -0.5,
83
+ ]
84
+
85
+ # RealSense 光学坐标系 frame 名称(与 /camera/camera/aligned_depth_to_color/image_raw 一致)
86
+ CAMERA_OPTICAL_FRAME = "camera_color_optical_frame"
87
+
88
+ # RealSense ROS2 相机节点:程序内自动拉起/退出
89
+ CAMERA_WS_PATH = "/home/agilex/ros_workspace/camera_ws"
90
+ CAMERA_SETUP_SCRIPT = os.path.join(CAMERA_WS_PATH, "install", "setup.sh")
91
+ CAMERA_LAUNCH_CMD = "ros2 launch realsense2_camera rs_align_depth_launch.py"
92
+ CAMERA_LAUNCH_SHELL_CMD = (
93
+ f"source {CAMERA_SETUP_SCRIPT} && {CAMERA_LAUNCH_CMD}"
94
+ )
95
+
96
+
97
+ def make_pointcloud2(points_xyz, colors_rgb, frame_id, stamp):
98
+ """
99
+ 将 (N,3) XYZ 和 (N,3) RGB 数组转换为 PointCloud2(XYZRGB),发布在给定坐标系下。
100
+ """
101
+ if points_xyz.size == 0:
102
+ return None
103
+ pts = np.asarray(points_xyz, dtype=np.float32)
104
+ cols = np.clip(np.asarray(colors_rgb, dtype=np.float32) * 255.0, 0, 255).astype(
105
+ np.uint8
106
+ )
107
+ if pts.shape[0] != cols.shape[0]:
108
+ n = min(pts.shape[0], cols.shape[0])
109
+ pts = pts[:n]
110
+ cols = cols[:n]
111
+
112
+ # 按 PCL/ROS 约定打包为 x,y,z,rgb(rgb 为 float32,内部存放 uint32 的 BGR)
113
+ r = cols[:, 0].astype(np.uint32)
114
+ g = cols[:, 1].astype(np.uint32)
115
+ b = cols[:, 2].astype(np.uint32)
116
+ rgb_uint32 = (r << 16) | (g << 8) | b
117
+ rgb_float = rgb_uint32.view(np.float32)
118
+
119
+ # 组装结构化数组:x,y,z,rgb
120
+ cloud_arr = np.zeros(
121
+ pts.shape[0],
122
+ dtype=[
123
+ ("x", np.float32),
124
+ ("y", np.float32),
125
+ ("z", np.float32),
126
+ ("rgb", np.float32),
127
+ ],
128
+ )
129
+ cloud_arr["x"] = pts[:, 0]
130
+ cloud_arr["y"] = pts[:, 1]
131
+ cloud_arr["z"] = pts[:, 2]
132
+ cloud_arr["rgb"] = rgb_float
133
+
134
+ msg = PointCloud2()
135
+ msg.header = Header()
136
+ msg.header.stamp = stamp
137
+ msg.header.frame_id = frame_id
138
+ msg.height = 1
139
+ msg.width = cloud_arr.shape[0]
140
+ msg.fields = [
141
+ PointField(name="x", offset=0, datatype=PointField.FLOAT32, count=1),
142
+ PointField(name="y", offset=4, datatype=PointField.FLOAT32, count=1),
143
+ PointField(name="z", offset=8, datatype=PointField.FLOAT32, count=1),
144
+ PointField(name="rgb", offset=12, datatype=PointField.FLOAT32, count=1),
145
+ ]
146
+ msg.is_bigendian = False
147
+ msg.point_step = 16 # 3*4 (xyz) + 4 (rgb)
148
+ msg.row_step = msg.point_step * cloud_arr.shape[0]
149
+ msg.is_dense = True
150
+ msg.data = cloud_arr.tobytes()
151
+ return msg
152
+
153
+
154
+ def start_camera_launch():
155
+ """
156
+ 在子进程中拉起 RealSense ROS2 节���:source camera_ws/setup.sh && ros2 launch ...
157
+ 返回 subprocess.Popen 实例,退出时需调用 stop_camera_launch(proc)。
158
+ """
159
+ if not os.path.isfile(CAMERA_SETUP_SCRIPT):
160
+ print(f"[Camera] 未找到 setup 脚本: {CAMERA_SETUP_SCRIPT},请检查路径")
161
+ return None
162
+ print("[Camera] 正在拉起 RealSense ROS2 节点...")
163
+ try:
164
+ proc = subprocess.Popen(
165
+ CAMERA_LAUNCH_SHELL_CMD,
166
+ shell=True,
167
+ executable="/bin/bash",
168
+ cwd=CAMERA_WS_PATH,
169
+ start_new_session=True,
170
+ stdout=subprocess.DEVNULL,
171
+ stderr=subprocess.PIPE,
172
+ )
173
+ print("[Camera] RealSense launch 已启动,等待数秒使节点就绪...")
174
+ time.sleep(5)
175
+ if proc.poll() is not None:
176
+ err = proc.stderr.read().decode("utf-8", errors="replace") if proc.stderr else ""
177
+ print(f"[Camera] launch 进程已异常退出: {err}")
178
+ return None
179
+ return proc
180
+ except Exception as e:
181
+ print(f"[Camera] 启动失败: {e}")
182
+ return None
183
+
184
+
185
+ def stop_camera_launch(proc, timeout=10):
186
+ """终止由 start_camera_launch 拉起的进程(及其进程组)。"""
187
+ if proc is None:
188
+ return
189
+ try:
190
+ if proc.poll() is None:
191
+ pgid = os.getpgid(proc.pid)
192
+ os.killpg(pgid, signal.SIGTERM)
193
+ proc.wait(timeout=timeout)
194
+ except ProcessLookupError:
195
+ pass
196
+ except Exception as e:
197
+ print(f"[Camera] 关闭 launch 时出错: {e}")
198
+ try:
199
+ proc.kill()
200
+ proc.wait(timeout=3)
201
+ except Exception:
202
+ pass
203
+
204
+
205
+ # 无保存文件时的 fallback:相机在基座系下的齐次矩阵(仅当未按 D 记录过时使用)
206
+ T_BASE_CAM_FALLBACK = np.array(
207
+ [
208
+ [-0.043365, -0.977782, 0.205091, 0.196176],
209
+ [-0.989188, 0.013236, -0.146053, 0.238188],
210
+ [0.140093, -0.209207, -0.967784, 0.219417],
211
+ [0.0, 0.0, 0.0, 1.0],
212
+ ],
213
+ dtype=np.float32,
214
+ )
215
+
216
+
217
+ def euler_to_rotation_matrix(roll, pitch, yaw):
218
+ """欧拉角 Z-Y-X (rad) -> 3x3 旋转矩阵"""
219
+ cr, sr = np.cos(roll), np.sin(roll)
220
+ cp, sp = np.cos(pitch), np.sin(pitch)
221
+ cy, sy = np.cos(yaw), np.sin(yaw)
222
+ R = np.array(
223
+ [
224
+ [cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr],
225
+ [sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr],
226
+ [-sp, cp * sr, cp * cr],
227
+ ]
228
+ )
229
+ return R
230
+
231
+
232
+ def rotation_matrix_to_euler(R):
233
+ """3x3 旋转矩阵 -> Z-Y-X 欧拉角 (roll, pitch, yaw) rad"""
234
+ sy = -R[2, 0]
235
+ pitch = np.arcsin(np.clip(sy, -1.0, 1.0))
236
+ cp = np.cos(pitch)
237
+ if np.abs(cp) > 1e-6:
238
+ yaw = np.arctan2(R[1, 0], R[0, 0])
239
+ roll = np.arctan2(R[2, 1], R[2, 2])
240
+ else:
241
+ yaw = 0.0
242
+ roll = np.arctan2(-R[0, 1], R[1, 1])
243
+ return roll, pitch, yaw
244
+
245
+
246
+ def pose_to_homogeneous_matrix(pose):
247
+ """[x,y,z,roll,pitch,yaw] -> 4x4 齐次矩阵"""
248
+ x, y, z = pose[0], pose[1], pose[2]
249
+ roll, pitch, yaw = pose[3], pose[4], pose[5]
250
+ R = euler_to_rotation_matrix(roll, pitch, yaw)
251
+ T = np.eye(4, dtype=np.float32)
252
+ T[:3, :3] = R
253
+ T[:3, 3] = [x, y, z]
254
+ return T
255
+
256
+
257
+ def homogeneous_to_pose(T):
258
+ """4x4 齐次矩阵 -> [x,y,z,roll,pitch,yaw] (m, rad)"""
259
+ x, y, z = T[0, 3], T[1, 3], T[2, 3]
260
+ R = T[:3, :3]
261
+ roll, pitch, yaw = rotation_matrix_to_euler(R)
262
+ return [float(x), float(y), float(z), float(roll), float(pitch), float(yaw)]
263
+
264
+
265
+ def quat_pose_to_homogeneous_matrix(pose7):
266
+ """[x, y, z, qx, qy, qz, qw] -> 4x4 齐次矩阵"""
267
+ x, y, z = pose7[0], pose7[1], pose7[2]
268
+ qx, qy, qz, qw = pose7[3], pose7[4], pose7[5], pose7[6]
269
+ R = quaternion_to_rotation_matrix(qx, qy, qz, qw)
270
+ T = np.eye(4, dtype=np.float32)
271
+ T[:3, :3] = R
272
+ T[:3, 3] = [x, y, z]
273
+ return T
274
+
275
+
276
+ def quaternion_to_rotation_matrix(qx, qy, qz, qw):
277
+ """四元数 (x, y, z, w) -> 3x3 旋转矩阵"""
278
+ return np.array(
279
+ [
280
+ [
281
+ 1.0 - 2.0 * (qy * qy + qz * qz),
282
+ 2.0 * (qx * qy - qz * qw),
283
+ 2.0 * (qx * qz + qy * qw),
284
+ ],
285
+ [
286
+ 2.0 * (qx * qy + qz * qw),
287
+ 1.0 - 2.0 * (qx * qx + qz * qz),
288
+ 2.0 * (qy * qz - qx * qw),
289
+ ],
290
+ [
291
+ 2.0 * (qx * qz - qy * qw),
292
+ 2.0 * (qy * qz + qx * qw),
293
+ 1.0 - 2.0 * (qx * qx + qy * qy),
294
+ ],
295
+ ],
296
+ dtype=np.float32,
297
+ )
298
+
299
+
300
+ def rotation_matrix_to_quaternion(R):
301
+ """3x3 旋转矩阵 -> 四元数 (qx, qy, qz, qw)"""
302
+ trace = R[0, 0] + R[1, 1] + R[2, 2]
303
+ if trace > 0:
304
+ s = 0.5 / np.sqrt(trace + 1.0)
305
+ qw = 0.25 / s
306
+ qx = (R[2, 1] - R[1, 2]) * s
307
+ qy = (R[0, 2] - R[2, 0]) * s
308
+ qz = (R[1, 0] - R[0, 1]) * s
309
+ elif R[0, 0] > R[1, 1] and R[0, 0] > R[2, 2]:
310
+ s = 2.0 * np.sqrt(1.0 + R[0, 0] - R[1, 1] - R[2, 2])
311
+ qw = (R[2, 1] - R[1, 2]) / s
312
+ qx = 0.25 * s
313
+ qy = (R[0, 1] + R[1, 0]) / s
314
+ qz = (R[0, 2] + R[2, 0]) / s
315
+ elif R[1, 1] > R[2, 2]:
316
+ s = 2.0 * np.sqrt(1.0 + R[1, 1] - R[0, 0] - R[2, 2])
317
+ qw = (R[0, 2] - R[2, 0]) / s
318
+ qx = (R[0, 1] + R[1, 0]) / s
319
+ qy = 0.25 * s
320
+ qz = (R[1, 2] + R[2, 1]) / s
321
+ else:
322
+ s = 2.0 * np.sqrt(1.0 + R[2, 2] - R[0, 0] - R[1, 1])
323
+ qw = (R[1, 0] - R[0, 1]) / s
324
+ qx = (R[0, 2] + R[2, 0]) / s
325
+ qy = (R[1, 2] + R[2, 1]) / s
326
+ qz = 0.25 * s
327
+ return (float(qx), float(qy), float(qz), float(qw))
328
+
329
+
330
+ def load_T_result_from_saved_j6():
331
+ """
332
+ 从 POSE_SAVE_FILE 加载 J6 法兰位姿,与 J6_TO_CAMERA 相乘得到 T_result(相机在基座系下)。
333
+ 若文件不存在或解析失败则返回 None,调用方用 T_BASE_CAM_FALLBACK。
334
+ """
335
+ if not os.path.exists(POSE_SAVE_FILE):
336
+ return None
337
+ try:
338
+ with open(POSE_SAVE_FILE, "r", encoding="utf-8") as f:
339
+ recorded_j6_pose = json.load(f)
340
+ T_j6 = pose_to_homogeneous_matrix(recorded_j6_pose)
341
+ T_j6_to_camera = quat_pose_to_homogeneous_matrix(J6_TO_CAMERA)
342
+ T_result = np.matmul(T_j6, T_j6_to_camera).astype(np.float32)
343
+ return T_result
344
+ except Exception as e:
345
+ print(f"[T_result] 加载 J6 位姿失败: {e},将使用 fallback 矩阵")
346
+ return None
347
+
348
+
349
+ def init_robot_and_gripper():
350
+ """
351
+ 初始化机械臂与夹爪(与 heihei 一致)。失败时返回 (None, None),主程序可仅做视觉。
352
+ """
353
+ try:
354
+ from pyAgxArm import create_agx_arm_config, AgxArmFactory
355
+
356
+ cfg = create_agx_arm_config(
357
+ robot=ROBOT_TYPE,
358
+ comm="can",
359
+ channel=CAN_CHANNEL,
360
+ bitrate=1000000,
361
+ auto_connect=True,
362
+ )
363
+ robot = AgxArmFactory.create_arm(cfg)
364
+ end_effector = robot.init_effector(robot.OPTIONS.EFFECTOR.AGX_GRIPPER)
365
+ robot.connect(start_read_thread=True)
366
+ time.sleep(0.5)
367
+ if not robot.is_ok():
368
+ raise ConnectionError("机械臂通信异常")
369
+ if not end_effector.is_ok():
370
+ raise ConnectionError("夹爪通信异常")
371
+ robot.set_tcp_offset(TCP_OFFSET)
372
+ # 使能
373
+ for _ in range(1000):
374
+ if robot.enable(joint_index=255):
375
+ break
376
+ time.sleep(0.01)
377
+ else:
378
+ raise TimeoutError("关节使能超时")
379
+ robot.set_speed_percent(SPEED_PERCENT)
380
+ robot.set_motion_mode(robot.OPTIONS.MOTION_MODE.P)
381
+ print("[Robot] 机械臂与夹爪初始化完成")
382
+ return robot, end_effector
383
+ except Exception as e:
384
+ print(f"[Robot] 初始化失败(将仅做视觉,不控制机械臂): {e}")
385
+ return None, None
386
+
387
+
388
+ def compute_grasp_from_pca_aabb(pts_base, gripper_max_opening=0.1):
389
+ """
390
+ 参考 demo.hpp / AABBGraspPlanner:3D PCA → 主轴系 AABB → 最短边作为夹持方向(Z) → 调整坐标系 →
391
+ Z 轴朝“远离原点”的方向(与 C++ 实现一致)。
392
+ 输入点云应为滤波后、基座系下的点云;返回 (center, R_grasp) 或 None。
393
+ """
394
+ pts = np.asarray(pts_base, dtype=np.float64)
395
+ if pts.shape[0] < 4:
396
+ return None
397
+ # 1) 中心点(对应 pcl::compute3DCentroid)
398
+ pca_centroid = np.mean(pts, axis=0)
399
+ # 2) 协方差矩阵(PCL 归一化:除以 n-1)
400
+ centered = pts - pca_centroid
401
+ covariance = (centered.T @ centered) / max(centered.shape[0] - 1, 1)
402
+ # 3) 特征值、特征向量(对应 Eigen::SelfAdjointEigenSolver)
403
+ eigen_values, eigen_vectors = np.linalg.eigh(covariance)
404
+ # 4) 确保特征向量构成右手坐标系(与 demo 完全一致)
405
+ ev = eigen_vectors
406
+ ev = ev.copy()
407
+ ev[:, 2] = np.cross(ev[:, 0], ev[:, 1])
408
+ ev[:, 1] = np.cross(ev[:, 2], ev[:, 0])
409
+ ev[:, 0] = np.cross(ev[:, 1], ev[:, 2])
410
+ for i in range(3):
411
+ n = np.linalg.norm(ev[:, i])
412
+ if n > 1e-10:
413
+ ev[:, i] = ev[:, i] / n
414
+ # 5) 按特征值降序排列特征向量(demo: indices 使 eigenValuesPCA(indices[j]) > eigenValuesPCA(indices[i]) 则 swap)
415
+ indices = np.argsort(eigen_values)[::-1]
416
+ sorted_eigen_vectors = ev[:, indices].copy()
417
+ # 6) 确保右手系(行列式为正)
418
+ if np.linalg.det(sorted_eigen_vectors) < 0:
419
+ sorted_eigen_vectors[:, 2] = -sorted_eigen_vectors[:, 2]
420
+ # 7) 变换矩阵:tm 的 3x3 = R^T,平移 = -R^T @ centroid;local = R^T @ (p - centroid)
421
+ R = sorted_eigen_vectors
422
+ local_pts = (R.T @ (pts - pca_centroid).T).T
423
+ # 8) 变换后点云的 AABB(对应 getMinMax3D)
424
+ min_pt = np.min(local_pts, axis=0)
425
+ max_pt = np.max(local_pts, axis=0)
426
+ aabb_length_x = float(max_pt[0] - min_pt[0])
427
+ aabb_width_y = float(max_pt[1] - min_pt[1])
428
+ aabb_height_z = float(max_pt[2] - min_pt[2])
429
+ # 9) 最短边作为夹持方向
430
+ min_dimension = min(aabb_length_x, aabb_width_y, aabb_height_z)
431
+ if min_dimension > gripper_max_opening:
432
+ return None
433
+ if min_dimension == aabb_length_x:
434
+ grasp_axis = 0
435
+ elif min_dimension == aabb_width_y:
436
+ grasp_axis = 1
437
+ else:
438
+ grasp_axis = 2
439
+ # 10) AABB 中心转回世界系(tm_inv 的 3x3 = R,平移 = centroid)
440
+ aabb_center_local = (min_pt + max_pt) * 0.5
441
+ aabb_center_global = R @ aabb_center_local + pca_centroid
442
+ center = np.array(aabb_center_global, dtype=np.float32)
443
+ # 11) 抓取方向 = tm_inv 的 3x3 = R(列为主方向)
444
+ rotation_matrix = R.copy()
445
+ # 12) 根据夹持方向调整坐标系:机械爪夹持方向为 Z(与 demo 一致)
446
+ if grasp_axis == 0:
447
+ # 新 Z = 原 X(夹持),新 X = 原 Y,新 Y = 原 Z
448
+ adjusted = np.column_stack([
449
+ rotation_matrix[:, 1],
450
+ rotation_matrix[:, 2],
451
+ rotation_matrix[:, 0],
452
+ ])
453
+ rotation_matrix = adjusted
454
+ elif grasp_axis == 1:
455
+ # 新 Z = 原 Y(夹持),新 X = 原 Z,新 Y = 原 X
456
+ adjusted = np.column_stack([
457
+ rotation_matrix[:, 2],
458
+ rotation_matrix[:, 0],
459
+ rotation_matrix[:, 1],
460
+ ])
461
+ rotation_matrix = adjusted
462
+ # grasp_axis == 2 不调整
463
+ # 13) 确保 Z 轴“远离原点”方向(与 demo.hpp 一致)
464
+ z_axis = rotation_matrix[:, 2]
465
+ position_vector = center.astype(np.float64)
466
+ norm_pos = np.linalg.norm(position_vector)
467
+ if norm_pos > 1e-8:
468
+ dot_product = float(z_axis.dot(position_vector / norm_pos))
469
+ if dot_product < 0.0:
470
+ rotation_matrix[:, 2] = -rotation_matrix[:, 2]
471
+ rotation_matrix[:, 0] = -rotation_matrix[:, 0]
472
+ # 14) 正交化(demo 中 determinant 偏离 1 时用 QR 修正)
473
+ det = np.linalg.det(rotation_matrix)
474
+ if abs(det - 1.0) > 0.1:
475
+ Q, _ = np.linalg.qr(rotation_matrix)
476
+ rotation_matrix = Q.copy()
477
+ if np.linalg.det(rotation_matrix) < 0:
478
+ rotation_matrix[:, 2] = -rotation_matrix[:, 2]
479
+ R_grasp = np.array(rotation_matrix, dtype=np.float32)
480
+ return center, R_grasp
481
+
482
+
483
+ def align_grasp_x_toward_base(R_grasp, T_cam_to_base):
484
+ """
485
+ 调整抓取姿态旋转矩阵,使 x 轴朝向 base_link 一侧。
486
+ T_cam_to_base: 4x4 齐次矩阵,将点从 camera_color_optical_frame 变换到 base_link。
487
+ 若当前 x 轴背向 base,则翻转 x、y 以保持右手系。
488
+ """
489
+ T_base_to_cam = np.linalg.inv(np.asarray(T_cam_to_base, dtype=np.float64))
490
+ base_origin_in_cam = T_base_to_cam[:3, 3]
491
+ n = np.linalg.norm(base_origin_in_cam)
492
+ if n < 1e-6:
493
+ return np.asarray(R_grasp, dtype=np.float32)
494
+ dir_to_base = base_origin_in_cam / n
495
+ R = np.asarray(R_grasp, dtype=np.float64).copy()
496
+ if np.dot(R[:, 0], dir_to_base) < 0.0:
497
+ R[:, 0] = -R[:, 0]
498
+ R[:, 1] = -R[:, 1] # 保持右手系
499
+ return R.astype(np.float32)
500
+
501
+
502
+ def save_pose_to_file(j6_pose):
503
+ """将 J6 法兰位姿保存到 POSE_SAVE_FILE"""
504
+ try:
505
+ with open(POSE_SAVE_FILE, "w", encoding="utf-8") as f:
506
+ json.dump(j6_pose, f, indent=4)
507
+ print(f"[Robot] J6 法兰位姿已保存: {POSE_SAVE_FILE}")
508
+ except Exception as e:
509
+ print(f"[Robot] 保存位姿失败: {e}")
510
+
511
+
512
+ def safe_shutdown_robot(robot, end_effector):
513
+ """安全失能机械臂与夹爪"""
514
+ if robot is not None:
515
+ try:
516
+ robot.disable(joint_index=255)
517
+ print("[Robot] 机械臂已失能")
518
+ except Exception:
519
+ pass
520
+ if end_effector is not None:
521
+ try:
522
+ end_effector.disable_gripper()
523
+ print("[Robot] 夹爪已失能")
524
+ except Exception:
525
+ pass
526
+
527
+ def sam_results_to_masklet_outputs(results, img_h, img_w):
528
+ """
529
+ 将 SAM3 的结果格式转换为 visualization_utils.render_masklet_frame 所需格式。
530
+ results 需要包含:
531
+ - "scores": list[Tensor]
532
+ - "boxes": list[Tensor],XYXY 像素坐标
533
+ - "masks": list[Tensor],形状 [1, H, W]
534
+ """
535
+ outputs = {
536
+ "out_boxes_xywh": [],
537
+ "out_probs": [],
538
+ "out_obj_ids": [],
539
+ "out_binary_masks": [],
540
+ }
541
+
542
+ num_objs = len(results.get("scores", []))
543
+ for i in range(num_objs):
544
+ score = results["scores"][i].item()
545
+ box_xyxy = results["boxes"][i].cpu().numpy()
546
+ x1, y1, x2, y2 = box_xyxy
547
+
548
+ # 归一化 XYWH
549
+ x = x1 / img_w
550
+ y = y1 / img_h
551
+ w = (x2 - x1) / img_w
552
+ h = (y2 - y1) / img_h
553
+
554
+ mask_tensor = results["masks"][i].squeeze(0).cpu()
555
+ mask_np = mask_tensor.numpy()
556
+ # 如果是概率图,简单阈值为 0.5
557
+ if mask_np.dtype != np.bool_:
558
+ mask_np = mask_np > 0.5
559
+
560
+ outputs["out_boxes_xywh"].append([x, y, w, h])
561
+ outputs["out_probs"].append(score)
562
+ outputs["out_obj_ids"].append(i)
563
+ outputs["out_binary_masks"].append(mask_np.astype(np.uint8))
564
+
565
+ return outputs
566
+
567
+
568
+ def sam_worker(
569
+ input_q: mp.Queue,
570
+ output_q: mp.Queue,
571
+ prompt_q: mp.Queue,
572
+ initial_prompt: str = "person",
573
+ ):
574
+ """
575
+ 子进程:专门跑 SAM3 推理(在 GPU 上),避免与 RealSense 的 C++/CUDA 冲突。
576
+ """
577
+ import torch
578
+ from sam3 import build_sam3_image_model
579
+ from sam3.model.sam3_image_processor import Sam3Processor
580
+ from sam3.visualization_utils import render_masklet_frame
581
+
582
+ device = "cuda" if torch.cuda.is_available() else "cpu"
583
+ print(f"[SAM Worker] 使用设备: {device}")
584
+
585
+ checkpoint_path = (
586
+ "/home/agilex/.cache/modelscope/hub/models/facebook/sam3/sam3.pt"
587
+ )
588
+ print(f"[SAM Worker] 加载 SAM3 模型: {checkpoint_path}")
589
+ model = build_sam3_image_model(
590
+ device=device,
591
+ checkpoint_path=checkpoint_path,
592
+ load_from_HF=False,
593
+ )
594
+ processor = Sam3Processor(model, confidence_threshold=0.5)
595
+ print("[SAM Worker] 模型加载完成,开始等待图像帧...")
596
+
597
+ current_prompt = initial_prompt
598
+ print(f"[SAM Worker] 初始文本提示: '{current_prompt}'")
599
+
600
+ with torch.no_grad():
601
+ while True:
602
+ frame_rgb = input_q.get()
603
+ if frame_rgb is None:
604
+ print("[SAM Worker] 收到退出信号,结束进程。")
605
+ break
606
+
607
+ if not isinstance(frame_rgb, np.ndarray):
608
+ continue
609
+
610
+ # 无阻塞检查是否有新的 prompt
611
+ try:
612
+ while True:
613
+ new_prompt = prompt_q.get_nowait()
614
+ if isinstance(new_prompt, str) and new_prompt.strip():
615
+ current_prompt = new_prompt.strip()
616
+ print(f"[SAM Worker] 更新文本提示: '{current_prompt}'")
617
+ except queue.Empty:
618
+ pass
619
+
620
+ h, w = frame_rgb.shape[:2]
621
+ pil_image = PILImage.fromarray(frame_rgb)
622
+
623
+ try:
624
+ state = processor.set_image(pil_image)
625
+ processor.reset_all_prompts(state)
626
+ state = processor.set_text_prompt(state=state, prompt=current_prompt)
627
+
628
+ sam_outputs = sam_results_to_masklet_outputs(
629
+ state, img_h=h, img_w=w
630
+ )
631
+ overlay_rgb = render_masklet_frame(
632
+ frame_rgb, sam_outputs, frame_idx=None, alpha=0.5
633
+ )
634
+
635
+ # 为每个目标分别保留掩码,便于单独生成点云和 AABB/OBB
636
+ per_object_masks = []
637
+ for m in sam_outputs["out_binary_masks"]:
638
+ if m.shape[0] != h or m.shape[1] != w:
639
+ m = cv2.resize(
640
+ m.astype(np.uint8),
641
+ (w, h),
642
+ interpolation=cv2.INTER_NEAREST,
643
+ )
644
+ per_object_masks.append(m.astype(np.uint8))
645
+
646
+ # 队列满就丢弃旧结果,只保留最新的
647
+ try:
648
+ while True:
649
+ output_q.get_nowait()
650
+ except queue.Empty:
651
+ pass
652
+ output_q.put_nowait(
653
+ {
654
+ "overlay": overlay_rgb,
655
+ "masks": per_object_masks,
656
+ "ids": sam_outputs["out_obj_ids"],
657
+ }
658
+ )
659
+ except Exception as e:
660
+ print(f"[SAM Worker] 推理异常: {e}")
661
+
662
+
663
+ class RealSenseAlignAdvanced:
664
+ def __init__(
665
+ self,
666
+ text_prompt: str,
667
+ sam_input_q: mp.Queue,
668
+ sam_output_q: mp.Queue,
669
+ prompt_q: mp.Queue,
670
+ robot=None,
671
+ end_effector=None,
672
+ node=None,
673
+ tf_broadcaster=None,
674
+ auto_mode=False,
675
+ ):
676
+ # 机械臂(可选):None 时仅视觉,不下发抓取
677
+ self.robot = robot
678
+ self.end_effector = end_effector
679
+ # ROS2 TF 发布(可选)
680
+ self._node = node
681
+ self._tf_broadcaster = tf_broadcaster
682
+ self._T_j6_to_camera = quat_pose_to_homogeneous_matrix(J6_TO_CAMERA)
683
+ # RealSense TF:camera_link -> camera_color_optical_frame 及其逆
684
+ self._T_camlink_to_optical = quat_pose_to_homogeneous_matrix(
685
+ T_CAMLINK_TO_COLOR_OPTICAL
686
+ )
687
+ self._T_optical_to_camlink = np.linalg.inv(self._T_camlink_to_optical)
688
+ # 相机在基座系下:优先用 J6×J6_TO_CAMERA,无文件则用 fallback
689
+ self.T_result = load_T_result_from_saved_j6()
690
+ if self.T_result is None:
691
+ self.T_result = T_BASE_CAM_FALLBACK.copy()
692
+ print("[T_result] 使用 fallback 矩阵,建议在 heihei 中按 D 记录位姿并保存")
693
+ else:
694
+ print("[T_result] 已从 J6 位姿文件加载并计算 T_result")
695
+ # 按 p 计算出的最佳抓取姿态(基座系 4x4),按 g 时下发
696
+ self.best_grasp_T = None
697
+ # 主臂/普通模式及记录的 J6 位姿(A/D/S/X 与 heihei 一致)
698
+ self.is_master_mode = False
699
+ self.recorded_j6_pose = None
700
+ if os.path.exists(POSE_SAVE_FILE):
701
+ try:
702
+ with open(POSE_SAVE_FILE, "r", encoding="utf-8") as f:
703
+ self.recorded_j6_pose = json.load(f)
704
+ except Exception:
705
+ pass
706
+
707
+ # 深度裁剪参数(用于去背景)
708
+ self.depth_clipping_distance = 1.0 # 默认裁剪距离(米)
709
+ self.running = False
710
+ # 自动化模式(--auto):状态机 self._auto_state,时间戳 self._auto_state_ts
711
+ self.auto_mode = bool(auto_mode)
712
+ self._auto_state = 0 # 0=等SAM就绪 1=X 2=q 3=p 4=delay2s 5=g 6=e 7=x 8=s 9=退出
713
+ self._auto_state_ts = 0.0
714
+ self._auto_p_retries = 0
715
+
716
+ # 点云与抓取可视化发布(基于 /camera/camera/aligned_depth_to_color/image_raw,坐标系为 camera_color_optical_frame)
717
+ if _ROS_AVAILABLE and self._node is not None:
718
+ self._pcd_pub = self._node.create_publisher(
719
+ PointCloud2, "sam3_grasp_cloud", 1
720
+ )
721
+ self._aabb_marker_pub = self._node.create_publisher(
722
+ Marker, "sam3_aabb_marker", 1
723
+ )
724
+ self._grasp_axes_pub = self._node.create_publisher(
725
+ Marker, "sam3_grasp_axes", 1
726
+ )
727
+ self._grasp_pose_pub = self._node.create_publisher(
728
+ PoseStamped, "sam3_grasp_pose", 1
729
+ )
730
+ self._marker_array_pub = self._node.create_publisher(
731
+ MarkerArray, "sam3_aabb_marker_array", 1
732
+ )
733
+ else:
734
+ self._pcd_pub = None
735
+ self._marker_array_pub = None
736
+
737
+ # OpenCV窗口配置
738
+ self.window_name = "RealSense + SAM3 Realtime"
739
+ cv2.namedWindow(self.window_name, cv2.WINDOW_NORMAL)
740
+ cv2.resizeWindow(self.window_name, 1280, 720)
741
+ # 创建滑块控制裁剪距离(0~6米,步长0.01)
742
+ cv2.createTrackbar(
743
+ "Depth Clip (m)", self.window_name, 100, 600, self.on_trackbar_change
744
+ )
745
+
746
+ # SAM3 推理相关(通过子进程通信)
747
+ self.text_prompt = text_prompt
748
+ self.sam_input_q = sam_input_q
749
+ self.sam_output_q = sam_output_q
750
+ self.prompt_q = prompt_q
751
+ self.last_overlay_bgr = None
752
+ # SAM3 掩码与 ID(按目标分别保存,便于单独点云/AABB 处理)
753
+ self.last_masks = None # list[np.ndarray]
754
+ self.last_obj_ids = None # list[int]
755
+
756
+ # 相机内参(首次帧时初始化,用于点云反投影)
757
+ self.fx = None
758
+ self.fy = None
759
+ self.cx = None
760
+ self.cy = None
761
+ # 帧计数器(仅用于调试打印,不影响功能)
762
+ self.frame_counter = 0
763
+
764
+ # ROS 相机订阅(使用 RealSense 对齐后的深度图与对应的相机内参)
765
+ self.bridge = CvBridge() if _ROS_AVAILABLE and self._node is not None else None
766
+ self._latest_color = None # BGR8, np.ndarray[h,w,3]
767
+ self._latest_depth = None # uint16, 对齐到彩色,np.ndarray[h,w]
768
+ self._have_cam_info = False
769
+
770
+ if _ROS_AVAILABLE and self._node is not None and self.bridge is not None:
771
+ # 颜色图
772
+ self._color_sub = self._node.create_subscription(
773
+ Image,
774
+ "/camera/camera/color/image_raw",
775
+ self._color_cb,
776
+ 10,
777
+ )
778
+ # 已对齐到彩色的深度图
779
+ self._depth_sub = self._node.create_subscription(
780
+ Image,
781
+ "/camera/camera/aligned_depth_to_color/image_raw",
782
+ self._depth_cb,
783
+ 10,
784
+ )
785
+ # 对齐深度图的相机内参(/camera/camera/aligned_depth_to_color/camera_info)
786
+ self._caminfo_sub = self._node.create_subscription(
787
+ CameraInfo,
788
+ "/camera/camera/aligned_depth_to_color/camera_info",
789
+ self._caminfo_cb,
790
+ 10,
791
+ )
792
+
793
+ def _color_cb(self, msg: Image):
794
+ if self.bridge is None:
795
+ return
796
+ try:
797
+ # RealSense ROS 默认编码为 rgb8/bgr8,这里统一转成 BGR,便于 OpenCV 使用
798
+ cv_image = self.bridge.imgmsg_to_cv2(msg, desired_encoding="bgr8")
799
+ self._latest_color = cv_image
800
+ except Exception as e:
801
+ print(f"[ROS Camera] 颜色图转换失败: {e}")
802
+
803
+ def _depth_cb(self, msg: Image):
804
+ if self.bridge is None:
805
+ return
806
+ try:
807
+ # 深度图通常为 16UC1(单位 mm),保留为 uint16,在主循环中乘以 DEPTH_SCALE_ROS 得到米
808
+ depth = self.bridge.imgmsg_to_cv2(msg, desired_encoding="passthrough")
809
+ self._latest_depth = depth
810
+ except Exception as e:
811
+ print(f"[ROS Camera] 深度图转换失败: {e}")
812
+
813
+ def _caminfo_cb(self, msg: CameraInfo):
814
+ # 只在首次收到时初始化内参
815
+ if self._have_cam_info:
816
+ return
817
+ # msg.k 是长度为 9 的数组,不能直接在 if 中作为布尔判定
818
+ if len(msg.k) == 9:
819
+ self.fx = float(msg.k[0])
820
+ self.fy = float(msg.k[4])
821
+ self.cx = float(msg.k[2])
822
+ self.cy = float(msg.k[5])
823
+ self._have_cam_info = True
824
+ print(
825
+ f"[Intrinsics] fx={self.fx:.2f}, fy={self.fy:.2f}, cx={self.cx:.2f}, cy={self.cy:.2f} (from ROS CameraInfo)"
826
+ )
827
+
828
+ def _publish_tf(self):
829
+ """发布参与坐标变换的 ROS TF:base_link -> piper_j6_flange -> camera,以及 base_link -> grasp_target(若有)."""
830
+ if not _ROS_AVAILABLE or self._node is None or self._tf_broadcaster is None:
831
+ return
832
+ stamp = self._node.get_clock().now().to_msg()
833
+ # 当前 J6 位姿:有机械臂则实时读取,否则用记录的位姿
834
+ j6_pose = None
835
+ if self.robot is not None and not self.is_master_mode:
836
+ fp = self.robot.get_flange_pose()
837
+ if fp is not None and len(fp.msg) >= 6:
838
+ j6_pose = list(fp.msg)
839
+ if j6_pose is None and self.recorded_j6_pose is not None:
840
+ j6_pose = self.recorded_j6_pose
841
+ if j6_pose is not None:
842
+ t_j6 = TransformStamped()
843
+ t_j6.header.stamp = stamp
844
+ t_j6.header.frame_id = TF_FRAME_BASE
845
+ t_j6.child_frame_id = TF_FRAME_J6_FLANGE
846
+ t_j6.transform.translation.x = float(j6_pose[0])
847
+ t_j6.transform.translation.y = float(j6_pose[1])
848
+ t_j6.transform.translation.z = float(j6_pose[2])
849
+ R = euler_to_rotation_matrix(j6_pose[3], j6_pose[4], j6_pose[5])
850
+ qx, qy, qz, qw = rotation_matrix_to_quaternion(R)
851
+ t_j6.transform.rotation.x = qx
852
+ t_j6.transform.rotation.y = qy
853
+ t_j6.transform.rotation.z = qz
854
+ t_j6.transform.rotation.w = qw
855
+ self._tf_broadcaster.sendTransform(t_j6)
856
+ # 固定:piper_j6_flange -> camera_link
857
+ # 已标定外参为:piper_j6_flange -> camera_color_optical_frame(J6_TO_CAMERA)
858
+ # RealSense 自身发布:camera_link -> camera_color_optical_frame(T_CAMLINK_TO_COLOR_OPTICAL)
859
+ # 这里发布的是:piper_j6_flange -> camera_link = (piper_j6_flange -> optical) * (optical -> camera_link)
860
+ Tc = self._T_j6_to_camera @ self._T_optical_to_camlink
861
+ tc = TransformStamped()
862
+ tc.header.stamp = stamp
863
+ tc.header.frame_id = TF_FRAME_J6_FLANGE
864
+ tc.child_frame_id = TF_FRAME_CAMERA
865
+ tc.transform.translation.x = float(Tc[0, 3])
866
+ tc.transform.translation.y = float(Tc[1, 3])
867
+ tc.transform.translation.z = float(Tc[2, 3])
868
+ qx, qy, qz, qw = rotation_matrix_to_quaternion(Tc[:3, :3])
869
+ tc.transform.rotation.x = qx
870
+ tc.transform.rotation.y = qy
871
+ tc.transform.rotation.z = qz
872
+ tc.transform.rotation.w = qw
873
+ self._tf_broadcaster.sendTransform(tc)
874
+ # 若有最佳抓取姿态:base_link -> grasp_target
875
+ if self.best_grasp_T is not None:
876
+ tg = TransformStamped()
877
+ tg.header.stamp = stamp
878
+ tg.header.frame_id = TF_FRAME_BASE
879
+ tg.child_frame_id = TF_FRAME_GRASP_TARGET
880
+ tg.transform.translation.x = float(self.best_grasp_T[0, 3])
881
+ tg.transform.translation.y = float(self.best_grasp_T[1, 3])
882
+ tg.transform.translation.z = float(self.best_grasp_T[2, 3])
883
+ qx, qy, qz, qw = rotation_matrix_to_quaternion(self.best_grasp_T[:3, :3])
884
+ tg.transform.rotation.x = qx
885
+ tg.transform.rotation.y = qy
886
+ tg.transform.rotation.z = qz
887
+ tg.transform.rotation.w = qw
888
+ self._tf_broadcaster.sendTransform(tg)
889
+
890
+ def _publish_aabb_marker(self, min_pt, max_pt, R_obb, center_obb, frame_id):
891
+ """在 RViz 中可视化 AABB/OBB 盒(用 CUBE marker 表示)。"""
892
+ if not _ROS_AVAILABLE or self._node is None or self._aabb_marker_pub is None:
893
+ return
894
+ stamp = self._node.get_clock().now().to_msg()
895
+ marker = Marker()
896
+ marker.header.stamp = stamp
897
+ marker.header.frame_id = frame_id
898
+ marker.ns = "sam3_aabb"
899
+ marker.id = 0
900
+ marker.type = Marker.CUBE
901
+ marker.action = Marker.ADD
902
+
903
+ marker.pose.position.x = float(center_obb[0])
904
+ marker.pose.position.y = float(center_obb[1])
905
+ marker.pose.position.z = float(center_obb[2])
906
+ qx, qy, qz, qw = rotation_matrix_to_quaternion(R_obb)
907
+ marker.pose.orientation.x = qx
908
+ marker.pose.orientation.y = qy
909
+ marker.pose.orientation.z = qz
910
+ marker.pose.orientation.w = qw
911
+
912
+ marker.scale.x = float(max_pt[0] - min_pt[0])
913
+ marker.scale.y = float(max_pt[1] - min_pt[1])
914
+ marker.scale.z = float(max_pt[2] - min_pt[2])
915
+ marker.color.r = 1.0
916
+ marker.color.g = 0.0
917
+ marker.color.b = 0.0
918
+ marker.color.a = 0.4
919
+ marker.lifetime = BuiltinDuration(sec=0, nanosec=0) # 0 = 常驻不自动删除
920
+ self._aabb_marker_pub.publish(marker)
921
+
922
+ def _make_aabb_marker(self, min_pt, max_pt, R_obb, center_obb, frame_id, marker_id=0):
923
+ """构造 AABB CUBE Marker(用于加入 MarkerArray),不发布。"""
924
+ if not _ROS_AVAILABLE or self._node is None:
925
+ return None
926
+ stamp = self._node.get_clock().now().to_msg()
927
+ marker = Marker()
928
+ marker.header.stamp = stamp
929
+ marker.header.frame_id = frame_id
930
+ marker.ns = "sam3_aabb"
931
+ marker.id = int(marker_id)
932
+ marker.type = Marker.CUBE
933
+ marker.action = Marker.ADD
934
+ marker.pose.position.x = float(center_obb[0])
935
+ marker.pose.position.y = float(center_obb[1])
936
+ marker.pose.position.z = float(center_obb[2])
937
+ qx, qy, qz, qw = rotation_matrix_to_quaternion(R_obb)
938
+ marker.pose.orientation.x = qx
939
+ marker.pose.orientation.y = qy
940
+ marker.pose.orientation.z = qz
941
+ marker.pose.orientation.w = qw
942
+ marker.scale.x = float(max_pt[0] - min_pt[0])
943
+ marker.scale.y = float(max_pt[1] - min_pt[1])
944
+ marker.scale.z = float(max_pt[2] - min_pt[2])
945
+ marker.color.r = 1.0
946
+ marker.color.g = 0.0
947
+ marker.color.b = 0.0
948
+ marker.color.a = 0.4
949
+ marker.lifetime = BuiltinDuration(sec=0, nanosec=0)
950
+ return marker
951
+
952
+ def _publish_grasp_pose_markers(self, center, R_grasp, frame_id):
953
+ """发布抓取姿态:PoseStamped + 轴线 Marker,供 RViz 可视化。"""
954
+ if not _ROS_AVAILABLE or self._node is None:
955
+ return
956
+ stamp = self._node.get_clock().now().to_msg()
957
+
958
+ # PoseStamped
959
+ if self._grasp_pose_pub is not None:
960
+ pose_msg = PoseStamped()
961
+ pose_msg.header.stamp = stamp
962
+ pose_msg.header.frame_id = frame_id
963
+ pose_msg.pose.position.x = float(center[0])
964
+ pose_msg.pose.position.y = float(center[1])
965
+ pose_msg.pose.position.z = float(center[2])
966
+ qx, qy, qz, qw = rotation_matrix_to_quaternion(R_grasp)
967
+ pose_msg.pose.orientation.x = qx
968
+ pose_msg.pose.orientation.y = qy
969
+ pose_msg.pose.orientation.z = qz
970
+ pose_msg.pose.orientation.w = qw
971
+ self._grasp_pose_pub.publish(pose_msg)
972
+
973
+ # 轴线 Marker(LINE_LIST)
974
+ if self._grasp_axes_pub is not None:
975
+ marker = Marker()
976
+ marker.header.stamp = stamp
977
+ marker.header.frame_id = frame_id
978
+ marker.ns = "sam3_grasp_axes"
979
+ marker.id = 0
980
+ marker.type = Marker.LINE_LIST
981
+ marker.action = Marker.ADD
982
+
983
+ marker.pose.position.x = float(center[0])
984
+ marker.pose.position.y = float(center[1])
985
+ marker.pose.position.z = float(center[2])
986
+ qx, qy, qz, qw = rotation_matrix_to_quaternion(R_grasp)
987
+ marker.pose.orientation.x = qx
988
+ marker.pose.orientation.y = qy
989
+ marker.pose.orientation.z = qz
990
+ marker.pose.orientation.w = qw
991
+
992
+ marker.scale.x = 0.005 # 线宽
993
+ axis_len = 0.1
994
+
995
+ # 定义局部坐标下的三条轴
996
+ from geometry_msgs.msg import Point as GeoPoint # local alias
997
+
998
+ def p(x, y, z):
999
+ pt = GeoPoint()
1000
+ pt.x = float(x)
1001
+ pt.y = float(y)
1002
+ pt.z = float(z)
1003
+ return pt
1004
+
1005
+ x_start, x_end = p(0, 0, 0), p(axis_len, 0, 0)
1006
+ y_start, y_end = p(0, 0, 0), p(0, axis_len, 0)
1007
+ z_start, z_end = p(0, 0, 0), p(0, 0, axis_len)
1008
+
1009
+ marker.points = [x_start, x_end, y_start, y_end, z_start, z_end]
1010
+
1011
+ from std_msgs.msg import ColorRGBA
1012
+
1013
+ xr = ColorRGBA(r=1.0, g=0.0, b=0.0, a=1.0)
1014
+ yr = ColorRGBA(r=0.0, g=1.0, b=0.0, a=1.0)
1015
+ zr = ColorRGBA(r=0.0, g=0.0, b=1.0, a=1.0)
1016
+ marker.colors = [xr, xr, yr, yr, zr, zr]
1017
+ marker.lifetime = BuiltinDuration(sec=0, nanosec=0) # 常驻
1018
+ self._grasp_axes_pub.publish(marker)
1019
+
1020
+ def _make_grasp_axes_marker(self, center, R_grasp, frame_id, marker_id=0):
1021
+ """构造抓取轴线 LINE_LIST Marker(用于加入 MarkerArray),不发布。"""
1022
+ if not _ROS_AVAILABLE or self._node is None:
1023
+ return None
1024
+ from geometry_msgs.msg import Point as GeoPoint
1025
+ from std_msgs.msg import ColorRGBA
1026
+ stamp = self._node.get_clock().now().to_msg()
1027
+ marker = Marker()
1028
+ marker.header.stamp = stamp
1029
+ marker.header.frame_id = frame_id
1030
+ marker.ns = "sam3_grasp_axes"
1031
+ marker.id = int(marker_id)
1032
+ marker.type = Marker.LINE_LIST
1033
+ marker.action = Marker.ADD
1034
+ marker.pose.position.x = float(center[0])
1035
+ marker.pose.position.y = float(center[1])
1036
+ marker.pose.position.z = float(center[2])
1037
+ qx, qy, qz, qw = rotation_matrix_to_quaternion(R_grasp)
1038
+ marker.pose.orientation.x = qx
1039
+ marker.pose.orientation.y = qy
1040
+ marker.pose.orientation.z = qz
1041
+ marker.pose.orientation.w = qw
1042
+ marker.scale.x = 0.005
1043
+ axis_len = 0.1
1044
+ def p(x, y, z):
1045
+ pt = GeoPoint()
1046
+ pt.x = float(x)
1047
+ pt.y = float(y)
1048
+ pt.z = float(z)
1049
+ return pt
1050
+ marker.points = [p(0, 0, 0), p(axis_len, 0, 0), p(0, 0, 0), p(0, axis_len, 0), p(0, 0, 0), p(0, 0, axis_len)]
1051
+ marker.colors = [
1052
+ ColorRGBA(r=1.0, g=0.0, b=0.0, a=1.0), ColorRGBA(r=1.0, g=0.0, b=0.0, a=1.0),
1053
+ ColorRGBA(r=0.0, g=1.0, b=0.0, a=1.0), ColorRGBA(r=0.0, g=1.0, b=0.0, a=1.0),
1054
+ ColorRGBA(r=0.0, g=0.0, b=1.0, a=1.0), ColorRGBA(r=0.0, g=0.0, b=1.0, a=1.0),
1055
+ ]
1056
+ marker.lifetime = BuiltinDuration(sec=0, nanosec=0)
1057
+ return marker
1058
+
1059
+ def remove_background(self, color_image, depth_image_m, clipping_dist):
1060
+ """基于深度距离移除背景,输入为 numpy 数组形式的彩色图和以米为单位的深度图。"""
1061
+ if color_image is None or depth_image_m is None:
1062
+ return None, None
1063
+
1064
+ original_color_image = color_image.copy()
1065
+ bg_removed_color_image = color_image.copy()
1066
+
1067
+ pixels_distance = depth_image_m
1068
+ background_mask = (pixels_distance <= 0) | (pixels_distance > clipping_dist)
1069
+ bg_removed_color_image[background_mask] = [0x99, 0x99, 0x99]
1070
+
1071
+ return bg_removed_color_image, original_color_image
1072
+
1073
+ def on_trackbar_change(self, value):
1074
+ """滑块回调函数,转换为米(value/100)"""
1075
+ self.depth_clipping_distance = value / 100.0
1076
+
1077
+ def _enable_robot_joints(self):
1078
+ """使能所有关节(带超时)"""
1079
+ if self.robot is None:
1080
+ return False
1081
+ start_t = time.monotonic()
1082
+ while time.monotonic() - start_t < 10.0:
1083
+ if self.robot.enable(joint_index=255):
1084
+ return True
1085
+ time.sleep(0.01)
1086
+ return False
1087
+
1088
+ def _switch_to_master_mode(self):
1089
+ """A:切换到主臂零力拖动模式"""
1090
+ if self.robot is None:
1091
+ print("[Robot] 未连接机械臂")
1092
+ return
1093
+ if self.is_master_mode:
1094
+ print("[Robot] 已处于主臂模式")
1095
+ return
1096
+ self.robot.disable(joint_index=255)
1097
+ time.sleep(0.2)
1098
+ self.robot.set_master_mode()
1099
+ time.sleep(1)
1100
+ self.is_master_mode = True
1101
+ print("[Robot] 已切换到主臂模式(零力拖动)")
1102
+
1103
+ def _switch_to_normal_mode_and_record(self):
1104
+ """D:切换到普通模式并记录当前位姿,更新 T_result 与 recorded_j6_pose"""
1105
+ if self.robot is None:
1106
+ print("[Robot] 未连接机械臂")
1107
+ return
1108
+ if self.is_master_mode:
1109
+ self.robot.reset()
1110
+ time.sleep(0.5)
1111
+ self.robot.set_slave_mode()
1112
+ time.sleep(0.5)
1113
+ if not self._enable_robot_joints():
1114
+ print("[Robot] 使能失败")
1115
+ return
1116
+ self.robot.set_speed_percent(SPEED_PERCENT)
1117
+ self.robot.set_motion_mode(self.robot.OPTIONS.MOTION_MODE.P)
1118
+ self.is_master_mode = False
1119
+ print("[Robot] 已切换到普通模式")
1120
+ my_flange_pose_msg = self.robot.get_flange_pose()
1121
+ print("my_flange_pose_msg:", my_flange_pose_msg)
1122
+ self.recorded_j6_pose = my_flange_pose_msg.msg
1123
+ save_pose_to_file(self.recorded_j6_pose)
1124
+ print("[Robot] 位姿已记录并保存,J6:", [round(p, 4) for p in self.recorded_j6_pose])
1125
+ T_j6 = pose_to_homogeneous_matrix(self.recorded_j6_pose)
1126
+ T_j6_to_camera = quat_pose_to_homogeneous_matrix(J6_TO_CAMERA)
1127
+ self.T_result = np.matmul(T_j6, T_j6_to_camera).astype(np.float32)
1128
+ print("[Robot] T_result 已更新(相机在基座系下)")
1129
+
1130
+ def _move_to_home(self):
1131
+ """S:机械臂回零"""
1132
+ if self.robot is None:
1133
+ print("[Robot] 未连接机械臂")
1134
+ return
1135
+ if self.is_master_mode:
1136
+ print("[Robot] 主臂模式下无法回零,请先按 D 切换普通模式")
1137
+ return
1138
+ print("[Robot] 回零中...")
1139
+ self.robot.move_j([0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
1140
+ start_t = time.monotonic()
1141
+ while time.monotonic() - start_t < MOTION_TIMEOUT:
1142
+ st = self.robot.get_arm_status()
1143
+ if st and st.msg.motion_status == 0:
1144
+ print("[Robot] 回零完成")
1145
+ return
1146
+ time.sleep(0.1)
1147
+ print("[Robot] 回零超时")
1148
+
1149
+ def _restore_recorded_pose(self):
1150
+ """X:复现记录的 J6 法兰位姿"""
1151
+ if self.robot is None:
1152
+ print("[Robot] 未连接机械臂")
1153
+ return
1154
+ if self.is_master_mode:
1155
+ print("[Robot] 主臂模式下无法复现,请先按 D 切换普通模式")
1156
+ return
1157
+ if self.recorded_j6_pose is None:
1158
+ print("[Robot] 未记录位姿,请先按 D 记录")
1159
+ return
1160
+ print("[Robot] 复现 J6 位姿...")
1161
+ self.robot.move_p(self.recorded_j6_pose)
1162
+ start_t = time.monotonic()
1163
+ while time.monotonic() - start_t < MOTION_TIMEOUT:
1164
+ st = self.robot.get_arm_status()
1165
+ if st and st.msg.motion_status == 0:
1166
+ print("[Robot] 位姿复现完成")
1167
+ return
1168
+ time.sleep(0.1)
1169
+ print("[Robot] 复现超时")
1170
+
1171
+ def _gripper_max(self):
1172
+ """Q:夹爪开到最大"""
1173
+ if self.end_effector is None:
1174
+ print("[Robot] 未连接夹爪")
1175
+ return
1176
+ try:
1177
+ self.end_effector.move_gripper(width=GRIPPER_MAX_WIDTH, force=GRIPPER_FORCE)
1178
+ time.sleep(1.0)
1179
+ print(f"[Robot] 夹爪已开到最大 ({GRIPPER_MAX_WIDTH*100}cm)")
1180
+ except Exception as e:
1181
+ print(f"[Robot] 夹爪控制失败: {e}")
1182
+
1183
+ def _gripper_min(self):
1184
+ """E:夹爪闭合到最小"""
1185
+ if self.end_effector is None:
1186
+ print("[Robot] 未连接夹爪")
1187
+ return
1188
+ try:
1189
+ self.end_effector.move_gripper(width=GRIPPER_MIN_WIDTH, force=GRIPPER_FORCE)
1190
+ time.sleep(1.0)
1191
+ print("[Robot] 夹爪已闭合")
1192
+ except Exception as e:
1193
+ print(f"[Robot] 夹爪控制失败: {e}")
1194
+
1195
+ def _compute_grasp_from_current_frame(self, original_color_image):
1196
+ """
1197
+ 基于当前帧(original_color_image + self._latest_depth + self.last_masks)计算点云与抓取姿态。
1198
+ 设置 self.best_grasp_T,发布 AABB/抓取 Marker;返回 (是否检测到有效目标, all_pts, all_cols)。
1199
+ """
1200
+ if (
1201
+ self._latest_depth is None
1202
+ or self.last_masks is None
1203
+ or self.last_obj_ids is None
1204
+ or self.fx is None
1205
+ or self.fy is None
1206
+ ):
1207
+ return False, [], []
1208
+ depth_raw = self._latest_depth.copy()
1209
+ h_d, w_d = depth_raw.shape
1210
+ depth_m = depth_raw.astype(np.float32) * float(DEPTH_SCALE_ROS)
1211
+ color_rgb = cv2.cvtColor(original_color_image, cv2.COLOR_BGR2RGB)
1212
+ best_grasp_score = -1.0
1213
+ best_grasp_T_cam = None
1214
+ all_pts = []
1215
+ all_cols = []
1216
+ aabb_markers = []
1217
+ grasp_markers = []
1218
+ for idx, mask_arr in enumerate(self.last_masks):
1219
+ if idx >= len(self.last_obj_ids):
1220
+ break
1221
+ mask = mask_arr
1222
+ if mask.shape != depth_raw.shape:
1223
+ mask = cv2.resize(
1224
+ mask.astype(np.uint8),
1225
+ (w_d, h_d),
1226
+ interpolation=cv2.INTER_NEAREST,
1227
+ )
1228
+ mask = mask.astype(bool)
1229
+ valid = (depth_m > 0.0) & mask
1230
+ ys, xs = np.where(valid)
1231
+ if ys.size == 0:
1232
+ continue
1233
+ z_cam = depth_m[ys, xs]
1234
+ x_cam = (
1235
+ (xs.astype(np.float32) - float(self.cx)) * z_cam / float(self.fx)
1236
+ )
1237
+ y_cam = (
1238
+ (ys.astype(np.float32) - float(self.cy)) * z_cam / float(self.fy)
1239
+ )
1240
+ pts_cam = np.stack([x_cam, y_cam, z_cam], axis=1)
1241
+ cols = color_rgb[ys, xs].astype(np.float32) / 255.0
1242
+ pcd_raw = o3d.geometry.PointCloud()
1243
+ pcd_raw.points = o3d.utility.Vector3dVector(pts_cam)
1244
+ pcd_raw.colors = o3d.utility.Vector3dVector(cols)
1245
+ pcd_down = pcd_raw.voxel_down_sample(voxel_size=0.005)
1246
+ if len(pcd_down.points) > 0:
1247
+ pcd_denoised, _ = pcd_down.remove_statistical_outlier(
1248
+ nb_neighbors=20, std_ratio=2.0
1249
+ )
1250
+ else:
1251
+ pcd_denoised = pcd_raw
1252
+ pcd_show = pcd_denoised if len(pcd_denoised.points) > 0 else pcd_raw
1253
+ all_pts.append(np.asarray(pcd_show.points, dtype=np.float32))
1254
+ all_cols.append(np.asarray(pcd_show.colors, dtype=np.float32))
1255
+ obb = pcd_show.get_oriented_bounding_box()
1256
+ center_obb = obb.center
1257
+ R_obb = obb.R
1258
+ pts_for_grasp = np.asarray(pcd_show.points, dtype=np.float64)
1259
+ result = compute_grasp_from_pca_aabb(
1260
+ pts_for_grasp, gripper_max_opening=float(GRIPPER_MAX_WIDTH)
1261
+ )
1262
+ if result is None:
1263
+ continue
1264
+ center, R_grasp = result
1265
+ R_grasp = align_grasp_x_toward_base(R_grasp, self.T_result)
1266
+ T_grasp_cam = np.eye(4, dtype=np.float32)
1267
+ T_grasp_cam[:3, :3] = R_grasp
1268
+ T_grasp_cam[:3, 3] = center
1269
+ dist = np.linalg.norm(center)
1270
+ score = 1.0 / (1.0 + dist)
1271
+ if score > best_grasp_score:
1272
+ best_grasp_score = score
1273
+ best_grasp_T_cam = T_grasp_cam
1274
+ min_b = np.asarray(obb.get_min_bound(), dtype=np.float64)
1275
+ max_b = np.asarray(obb.get_max_bound(), dtype=np.float64)
1276
+ try:
1277
+ self._publish_aabb_marker(
1278
+ min_b, max_b, R_obb, center_obb, CAMERA_OPTICAL_FRAME
1279
+ )
1280
+ self._publish_grasp_pose_markers(
1281
+ center, R_grasp, CAMERA_OPTICAL_FRAME
1282
+ )
1283
+ if _ROS_AVAILABLE and getattr(self, "_marker_array_pub", None):
1284
+ m_aabb = self._make_aabb_marker(
1285
+ min_b, max_b, R_obb, center_obb,
1286
+ CAMERA_OPTICAL_FRAME, len(aabb_markers)
1287
+ )
1288
+ m_grasp = self._make_grasp_axes_marker(
1289
+ center, R_grasp, CAMERA_OPTICAL_FRAME,
1290
+ len(aabb_markers) + len(grasp_markers)
1291
+ )
1292
+ if m_aabb is not None:
1293
+ aabb_markers.append(m_aabb)
1294
+ if m_grasp is not None:
1295
+ grasp_markers.append(m_grasp)
1296
+ except Exception:
1297
+ pass
1298
+ if _ROS_AVAILABLE and getattr(self, "_marker_array_pub", None) and (aabb_markers or grasp_markers):
1299
+ arr = MarkerArray()
1300
+ arr.markers = aabb_markers + grasp_markers
1301
+ self._marker_array_pub.publish(arr)
1302
+ if best_grasp_T_cam is not None:
1303
+ T_grasp_cam_h = np.eye(4, dtype=np.float32)
1304
+ T_grasp_cam_h[:3, :3] = best_grasp_T_cam[:3, :3]
1305
+ T_grasp_cam_h[:3, 3] = best_grasp_T_cam[:3, 3]
1306
+ T_grasp_base = (self.T_result @ T_grasp_cam_h).astype(np.float32)
1307
+ self.best_grasp_T = T_grasp_base
1308
+ print(
1309
+ "[GRASP] 选中的最佳抓取姿态(基座坐标系下 4x4 齐次矩阵):\n",
1310
+ self.best_grasp_T,
1311
+ )
1312
+ else:
1313
+ self.best_grasp_T = None
1314
+ return self.best_grasp_T is not None, all_pts, all_cols
1315
+
1316
+ def _do_grasp_move(self):
1317
+ """执行 g 功能:下发当前最佳抓取姿态并等待机械臂到达。"""
1318
+ if self.robot is None:
1319
+ print("[GRASP] 未连接机械臂,无法下发抓取姿态")
1320
+ return
1321
+ if self.best_grasp_T is None:
1322
+ print("[GRASP] 无抓取姿态,请先执行 p 计算")
1323
+ return
1324
+ T_tcp = self.best_grasp_T
1325
+ T_tcp_to_flange = np.eye(4, dtype=np.float32)
1326
+ T_tcp_to_flange[2, 3] = -float(TCP_OFFSET[2])
1327
+ T_flange = (T_tcp @ T_tcp_to_flange).astype(np.float32)
1328
+ pose_flange = homogeneous_to_pose(T_flange)
1329
+ print("[GRASP] 下发抓取姿态(法兰位姿):", [round(p, 4) for p in pose_flange])
1330
+ try:
1331
+ self.robot.move_p(pose_flange)
1332
+ start_t = time.monotonic()
1333
+ while True:
1334
+ arm_status = self.robot.get_arm_status()
1335
+ if arm_status and arm_status.msg.motion_status == 0:
1336
+ print("[GRASP] 机械臂已到达目标位姿")
1337
+ break
1338
+ if time.monotonic() - start_t > MOTION_TIMEOUT:
1339
+ print("[GRASP] 运动超时")
1340
+ break
1341
+ time.sleep(0.1)
1342
+ except Exception as e:
1343
+ print(f"[GRASP] 下发失败: {e}")
1344
+
1345
+ def run(self):
1346
+ """主运行函数:RealSense 采集 + SAM3 实时推理"""
1347
+ try:
1348
+ self.running = True
1349
+
1350
+ with torch.no_grad():
1351
+ while self.running:
1352
+ self.frame_counter += 1
1353
+ if cv2.getWindowProperty(self.window_name, cv2.WND_PROP_VISIBLE) < 1:
1354
+ break
1355
+ # 有机械臂且非主臂模式时,用当前 J6 位姿更新 T_result(相机在基座系下)
1356
+ if self.robot is not None and not self.is_master_mode:
1357
+ fp = self.robot.get_flange_pose()
1358
+ if fp is not None and len(fp.msg) >= 6:
1359
+ T_j6 = pose_to_homogeneous_matrix(fp.msg)
1360
+ self.T_result = (T_j6 @ self._T_j6_to_camera).astype(np.float32)
1361
+ if _ROS_AVAILABLE and self._node is not None:
1362
+ rclpy.spin_once(self._node, timeout_sec=0)
1363
+ # 有机械臂且非主臂模式时,用当前 J6 位姿更新 T_result(相机在基座系下)
1364
+ if self.robot is not None and not self.is_master_mode:
1365
+ fp = self.robot.get_flange_pose()
1366
+ if fp is not None and len(fp.msg) >= 6:
1367
+ T_j6 = pose_to_homogeneous_matrix(fp.msg)
1368
+ self.T_result = (T_j6 @ self._T_j6_to_camera).astype(np.float32)
1369
+ self._publish_tf()
1370
+
1371
+ # 等待 ROS 相机话题(颜色图 + 对齐深度图)准备就绪
1372
+ if self._latest_color is None or self._latest_depth is None:
1373
+ continue
1374
+ color_image = self._latest_color.copy()
1375
+ depth_raw = self._latest_depth.copy()
1376
+
1377
+ # 相机内参应从 CameraInfo 话题获取,若尚未获取则暂不处理
1378
+ if (
1379
+ self.fx is None
1380
+ or self.fy is None
1381
+ or self.cx is None
1382
+ or self.cy is None
1383
+ ):
1384
+ continue
1385
+
1386
+ # depth_raw: uint16, 单位 mm -> 转为 m
1387
+ depth_m = depth_raw.astype(np.float32) * float(DEPTH_SCALE_ROS)
1388
+
1389
+ color_image_bg_removed, original_color_image = self.remove_background(
1390
+ color_image,
1391
+ depth_m,
1392
+ self.depth_clipping_distance,
1393
+ )
1394
+
1395
+ # 可视化深度伪彩色图
1396
+ depth_norm = depth_m / max(self.depth_clipping_distance, 1e-3)
1397
+ depth_norm = np.clip(depth_norm, 0.0, 1.0)
1398
+ depth_colormap = cv2.applyColorMap(
1399
+ (depth_norm * 255.0).astype(np.uint8), cv2.COLORMAP_JET
1400
+ )
1401
+
1402
+ h, w = color_image_bg_removed.shape[:2]
1403
+ pip_w, pip_h = int(w / 5), int(h / 5)
1404
+ margin = int(max(w, h) / 25)
1405
+
1406
+ # ===== SAM3 实时推理(通过子进程)=====
1407
+ rgb_for_sam = cv2.cvtColor(original_color_image, cv2.COLOR_BGR2RGB)
1408
+
1409
+ # 往子进程发送当前帧(队列满则跳过,避免阻塞)
1410
+ if not self.sam_input_q.full():
1411
+ try:
1412
+ self.sam_input_q.put_nowait(rgb_for_sam)
1413
+ except queue.Full:
1414
+ pass
1415
+
1416
+ # 尝试从子进程获取最新的分割结果与掩码(如无新结果则继续使用上一帧)
1417
+ try:
1418
+ while True:
1419
+ data = self.sam_output_q.get_nowait()
1420
+ self.last_overlay_bgr = cv2.cvtColor(
1421
+ data["overlay"], cv2.COLOR_RGB2BGR
1422
+ )
1423
+ self.last_masks = data.get("masks", None)
1424
+ self.last_obj_ids = data.get("ids", None)
1425
+ except queue.Empty:
1426
+ pass
1427
+
1428
+ # ===== 组合深度/RGB 画中画 =====
1429
+ # 主画面:去背景后的彩色图
1430
+ final_display_image = color_image_bg_removed.copy()
1431
+
1432
+ # 深度图画中画(右上角)
1433
+ depth_pip = cv2.resize(depth_colormap, (pip_w, pip_h))
1434
+ depth_pip_x = w - pip_w - margin
1435
+ depth_pip_y = margin
1436
+ final_display_image[
1437
+ depth_pip_y : depth_pip_y + pip_h,
1438
+ depth_pip_x : depth_pip_x + pip_w,
1439
+ ] = depth_pip
1440
+
1441
+ # 原始 RGB 画中画(右下角)
1442
+ rgb_pip = cv2.resize(original_color_image, (pip_w, pip_h))
1443
+ rgb_pip_x = w - pip_w - margin
1444
+ rgb_pip_y = h - pip_h - margin
1445
+ final_display_image[
1446
+ rgb_pip_y : rgb_pip_y + pip_h,
1447
+ rgb_pip_x : rgb_pip_x + pip_w,
1448
+ ] = rgb_pip
1449
+
1450
+ # SAM3 分割结果画中画(左上角),如果已有结果
1451
+ if self.last_overlay_bgr is not None:
1452
+ sam_pip = cv2.resize(self.last_overlay_bgr, (pip_w, pip_h))
1453
+ sam_pip_x = margin
1454
+ sam_pip_y = margin
1455
+ final_display_image[
1456
+ sam_pip_y : sam_pip_y + pip_h,
1457
+ sam_pip_x : sam_pip_x + pip_w,
1458
+ ] = sam_pip
1459
+
1460
+ # 文字提示
1461
+ cv2.putText(
1462
+ final_display_image,
1463
+ f"Depth Clip: {self.depth_clipping_distance:.2f}m",
1464
+ (10, 30),
1465
+ cv2.FONT_HERSHEY_SIMPLEX,
1466
+ 1,
1467
+ (0, 255, 0),
1468
+ 2,
1469
+ )
1470
+ cv2.putText(
1471
+ final_display_image,
1472
+ f"SAM3 Text Prompt: '{self.text_prompt}'",
1473
+ (10, 65),
1474
+ cv2.FONT_HERSHEY_SIMPLEX,
1475
+ 0.7,
1476
+ (0, 255, 255),
1477
+ 2,
1478
+ )
1479
+ cv2.putText(
1480
+ final_display_image,
1481
+ "Depth",
1482
+ (depth_pip_x + 5, depth_pip_y + 20),
1483
+ cv2.FONT_HERSHEY_SIMPLEX,
1484
+ 0.5,
1485
+ (255, 255, 255),
1486
+ 1,
1487
+ )
1488
+ cv2.putText(
1489
+ final_display_image,
1490
+ "RGB",
1491
+ (rgb_pip_x + 5, rgb_pip_y + 20),
1492
+ cv2.FONT_HERSHEY_SIMPLEX,
1493
+ 0.5,
1494
+ (255, 255, 255),
1495
+ 1,
1496
+ )
1497
+ if self.last_overlay_bgr is not None:
1498
+ cv2.putText(
1499
+ final_display_image,
1500
+ "SAM3",
1501
+ (margin + 5, margin + 20),
1502
+ cv2.FONT_HERSHEY_SIMPLEX,
1503
+ 0.5,
1504
+ (255, 255, 255),
1505
+ 1,
1506
+ )
1507
+
1508
+ cv2.imshow(self.window_name, final_display_image)
1509
+
1510
+ # ---------- 自动化模式(--auto)状态机 ----------
1511
+ if self.auto_mode:
1512
+ now = time.monotonic()
1513
+ sam_ready = (
1514
+ self.last_masks is not None
1515
+ and self.last_obj_ids is not None
1516
+ and self.fx is not None
1517
+ and self._latest_depth is not None
1518
+ )
1519
+ if self._auto_state == 0:
1520
+ if sam_ready:
1521
+ print("[Auto] SAM3 已就绪,执行 X(复现位姿)")
1522
+ self._restore_recorded_pose()
1523
+ self._auto_state_ts = now
1524
+ self._auto_state = 1
1525
+ elif self._auto_state == 1:
1526
+ if now - self._auto_state_ts >= 2.0:
1527
+ print("[Auto] 执行 q(夹爪开)")
1528
+ self._gripper_max()
1529
+ self._auto_state_ts = now
1530
+ self._auto_state = 2
1531
+ elif self._auto_state == 2:
1532
+ if now - self._auto_state_ts >= 1.0:
1533
+ self._auto_p_retries = 0
1534
+ self._auto_state = 3
1535
+ elif self._auto_state == 3:
1536
+ found, all_pts, all_cols = self._compute_grasp_from_current_frame(
1537
+ original_color_image
1538
+ )
1539
+ if found:
1540
+ if (
1541
+ self._pcd_pub is not None
1542
+ and len(all_pts) > 0
1543
+ and len(all_cols) > 0
1544
+ ):
1545
+ pts_cat = np.concatenate(all_pts, axis=0)
1546
+ cols_cat = np.concatenate(all_cols, axis=0)
1547
+ stamp = self._node.get_clock().now().to_msg()
1548
+ msg = make_pointcloud2(
1549
+ pts_cat, cols_cat, CAMERA_OPTICAL_FRAME, stamp
1550
+ )
1551
+ if msg is not None:
1552
+ self._pcd_pub.publish(msg)
1553
+ print("[Auto] p 检测到有效目标,延迟 2s 后执行 g")
1554
+ self._auto_state_ts = now
1555
+ self._auto_state = 4
1556
+ else:
1557
+ self._auto_p_retries += 1
1558
+ if self._auto_p_retries >= 10:
1559
+ print("[Auto] p 连续 10 次无有效目标,关闭程序")
1560
+ self.running = False
1561
+ break
1562
+ elif self._auto_state == 4:
1563
+ if now - self._auto_state_ts >= 2.0:
1564
+ print("[Auto] 执行 g(下发抓取)")
1565
+ self._do_grasp_move()
1566
+ self._auto_state_ts = now
1567
+ self._auto_state = 5
1568
+ elif self._auto_state == 5:
1569
+ if now - self._auto_state_ts >= 2.0:
1570
+ print("[Auto] 执行 e(夹爪合)")
1571
+ self._gripper_min()
1572
+ self._auto_state_ts = now
1573
+ self._auto_state = 6
1574
+ elif self._auto_state == 6:
1575
+ if now - self._auto_state_ts >= 1.0:
1576
+ print("[Auto] 执行 x(复现位姿)")
1577
+ self._restore_recorded_pose()
1578
+ self._auto_state_ts = now
1579
+ self._auto_state = 7
1580
+ elif self._auto_state == 7:
1581
+ if now - self._auto_state_ts >= 2.0:
1582
+ print("[Auto] 执行 s(回零)")
1583
+ self._move_to_home()
1584
+ self._auto_state_ts = now
1585
+ self._auto_state = 8
1586
+ elif self._auto_state == 8:
1587
+ if now - self._auto_state_ts >= 2.0:
1588
+ print("[Auto] 流程结束,退出程序")
1589
+ self.running = False
1590
+ break
1591
+ key = cv2.waitKey(1)
1592
+ if key & 0xFF == 27: # ESC 退出
1593
+ break
1594
+ key_lower = (key & 0xFF) | 0x20 if key >= 0 else -1 # 小写便于不区分大小写
1595
+ if key_lower == ord("a"):
1596
+ self._switch_to_master_mode()
1597
+ elif key_lower == ord("d"):
1598
+ self._switch_to_normal_mode_and_record()
1599
+ elif key_lower == ord("s"):
1600
+ self._move_to_home()
1601
+ elif key_lower == ord("x"):
1602
+ self._restore_recorded_pose()
1603
+ elif key_lower == ord("q"):
1604
+ self._gripper_max()
1605
+ elif key_lower == ord("e"):
1606
+ self._gripper_min()
1607
+ # 按 'p' 键:基于当前帧计算点云 + AABB + 抓取姿态,并通过 ROS (RViz) 可视化
1608
+ if (
1609
+ key & 0xFF == ord("p")
1610
+ and self.last_masks is not None
1611
+ and self.last_obj_ids is not None
1612
+ and self.fx is not None
1613
+ and self.fy is not None
1614
+ ):
1615
+ if self._latest_depth is None:
1616
+ print("[PCD] 当前无有效深度帧,无法生成点云")
1617
+ continue
1618
+ found, all_pts, all_cols = self._compute_grasp_from_current_frame(
1619
+ original_color_image
1620
+ )
1621
+ if (
1622
+ self._pcd_pub is not None
1623
+ and len(all_pts) > 0
1624
+ and len(all_cols) > 0
1625
+ ):
1626
+ pts_cat = np.concatenate(all_pts, axis=0)
1627
+ cols_cat = np.concatenate(all_cols, axis=0)
1628
+ stamp = self._node.get_clock().now().to_msg()
1629
+ msg = make_pointcloud2(
1630
+ pts_cat, cols_cat, CAMERA_OPTICAL_FRAME, stamp
1631
+ )
1632
+ if msg is not None:
1633
+ self._pcd_pub.publish(msg)
1634
+ # 按 't' 键:在终端输入新的文本提示词
1635
+ if key & 0xFF == ord("t"):
1636
+ try:
1637
+ new_prompt = input(
1638
+ "\n请输入新的 SAM3 文本提示(回车确认,留空则忽略):"
1639
+ ).strip()
1640
+ except EOFError:
1641
+ new_prompt = ""
1642
+ if new_prompt:
1643
+ self.text_prompt = new_prompt
1644
+ # 将新提示传递给 SAM 子进程
1645
+ try:
1646
+ self.prompt_q.put_nowait(new_prompt)
1647
+ except queue.Full:
1648
+ # 丢弃旧的,只保留最新
1649
+ try:
1650
+ while True:
1651
+ self.prompt_q.get_nowait()
1652
+ except queue.Empty:
1653
+ pass
1654
+ self.prompt_q.put_nowait(new_prompt)
1655
+ print(f"[Main] 已更新文本提示: '{self.text_prompt}'")
1656
+
1657
+ # 按 'g' 键:下发当前选中的最佳抓取姿态,控制机械臂 TCP 到达
1658
+ if key & 0xFF == ord("g"):
1659
+ self._do_grasp_move()
1660
+
1661
+ except Exception as e:
1662
+ print(f"Error: {e}")
1663
+ import traceback
1664
+
1665
+ traceback.print_exc()
1666
+ finally:
1667
+ self.stop()
1668
+
1669
+ def stop(self):
1670
+ """停止并释放资源"""
1671
+ self.running = False
1672
+ try:
1673
+ if hasattr(self, "pipeline") and self.pipeline is not None:
1674
+ self.pipeline.stop()
1675
+ except Exception:
1676
+ pass
1677
+ cv2.destroyAllWindows()
1678
+ print("RealSense pipeline stopped, resources released")
1679
+
1680
+ if __name__ == "__main__":
1681
+ parser = argparse.ArgumentParser(
1682
+ description="RealSense + SAM3 实时分割(SAM 在子进程 GPU 上运行),可选机械臂控制"
1683
+ )
1684
+ parser.add_argument(
1685
+ "--prompt",
1686
+ type=str,
1687
+ default="person",
1688
+ help="SAM3 文本提示,例如 'person', 'hand', 'chair' 等",
1689
+ )
1690
+ parser.add_argument(
1691
+ "--auto",
1692
+ action="store_true",
1693
+ help="自动化运行:X→q→p(最多10次)→g→e→x→s 后退出",
1694
+ )
1695
+ parser.add_argument(
1696
+ "--no-camera-launch",
1697
+ action="store_true",
1698
+ help="不自动拉起 RealSense ROS 节点(已手动启动时使用)",
1699
+ )
1700
+ args = parser.parse_args()
1701
+
1702
+ # RealSense ROS2 节点:程序内拉起,退出时关闭(可用 --no-camera-launch 跳过)
1703
+ camera_proc_ref = [None] # 用列表以便 signal 回调和 finally 共享
1704
+
1705
+ def _camera_exit_handler(signum, frame):
1706
+ stop_camera_launch(camera_proc_ref[0])
1707
+ camera_proc_ref[0] = None
1708
+ sys.exit(128 + (signum if signum < 128 else 0))
1709
+
1710
+ if _ROS_AVAILABLE and not args.no_camera_launch:
1711
+ camera_proc_ref[0] = start_camera_launch()
1712
+ if camera_proc_ref[0] is not None:
1713
+ signal.signal(signal.SIGINT, _camera_exit_handler)
1714
+ signal.signal(signal.SIGTERM, _camera_exit_handler)
1715
+
1716
+ node = None
1717
+ if _ROS_AVAILABLE:
1718
+ rclpy.init(args=None)
1719
+ node = Node("realsense_sam")
1720
+ tf_broadcaster = TransformBroadcaster(node)
1721
+ else:
1722
+ tf_broadcaster = None
1723
+ print("[TF] 未检测到 ROS2,将不发布 TF")
1724
+
1725
+ mp.set_start_method("spawn", force=True)
1726
+ sam_input_q: mp.Queue = mp.Queue(maxsize=2)
1727
+ sam_output_q: mp.Queue = mp.Queue(maxsize=2)
1728
+ prompt_q: mp.Queue = mp.Queue(maxsize=4)
1729
+
1730
+ sam_proc = mp.Process(
1731
+ target=sam_worker,
1732
+ args=(sam_input_q, sam_output_q, prompt_q, args.prompt),
1733
+ daemon=True,
1734
+ )
1735
+ sam_proc.start()
1736
+
1737
+ robot, end_effector = init_robot_and_gripper()
1738
+
1739
+ try:
1740
+ rs_align = RealSenseAlignAdvanced(
1741
+ text_prompt=args.prompt,
1742
+ sam_input_q=sam_input_q,
1743
+ sam_output_q=sam_output_q,
1744
+ prompt_q=prompt_q,
1745
+ robot=robot,
1746
+ end_effector=end_effector,
1747
+ node=node,
1748
+ tf_broadcaster=tf_broadcaster,
1749
+ auto_mode=args.auto,
1750
+ )
1751
+ if args.auto:
1752
+ print("[Auto] 自动化流程已启用:等待 SAM3 就绪后执行 X→q→p(最多10次)→g→e→x→s→退出")
1753
+ else:
1754
+ print(
1755
+ "按键: A=主臂零力 D=普通模式+记录位姿 S=回零 X=复现位姿 Q=夹爪开 E=夹爪合 "
1756
+ "p=点云/抓取 t=改提示词 g=下发抓取 Esc=退出"
1757
+ )
1758
+ rs_align.run()
1759
+ finally:
1760
+ stop_camera_launch(camera_proc_ref[0])
1761
+ camera_proc_ref[0] = None
1762
+ safe_shutdown_robot(robot, end_effector)
1763
+ if node is not None:
1764
+ node.destroy_node()
1765
+ if _ROS_AVAILABLE:
1766
+ rclpy.shutdown()
1767
+ try:
1768
+ sam_input_q.put_nowait(None)
1769
+ except queue.Full:
1770
+ pass
1771
+ sam_proc.join(timeout=5.0)
third_party/GraspGen/sam3/sam3/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ from .model_builder import build_sam3_image_model
6
+
7
+ __version__ = "0.1.0"
8
+
9
+ __all__ = ["build_sam3_image_model"]
third_party/GraspGen/sam3/sam3/eval/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
third_party/GraspGen/sam3/sam3/eval/cgf1_eval.py ADDED
@@ -0,0 +1,705 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ import contextlib
6
+ import copy
7
+ import json
8
+ import os
9
+ import time
10
+ from collections import defaultdict
11
+ from dataclasses import dataclass
12
+ from typing import List, Union
13
+
14
+ import numpy as np
15
+ import pycocotools.mask as maskUtils
16
+ from pycocotools.coco import COCO
17
+ from pycocotools.cocoeval import COCOeval
18
+ from scipy.optimize import linear_sum_assignment
19
+ from tqdm import tqdm
20
+
21
+
22
+ @dataclass
23
+ class Metric:
24
+ name: str
25
+
26
+ # whether the metric is computed at the image level or the box level
27
+ image_level: bool
28
+
29
+ # iou threshold (None is used for image level metrics or to indicate averaging over all thresholds in [0.5:0.95])
30
+ iou_threshold: Union[float, None]
31
+
32
+
33
+ CGF1_METRICS = [
34
+ Metric(name="cgF1", image_level=False, iou_threshold=None),
35
+ Metric(name="precision", image_level=False, iou_threshold=None),
36
+ Metric(name="recall", image_level=False, iou_threshold=None),
37
+ Metric(name="F1", image_level=False, iou_threshold=None),
38
+ Metric(name="positive_macro_F1", image_level=False, iou_threshold=None),
39
+ Metric(name="positive_micro_F1", image_level=False, iou_threshold=None),
40
+ Metric(name="positive_micro_precision", image_level=False, iou_threshold=None),
41
+ Metric(name="IL_precision", image_level=True, iou_threshold=None),
42
+ Metric(name="IL_recall", image_level=True, iou_threshold=None),
43
+ Metric(name="IL_F1", image_level=True, iou_threshold=None),
44
+ Metric(name="IL_FPR", image_level=True, iou_threshold=None),
45
+ Metric(name="IL_MCC", image_level=True, iou_threshold=None),
46
+ Metric(name="cgF1", image_level=False, iou_threshold=0.5),
47
+ Metric(name="precision", image_level=False, iou_threshold=0.5),
48
+ Metric(name="recall", image_level=False, iou_threshold=0.5),
49
+ Metric(name="F1", image_level=False, iou_threshold=0.5),
50
+ Metric(name="positive_macro_F1", image_level=False, iou_threshold=0.5),
51
+ Metric(name="positive_micro_F1", image_level=False, iou_threshold=0.5),
52
+ Metric(name="positive_micro_precision", image_level=False, iou_threshold=0.5),
53
+ Metric(name="cgF1", image_level=False, iou_threshold=0.75),
54
+ Metric(name="precision", image_level=False, iou_threshold=0.75),
55
+ Metric(name="recall", image_level=False, iou_threshold=0.75),
56
+ Metric(name="F1", image_level=False, iou_threshold=0.75),
57
+ Metric(name="positive_macro_F1", image_level=False, iou_threshold=0.75),
58
+ Metric(name="positive_micro_F1", image_level=False, iou_threshold=0.75),
59
+ Metric(name="positive_micro_precision", image_level=False, iou_threshold=0.75),
60
+ ]
61
+
62
+
63
+ class COCOCustom(COCO):
64
+ """COCO class from pycocotools with tiny modifications for speed"""
65
+
66
+ def createIndex(self):
67
+ # create index
68
+ print("creating index...")
69
+ anns, cats, imgs = {}, {}, {}
70
+ imgToAnns, catToImgs = defaultdict(list), defaultdict(list)
71
+ if "annotations" in self.dataset:
72
+ for ann in self.dataset["annotations"]:
73
+ imgToAnns[ann["image_id"]].append(ann)
74
+ anns[ann["id"]] = ann
75
+
76
+ if "images" in self.dataset:
77
+ # MODIFICATION: do not reload imgs if they are already there
78
+ if self.imgs:
79
+ imgs = self.imgs
80
+ else:
81
+ for img in self.dataset["images"]:
82
+ imgs[img["id"]] = img
83
+ # END MODIFICATION
84
+
85
+ if "categories" in self.dataset:
86
+ for cat in self.dataset["categories"]:
87
+ cats[cat["id"]] = cat
88
+
89
+ if "annotations" in self.dataset and "categories" in self.dataset:
90
+ for ann in self.dataset["annotations"]:
91
+ catToImgs[ann["category_id"]].append(ann["image_id"])
92
+
93
+ print("index created!")
94
+
95
+ # create class members
96
+ self.anns = anns
97
+ self.imgToAnns = imgToAnns
98
+ self.catToImgs = catToImgs
99
+ self.imgs = imgs
100
+ self.cats = cats
101
+
102
+ def loadRes(self, resFile):
103
+ """
104
+ Load result file and return a result api object.
105
+ :param resFile (str) : file name of result file
106
+ :return: res (obj) : result api object
107
+ """
108
+ res = COCOCustom()
109
+ res.dataset["info"] = copy.deepcopy(self.dataset.get("info", {}))
110
+ # MODIFICATION: no copy
111
+ # res.dataset['images'] = [img for img in self.dataset['images']]
112
+ res.dataset["images"] = self.dataset["images"]
113
+ # END MODIFICATION
114
+
115
+ print("Loading and preparing results...")
116
+ tic = time.time()
117
+ if type(resFile) == str:
118
+ with open(resFile) as f:
119
+ anns = json.load(f)
120
+ elif type(resFile) == np.ndarray:
121
+ anns = self.loadNumpyAnnotations(resFile)
122
+ else:
123
+ anns = resFile
124
+ assert type(anns) == list, "results in not an array of objects"
125
+ annsImgIds = [ann["image_id"] for ann in anns]
126
+ # MODIFICATION: faster and cached subset check
127
+ if not hasattr(self, "img_id_set"):
128
+ self.img_id_set = set(self.getImgIds())
129
+ assert set(annsImgIds).issubset(self.img_id_set), (
130
+ "Results do not correspond to current coco set"
131
+ )
132
+ # END MODIFICATION
133
+ if "caption" in anns[0]:
134
+ imgIds = set([img["id"] for img in res.dataset["images"]]) & set(
135
+ [ann["image_id"] for ann in anns]
136
+ )
137
+ res.dataset["images"] = [
138
+ img for img in res.dataset["images"] if img["id"] in imgIds
139
+ ]
140
+ for id, ann in enumerate(anns):
141
+ ann["id"] = id + 1
142
+ elif "bbox" in anns[0] and not anns[0]["bbox"] == []:
143
+ res.dataset["categories"] = copy.deepcopy(self.dataset["categories"])
144
+ for id, ann in enumerate(anns):
145
+ bb = ann["bbox"]
146
+ x1, x2, y1, y2 = [bb[0], bb[0] + bb[2], bb[1], bb[1] + bb[3]]
147
+ if not "segmentation" in ann:
148
+ ann["segmentation"] = [[x1, y1, x1, y2, x2, y2, x2, y1]]
149
+ ann["area"] = bb[2] * bb[3]
150
+ ann["id"] = id + 1
151
+ ann["iscrowd"] = 0
152
+ elif "segmentation" in anns[0]:
153
+ res.dataset["categories"] = copy.deepcopy(self.dataset["categories"])
154
+ for id, ann in enumerate(anns):
155
+ # now only support compressed RLE format as segmentation results
156
+ ann["area"] = maskUtils.area(ann["segmentation"])
157
+ if not "bbox" in ann:
158
+ ann["bbox"] = maskUtils.toBbox(ann["segmentation"])
159
+ ann["id"] = id + 1
160
+ ann["iscrowd"] = 0
161
+ elif "keypoints" in anns[0]:
162
+ res.dataset["categories"] = copy.deepcopy(self.dataset["categories"])
163
+ for id, ann in enumerate(anns):
164
+ s = ann["keypoints"]
165
+ x = s[0::3]
166
+ y = s[1::3]
167
+ x0, x1, y0, y1 = np.min(x), np.max(x), np.min(y), np.max(y)
168
+ ann["area"] = (x1 - x0) * (y1 - y0)
169
+ ann["id"] = id + 1
170
+ ann["bbox"] = [x0, y0, x1 - x0, y1 - y0]
171
+ print("DONE (t={:0.2f}s)".format(time.time() - tic))
172
+
173
+ res.dataset["annotations"] = anns
174
+ # MODIFICATION: inherit images
175
+ res.imgs = self.imgs
176
+ # END MODIFICATION
177
+ res.createIndex()
178
+ return res
179
+
180
+
181
+ class CGF1Eval(COCOeval):
182
+ """
183
+ This evaluator is based upon COCO evaluation, but evaluates the model in a more realistic setting
184
+ for downstream applications.
185
+ See SAM3 paper for the details on the CGF1 metric.
186
+
187
+ Do not use this evaluator directly. Prefer the CGF1Evaluator wrapper.
188
+
189
+ Notes:
190
+ - This evaluator does not support per-category evaluation (in the way defined by pyCocotools)
191
+ - In open vocabulary settings, we have different noun-phrases for each image. What we call an "image_id" here is actually an (image, noun-phrase) pair. So in every "image_id" there is only one category, implied by the noun-phrase. Thus we can ignore the usual coco "category" field of the predictions
192
+ """
193
+
194
+ def __init__(
195
+ self,
196
+ coco_gt=None,
197
+ coco_dt=None,
198
+ iouType="segm",
199
+ threshold=0.5,
200
+ ):
201
+ """
202
+ Args:
203
+ coco_gt (COCO): ground truth COCO API
204
+ coco_dt (COCO): detections COCO API
205
+ iou_type (str): type of IoU to evaluate
206
+ threshold (float): threshold for predictions
207
+ """
208
+ super().__init__(coco_gt, coco_dt, iouType)
209
+ self.threshold = threshold
210
+
211
+ self.params.useCats = False
212
+ self.params.areaRng = [[0**2, 1e5**2]]
213
+ self.params.areaRngLbl = ["all"]
214
+ self.params.maxDets = [1000000]
215
+
216
+ def computeIoU(self, imgId, catId):
217
+ # Same as the original COCOeval.computeIoU, but without sorting
218
+ p = self.params
219
+ if p.useCats:
220
+ gt = self._gts[imgId, catId]
221
+ dt = self._dts[imgId, catId]
222
+ else:
223
+ gt = [_ for cId in p.catIds for _ in self._gts[imgId, cId]]
224
+ dt = [_ for cId in p.catIds for _ in self._dts[imgId, cId]]
225
+ if len(gt) == 0 and len(dt) == 0:
226
+ return []
227
+
228
+ if p.iouType == "segm":
229
+ g = [g["segmentation"] for g in gt]
230
+ d = [d["segmentation"] for d in dt]
231
+ elif p.iouType == "bbox":
232
+ g = [g["bbox"] for g in gt]
233
+ d = [d["bbox"] for d in dt]
234
+ else:
235
+ raise Exception("unknown iouType for iou computation")
236
+
237
+ # compute iou between each dt and gt region
238
+ iscrowd = [int(o["iscrowd"]) for o in gt]
239
+ ious = maskUtils.iou(d, g, iscrowd)
240
+ return ious
241
+
242
+ def evaluateImg(self, imgId, catId, aRng, maxDet):
243
+ """
244
+ perform evaluation for single category and image
245
+ :return: dict (single image results)
246
+ """
247
+ p = self.params
248
+ assert not p.useCats, "This evaluator does not support per-category evaluation."
249
+ assert catId == -1
250
+ all_gts = [_ for cId in p.catIds for _ in self._gts[imgId, cId]]
251
+ keep_gt = np.array([not g["ignore"] for g in all_gts], dtype=bool)
252
+ gt = [g for g in all_gts if not g["ignore"]]
253
+ all_dts = [_ for cId in p.catIds for _ in self._dts[imgId, cId]]
254
+ keep_dt = np.array([d["score"] >= self.threshold for d in all_dts], dtype=bool)
255
+ dt = [d for d in all_dts if d["score"] >= self.threshold]
256
+ if len(gt) == 0 and len(dt) == 0:
257
+ # This is a "true negative" case, where there are no GTs and no predictions
258
+ # The box-level metrics are ill-defined, so we don't add them to this dict
259
+ return {
260
+ "image_id": imgId,
261
+ "IL_TP": 0,
262
+ "IL_TN": 1,
263
+ "IL_FP": 0,
264
+ "IL_FN": 0,
265
+ "num_dt": len(dt),
266
+ }
267
+
268
+ if len(gt) > 0 and len(dt) == 0:
269
+ # This is a "false negative" case, where there are GTs but no predictions
270
+ return {
271
+ "image_id": imgId,
272
+ "IL_TP": 0,
273
+ "IL_TN": 0,
274
+ "IL_FP": 0,
275
+ "IL_FN": 1,
276
+ "TPs": np.zeros((len(p.iouThrs),), dtype=np.int64),
277
+ "FPs": np.zeros((len(p.iouThrs),), dtype=np.int64),
278
+ "FNs": np.ones((len(p.iouThrs),), dtype=np.int64) * len(gt),
279
+ "local_F1s": np.zeros((len(p.iouThrs),), dtype=np.int64),
280
+ "local_positive_F1s": np.zeros((len(p.iouThrs),), dtype=np.int64),
281
+ "num_dt": len(dt),
282
+ }
283
+
284
+ # Load pre-computed ious
285
+ ious = self.ious[(imgId, catId)]
286
+
287
+ # compute matching
288
+ if len(ious) == 0:
289
+ ious = np.zeros((len(dt), len(gt)))
290
+ else:
291
+ ious = ious[keep_dt, :][:, keep_gt]
292
+ assert ious.shape == (len(dt), len(gt))
293
+
294
+ matched_dt, matched_gt = linear_sum_assignment(-ious)
295
+
296
+ match_scores = ious[matched_dt, matched_gt]
297
+
298
+ TPs, FPs, FNs = [], [], []
299
+ IL_perfect = []
300
+ for thresh in p.iouThrs:
301
+ TP = (match_scores >= thresh).sum()
302
+ FP = len(dt) - TP
303
+ FN = len(gt) - TP
304
+ assert FP >= 0 and FN >= 0, (
305
+ f"FP: {FP}, FN: {FN}, TP: {TP}, match_scores: {match_scores}, len(dt): {len(dt)}, len(gt): {len(gt)}, ious: {ious}"
306
+ )
307
+ TPs.append(TP)
308
+ FPs.append(FP)
309
+ FNs.append(FN)
310
+
311
+ if FP == FN and FP == 0:
312
+ IL_perfect.append(1)
313
+ else:
314
+ IL_perfect.append(0)
315
+
316
+ TPs = np.array(TPs, dtype=np.int64)
317
+ FPs = np.array(FPs, dtype=np.int64)
318
+ FNs = np.array(FNs, dtype=np.int64)
319
+ IL_perfect = np.array(IL_perfect, dtype=np.int64)
320
+
321
+ # compute precision recall and F1
322
+ precision = TPs / (TPs + FPs + 1e-4)
323
+ assert np.all(precision <= 1)
324
+ recall = TPs / (TPs + FNs + 1e-4)
325
+ assert np.all(recall <= 1)
326
+ F1 = 2 * precision * recall / (precision + recall + 1e-4)
327
+
328
+ result = {
329
+ "image_id": imgId,
330
+ "TPs": TPs,
331
+ "FPs": FPs,
332
+ "FNs": FNs,
333
+ "local_F1s": F1,
334
+ "IL_TP": (len(gt) > 0) and (len(dt) > 0),
335
+ "IL_FP": (len(gt) == 0) and (len(dt) > 0),
336
+ "IL_TN": (len(gt) == 0) and (len(dt) == 0),
337
+ "IL_FN": (len(gt) > 0) and (len(dt) == 0),
338
+ "num_dt": len(dt),
339
+ }
340
+ if len(gt) > 0 and len(dt) > 0:
341
+ result["local_positive_F1s"] = F1
342
+ return result
343
+
344
+ def accumulate(self, p=None):
345
+ """
346
+ Accumulate per image evaluation results and store the result in self.eval
347
+ :param p: input params for evaluation
348
+ :return: None
349
+ """
350
+ if self.evalImgs is None or len(self.evalImgs) == 0:
351
+ print("Please run evaluate() first")
352
+ # allows input customized parameters
353
+ if p is None:
354
+ p = self.params
355
+
356
+ setImgIds = set(p.imgIds)
357
+
358
+ # TPs, FPs, FNs
359
+ TPs = np.zeros((len(p.iouThrs),), dtype=np.int64)
360
+ FPs = np.zeros((len(p.iouThrs),), dtype=np.int64)
361
+ pmFPs = np.zeros((len(p.iouThrs),), dtype=np.int64)
362
+ FNs = np.zeros((len(p.iouThrs),), dtype=np.int64)
363
+ local_F1s = np.zeros((len(p.iouThrs),), dtype=np.float64)
364
+
365
+ # Image level metrics
366
+ IL_TPs = 0
367
+ IL_FPs = 0
368
+ IL_TNs = 0
369
+ IL_FNs = 0
370
+
371
+ valid_img_count = 0
372
+ valid_F1_count = 0
373
+ evaledImgIds = set()
374
+ for res in self.evalImgs:
375
+ if res["image_id"] not in setImgIds:
376
+ continue
377
+ evaledImgIds.add(res["image_id"])
378
+ IL_TPs += res["IL_TP"]
379
+ IL_FPs += res["IL_FP"]
380
+ IL_TNs += res["IL_TN"]
381
+ IL_FNs += res["IL_FN"]
382
+
383
+ if "TPs" not in res:
384
+ continue
385
+
386
+ TPs += res["TPs"]
387
+ FPs += res["FPs"]
388
+ FNs += res["FNs"]
389
+ valid_img_count += 1
390
+
391
+ if "local_positive_F1s" in res:
392
+ local_F1s += res["local_positive_F1s"]
393
+ pmFPs += res["FPs"]
394
+ if res["num_dt"] > 0:
395
+ valid_F1_count += 1
396
+
397
+ assert len(setImgIds - evaledImgIds) == 0, (
398
+ f"{len(setImgIds - evaledImgIds)} images not evaluated. "
399
+ f"Here are the IDs of the first 3: {list(setImgIds - evaledImgIds)[:3]}"
400
+ )
401
+
402
+ # compute precision recall and F1
403
+ precision = TPs / (TPs + FPs + 1e-4)
404
+ positive_micro_precision = TPs / (TPs + pmFPs + 1e-4)
405
+ assert np.all(precision <= 1)
406
+ recall = TPs / (TPs + FNs + 1e-4)
407
+ assert np.all(recall <= 1)
408
+ F1 = 2 * precision * recall / (precision + recall + 1e-4)
409
+ positive_micro_F1 = (
410
+ 2
411
+ * positive_micro_precision
412
+ * recall
413
+ / (positive_micro_precision + recall + 1e-4)
414
+ )
415
+
416
+ IL_rec = IL_TPs / (IL_TPs + IL_FNs + 1e-6)
417
+ IL_prec = IL_TPs / (IL_TPs + IL_FPs + 1e-6)
418
+ IL_F1 = 2 * IL_prec * IL_rec / (IL_prec + IL_rec + 1e-6)
419
+ IL_FPR = IL_FPs / (IL_FPs + IL_TNs + 1e-6)
420
+ IL_MCC = float(IL_TPs * IL_TNs - IL_FPs * IL_FNs) / (
421
+ (
422
+ float(IL_TPs + IL_FPs)
423
+ * float(IL_TPs + IL_FNs)
424
+ * float(IL_TNs + IL_FPs)
425
+ * float(IL_TNs + IL_FNs)
426
+ )
427
+ ** 0.5
428
+ + 1e-6
429
+ )
430
+
431
+ self.eval = {
432
+ "params": p,
433
+ "TPs": TPs,
434
+ "FPs": FPs,
435
+ "positive_micro_FPs": pmFPs,
436
+ "FNs": FNs,
437
+ "precision": precision,
438
+ "positive_micro_precision": positive_micro_precision,
439
+ "recall": recall,
440
+ "F1": F1,
441
+ "positive_micro_F1": positive_micro_F1,
442
+ "positive_macro_F1": local_F1s / valid_F1_count,
443
+ "IL_recall": IL_rec,
444
+ "IL_precision": IL_prec,
445
+ "IL_F1": IL_F1,
446
+ "IL_FPR": IL_FPR,
447
+ "IL_MCC": IL_MCC,
448
+ }
449
+ self.eval["cgF1"] = self.eval["positive_micro_F1"] * self.eval["IL_MCC"]
450
+
451
+ def summarize(self):
452
+ """
453
+ Compute and display summary metrics for evaluation results.
454
+ """
455
+ if not self.eval:
456
+ raise Exception("Please run accumulate() first")
457
+
458
+ def _summarize(iouThr=None, metric=""):
459
+ p = self.params
460
+ iStr = " {:<18} @[ IoU={:<9}] = {:0.3f}"
461
+ titleStr = "Average " + metric
462
+ iouStr = (
463
+ "{:0.2f}:{:0.2f}".format(p.iouThrs[0], p.iouThrs[-1])
464
+ if iouThr is None
465
+ else "{:0.2f}".format(iouThr)
466
+ )
467
+
468
+ s = self.eval[metric]
469
+ # IoU
470
+ if iouThr is not None:
471
+ t = np.where(iouThr == p.iouThrs)[0]
472
+ s = s[t]
473
+
474
+ if len(s[s > -1]) == 0:
475
+ mean_s = -1
476
+ else:
477
+ mean_s = np.mean(s[s > -1])
478
+ print(iStr.format(titleStr, iouStr, mean_s))
479
+ return mean_s
480
+
481
+ def _summarize_single(metric=""):
482
+ titleStr = "Average " + metric
483
+ iStr = " {:<35} = {:0.3f}"
484
+ s = self.eval[metric]
485
+ print(iStr.format(titleStr, s))
486
+ return s
487
+
488
+ def _summarizeDets():
489
+ stats = []
490
+
491
+ for metric in CGF1_METRICS:
492
+ if metric.image_level:
493
+ stats.append(_summarize_single(metric=metric.name))
494
+ else:
495
+ stats.append(
496
+ _summarize(iouThr=metric.iou_threshold, metric=metric.name)
497
+ )
498
+ return np.asarray(stats)
499
+
500
+ summarize = _summarizeDets
501
+ self.stats = summarize()
502
+
503
+
504
+ def _evaluate(self):
505
+ """
506
+ Run per image evaluation on given images and store results (a list of dict) in self.evalImgs
507
+ """
508
+ p = self.params
509
+ # add backward compatibility if useSegm is specified in params
510
+ p.imgIds = list(np.unique(p.imgIds))
511
+ p.useCats = False
512
+ p.maxDets = sorted(p.maxDets)
513
+ self.params = p
514
+
515
+ self._prepare()
516
+ # loop through images, area range, max detection number
517
+ catIds = [-1]
518
+
519
+ if p.iouType == "segm" or p.iouType == "bbox":
520
+ computeIoU = self.computeIoU
521
+ else:
522
+ raise RuntimeError(f"Unsupported iou {p.iouType}")
523
+ self.ious = {
524
+ (imgId, catId): computeIoU(imgId, catId)
525
+ for imgId in p.imgIds
526
+ for catId in catIds
527
+ }
528
+
529
+ maxDet = p.maxDets[-1]
530
+ evalImgs = [
531
+ self.evaluateImg(imgId, catId, areaRng, maxDet)
532
+ for catId in catIds
533
+ for areaRng in p.areaRng
534
+ for imgId in p.imgIds
535
+ ]
536
+ # this is NOT in the pycocotools code, but could be done outside
537
+ evalImgs = np.asarray(evalImgs).reshape(len(catIds), len(p.areaRng), len(p.imgIds))
538
+ return p.imgIds, evalImgs
539
+
540
+
541
+ class CGF1Evaluator:
542
+ """
543
+ Wrapper class for cgF1 evaluation.
544
+ This supports the oracle setting (when several ground-truths are available per image)
545
+ """
546
+
547
+ def __init__(
548
+ self,
549
+ gt_path: Union[str, List[str]],
550
+ iou_type="segm",
551
+ verbose=False,
552
+ ):
553
+ """
554
+ Args:
555
+ gt_path (str or list of str): path(s) to ground truth COCO json file(s)
556
+ iou_type (str): type of IoU to evaluate
557
+ threshold (float): threshold for predictions
558
+ """
559
+ self.gt_paths = gt_path if isinstance(gt_path, list) else [gt_path]
560
+ self.iou_type = iou_type
561
+
562
+ self.coco_gts = [COCOCustom(gt) for gt in self.gt_paths]
563
+
564
+ self.verbose = verbose
565
+
566
+ self.coco_evals = []
567
+ for i, coco_gt in enumerate(self.coco_gts):
568
+ self.coco_evals.append(
569
+ CGF1Eval(
570
+ coco_gt=coco_gt,
571
+ iouType=iou_type,
572
+ )
573
+ )
574
+ self.coco_evals[i].useCats = False
575
+
576
+ exclude_img_ids = set()
577
+ # exclude_img_ids are the ids that are not exhaustively annotated in any of the other gts
578
+ for coco_gt in self.coco_gts[1:]:
579
+ exclude_img_ids = exclude_img_ids.union(
580
+ {
581
+ img["id"]
582
+ for img in coco_gt.dataset["images"]
583
+ if not img["is_instance_exhaustive"]
584
+ }
585
+ )
586
+ # we only eval on instance exhaustive queries
587
+ self.eval_img_ids = [
588
+ img["id"]
589
+ for img in self.coco_gts[0].dataset["images"]
590
+ if (img["is_instance_exhaustive"] and img["id"] not in exclude_img_ids)
591
+ ]
592
+
593
+ def evaluate(self, pred_file: str):
594
+ """
595
+ Evaluate the detections using cgF1 metric.
596
+
597
+ Args:
598
+ pred_file: path to the predictions COCO json file
599
+
600
+ """
601
+ assert len(self.coco_gts) > 0, "No ground truth provided for evaluation."
602
+ assert len(self.coco_gts) == len(self.coco_evals), (
603
+ "Mismatch in number of ground truths and evaluators."
604
+ )
605
+
606
+ if self.verbose:
607
+ print(f"Loading predictions from {pred_file}")
608
+
609
+ with open(pred_file, "r") as f:
610
+ preds = json.load(f)
611
+
612
+ if self.verbose:
613
+ print(f"Loaded {len(preds)} predictions")
614
+
615
+ img2preds = defaultdict(list)
616
+ for pred in preds:
617
+ img2preds[pred["image_id"]].append(pred)
618
+
619
+ all_eval_imgs = []
620
+ for img_id in tqdm(self.eval_img_ids, disable=not self.verbose):
621
+ results = img2preds[img_id]
622
+ all_scorings = []
623
+ for cur_coco_gt, coco_eval in zip(self.coco_gts, self.coco_evals):
624
+ # suppress pycocotools prints
625
+ with open(os.devnull, "w") as devnull:
626
+ with contextlib.redirect_stdout(devnull):
627
+ coco_dt = (
628
+ cur_coco_gt.loadRes(results) if results else COCOCustom()
629
+ )
630
+
631
+ coco_eval.cocoDt = coco_dt
632
+ coco_eval.params.imgIds = [img_id]
633
+ coco_eval.params.useCats = False
634
+ img_ids, eval_imgs = _evaluate(coco_eval)
635
+ all_scorings.append(eval_imgs)
636
+ selected = self._select_best_scoring(all_scorings)
637
+ all_eval_imgs.append(selected)
638
+
639
+ # After this point, we have selected the best scoring per image among several ground truths
640
+ # we can now accumulate and summarize, using only the first coco_eval
641
+
642
+ self.coco_evals[0].evalImgs = list(
643
+ np.concatenate(all_eval_imgs, axis=2).flatten()
644
+ )
645
+ self.coco_evals[0].params.imgIds = self.eval_img_ids
646
+ self.coco_evals[0]._paramsEval = copy.deepcopy(self.coco_evals[0].params)
647
+
648
+ if self.verbose:
649
+ print(f"Accumulating results")
650
+ self.coco_evals[0].accumulate()
651
+ print("cgF1 metric, IoU type={}".format(self.iou_type))
652
+ self.coco_evals[0].summarize()
653
+ print()
654
+
655
+ out = {}
656
+ for i, value in enumerate(self.coco_evals[0].stats):
657
+ name = CGF1_METRICS[i].name
658
+ if CGF1_METRICS[i].iou_threshold is not None:
659
+ name = f"{name}@{CGF1_METRICS[i].iou_threshold}"
660
+ out[f"cgF1_eval_{self.iou_type}_{name}"] = float(value)
661
+
662
+ return out
663
+
664
+ @staticmethod
665
+ def _select_best_scoring(scorings):
666
+ # This function is used for "oracle" type evaluation.
667
+ # It accepts the evaluation results with respect to several ground truths, and picks the best
668
+ if len(scorings) == 1:
669
+ return scorings[0]
670
+
671
+ assert scorings[0].ndim == 3, (
672
+ f"Expecting results in [numCats, numAreas, numImgs] format, got {scorings[0].shape}"
673
+ )
674
+ assert scorings[0].shape[0] == 1, (
675
+ f"Expecting a single category, got {scorings[0].shape[0]}"
676
+ )
677
+
678
+ for scoring in scorings:
679
+ assert scoring.shape == scorings[0].shape, (
680
+ f"Shape mismatch: {scoring.shape}, {scorings[0].shape}"
681
+ )
682
+
683
+ selected_imgs = []
684
+ for img_id in range(scorings[0].shape[-1]):
685
+ best = scorings[0][:, :, img_id]
686
+
687
+ for scoring in scorings[1:]:
688
+ current = scoring[:, :, img_id]
689
+ if "local_F1s" in best[0, 0] and "local_F1s" in current[0, 0]:
690
+ # we were able to compute a F1 score for this particular image in both evaluations
691
+ # best["local_F1s"] contains the results at various IoU thresholds. We simply take the average for comparision
692
+ best_score = best[0, 0]["local_F1s"].mean()
693
+ current_score = current[0, 0]["local_F1s"].mean()
694
+ if current_score > best_score:
695
+ best = current
696
+
697
+ else:
698
+ # If we're here, it means that in that in some evaluation we were not able to get a valid local F1
699
+ # This happens when both the predictions and targets are empty. In that case, we can assume it's a perfect prediction
700
+ if "local_F1s" not in current[0, 0]:
701
+ best = current
702
+ selected_imgs.append(best)
703
+ result = np.stack(selected_imgs, axis=-1)
704
+ assert result.shape == scorings[0].shape
705
+ return result
third_party/GraspGen/sam3/sam3/eval/coco_eval.py ADDED
@@ -0,0 +1,914 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ """
6
+ COCO evaluator that works in distributed mode.
7
+
8
+ Mostly copy-paste from https://github.com/pytorch/vision/blob/edfd5a7/references/detection/coco_eval.py
9
+ The difference is that there is less copy-pasting from pycocotools
10
+ in the end of the file, as python3 can suppress prints with contextlib
11
+ """
12
+
13
+ import contextlib
14
+ import copy
15
+ import json
16
+ import logging
17
+ import os
18
+ import pickle
19
+ from collections import defaultdict
20
+ from pathlib import Path
21
+ from typing import Any, List, Optional
22
+
23
+ import numpy as np
24
+ import pycocotools.mask as mask_utils
25
+ import torch
26
+ from iopath.common.file_io import g_pathmgr
27
+ from pycocotools.coco import COCO
28
+ from pycocotools.cocoeval import COCOeval
29
+ from sam3.train.masks_ops import rle_encode
30
+ from sam3.train.utils.distributed import (
31
+ all_gather,
32
+ gather_to_rank_0_via_filesys,
33
+ get_rank,
34
+ is_main_process,
35
+ )
36
+
37
+ RARITY_BUCKETS = {0: "frequent", 1: "common", 2: "medium", 3: "rare"}
38
+
39
+
40
+ class CocoEvaluator:
41
+ def __init__(
42
+ self,
43
+ coco_gt,
44
+ iou_types: List[str],
45
+ useCats: bool,
46
+ dump_dir: Optional[str],
47
+ postprocessor,
48
+ average_by_rarity=False,
49
+ metrics_dump_dir: Optional[str] = None,
50
+ gather_pred_via_filesys=False,
51
+ use_normalized_areas=True,
52
+ maxdets=[1, 10, 100],
53
+ exhaustive_only=False,
54
+ all_exhaustive_only=True,
55
+ ):
56
+ """Online coco evaluator. It will evaluate images as they are generated by the model, then accumulate/summarize at the end
57
+
58
+ Args:
59
+ - coco_gt: COCO api object containing the gt
60
+ - iou_types: can be either "bbox" or "segm"
61
+ - useCats: If true, categories will be used for evaluation
62
+ - dump_dir: if non null, then the predictions will be dumped in that directory
63
+ - postprocessor: Module to convert the model's output into the coco format
64
+ - average_by_rarity: if true then we expect the images information in the gt dataset
65
+ to have a "rarity" field. Then the AP will be computed on all rarity buckets
66
+ individually, then averaged
67
+ - gather_pred_via_filesys: if true, we use the filesystem for collective gathers
68
+ - use_normalized_areas: if true, the areas of the objects in the GT are assumed to be
69
+ normalized by the area of the image. In that case, the size buckets are adjusted
70
+ - maxdets: maximal number of detections to be evaluated on each image.
71
+ - exhaustive_only: If true, we restrict eval only to exhaustive annotations
72
+ - all_exhaustive_only: If true, datapoints are restricted only to those with all exhaustive annotations
73
+
74
+ """
75
+ # coco_gt = copy.deepcopy(coco_gt)
76
+ self.coco_gts = [coco_gt] if not isinstance(coco_gt, list) else coco_gt
77
+ assert len(maxdets) == 3, f"expecting 3 detection threshold, got {len(maxdets)}"
78
+
79
+ self.use_normalized_areas = use_normalized_areas
80
+ self.iou_types = iou_types
81
+ self.useCats = useCats
82
+ self.maxdets = maxdets
83
+ self.dump = None
84
+ self.dump_dir = dump_dir
85
+ if self.dump_dir is not None:
86
+ self.dump = []
87
+ if is_main_process():
88
+ if not os.path.exists(self.dump_dir):
89
+ os.makedirs(self.dump_dir, exist_ok=True)
90
+ logging.info(f"Create the folder: {dump_dir}")
91
+
92
+ self.initialized = False
93
+
94
+ # Whether to gather predictions through filesystem (instead of torch
95
+ # collective ops; requiring a shared filesystem across all ranks)
96
+ self.gather_pred_via_filesys = gather_pred_via_filesys
97
+ self.use_self_evaluate = True # CPP version is disabled
98
+ self.postprocessor = postprocessor
99
+ self.average_by_rarity = average_by_rarity
100
+ self.exhaustive_only = exhaustive_only
101
+ self.all_exhaustive_only = all_exhaustive_only
102
+ self.metrics_dump_dir = metrics_dump_dir
103
+ if self.metrics_dump_dir is not None:
104
+ if is_main_process():
105
+ if not os.path.exists(self.metrics_dump_dir):
106
+ os.makedirs(self.metrics_dump_dir, exist_ok=True)
107
+ logging.info(f"Create the folder: {metrics_dump_dir}")
108
+
109
+ def _lazy_init(self, coco_cls=COCO):
110
+ if self.initialized:
111
+ return
112
+
113
+ self.initialized = True
114
+
115
+ self.coco_gts = [
116
+ coco_cls(g_pathmgr.get_local_path(gt)) if isinstance(gt, str) else gt
117
+ for gt in self.coco_gts
118
+ ]
119
+
120
+ self.reset()
121
+
122
+ self.eval_img_ids = None
123
+
124
+ if self.exhaustive_only:
125
+ exclude_img_ids = set()
126
+ # exclude_img_ids are the ids that are not exhaustively annotated in any of the other gts
127
+ if self.all_exhaustive_only:
128
+ for coco_gt in self.coco_gts[1:]:
129
+ exclude_img_ids = exclude_img_ids.union(
130
+ {
131
+ img["id"]
132
+ for img in coco_gt.dataset["images"]
133
+ if not img["is_instance_exhaustive"]
134
+ }
135
+ )
136
+ # we only eval on instance exhaustive queries
137
+ self.eval_img_ids = [
138
+ img["id"]
139
+ for img in self.coco_gts[0].dataset["images"]
140
+ if (img["is_instance_exhaustive"] and img["id"] not in exclude_img_ids)
141
+ ]
142
+
143
+ self.rarity_buckets = None
144
+ if self.average_by_rarity:
145
+ self.rarity_buckets = defaultdict(list)
146
+ eval_img_ids_set = (
147
+ set(self.eval_img_ids) if self.eval_img_ids is not None else None
148
+ )
149
+ for img in self.coco_gts[0].dataset["images"]:
150
+ if self.eval_img_ids is not None and img["id"] not in eval_img_ids_set:
151
+ continue
152
+ self.rarity_buckets[img["rarity"]].append(img["id"])
153
+ print("Rarity buckets sizes:")
154
+ for k, v in self.rarity_buckets.items():
155
+ print(f"{k}: {len(v)}")
156
+
157
+ def set_sync_device(self, device: torch.device) -> Any:
158
+ self._sync_device = device
159
+
160
+ def _evaluate(self, *args, **kwargs):
161
+ return evaluate(*args, **kwargs)
162
+
163
+ def _loadRes(self, *args, **kwargs):
164
+ return loadRes(*args, **kwargs)
165
+
166
+ def update(self, *args, **kwargs):
167
+ self._lazy_init()
168
+ predictions = self.postprocessor.process_results(*args, **kwargs)
169
+
170
+ img_ids = list(np.unique(list(predictions.keys())))
171
+ self.img_ids.extend(img_ids)
172
+
173
+ for iou_type in self.iou_types:
174
+ results = self.prepare(predictions, iou_type)
175
+ self._dump(results)
176
+
177
+ assert len(self.coco_gts) == len(self.coco_evals)
178
+ all_scorings = []
179
+ for cur_coco_gt, cur_coco_eval in zip(self.coco_gts, self.coco_evals):
180
+ # suppress pycocotools prints
181
+ with open(os.devnull, "w") as devnull:
182
+ with contextlib.redirect_stdout(devnull):
183
+ coco_dt = (
184
+ self._loadRes(cur_coco_gt, results) if results else COCO()
185
+ )
186
+
187
+ coco_eval = cur_coco_eval[iou_type]
188
+
189
+ coco_eval.cocoDt = coco_dt
190
+ coco_eval.params.imgIds = list(img_ids)
191
+ coco_eval.params.useCats = self.useCats
192
+ coco_eval.params.maxDets = self.maxdets
193
+ img_ids, eval_imgs = self._evaluate(coco_eval, self.use_self_evaluate)
194
+ all_scorings.append(eval_imgs)
195
+
196
+ selected = self.select_best_scoring(all_scorings)
197
+ self.eval_imgs[iou_type].append(selected)
198
+
199
+ def select_best_scoring(self, scorings):
200
+ # This function is used for "oracle" type evaluation.
201
+ # It accepts the evaluation results with respect to several ground truths, and picks the best
202
+ if len(scorings) == 1:
203
+ return scorings[0]
204
+
205
+ # Currently we don't support Oracle Phrase AP.
206
+ # To implement it, we likely need to modify the cpp code since the eval_image type is opaque
207
+ raise RuntimeError("Not implemented")
208
+
209
+ def _dump(self, results):
210
+ if self.dump is not None:
211
+ dumped_results = copy.deepcopy(results)
212
+ for r in dumped_results:
213
+ if "bbox" not in self.iou_types and "bbox" in r:
214
+ del r["bbox"]
215
+ elif "bbox" in r:
216
+ r["bbox"] = [round(coord, 5) for coord in r["bbox"]]
217
+ r["score"] = round(r["score"], 5)
218
+ self.dump.extend(dumped_results)
219
+
220
+ def synchronize_between_processes(self):
221
+ self._lazy_init()
222
+ logging.info("Coco evaluator: Synchronizing between processes")
223
+ for iou_type in self.iou_types:
224
+ if len(self.eval_imgs[iou_type]) > 0:
225
+ self.eval_imgs[iou_type] = np.concatenate(self.eval_imgs[iou_type], 2)
226
+ else:
227
+ num_areas = len(self.coco_evals[0][iou_type].params.areaRng)
228
+ # assuming 1 class
229
+ assert not self.useCats
230
+ self.eval_imgs[iou_type] = np.empty((1, num_areas, 0))
231
+ create_common_coco_eval(
232
+ self.coco_evals[0][iou_type],
233
+ self.img_ids,
234
+ self.eval_imgs[iou_type],
235
+ use_self_evaluate=self.use_self_evaluate,
236
+ gather_pred_via_filesys=self.gather_pred_via_filesys,
237
+ metrics_dump_dir=self.metrics_dump_dir,
238
+ )
239
+ if self.dump is not None:
240
+ dumped_file = Path(self.dump_dir) / f"coco_predictions_{get_rank()}.json"
241
+ logging.info(f"COCO evaluator: Dumping local predictions to {dumped_file}")
242
+ with g_pathmgr.open(str(dumped_file), "w") as f:
243
+ json.dump(self.dump, f)
244
+
245
+ # if self.gather_pred_via_filesys:
246
+ # dump = gather_to_rank_0_via_filesys(self.dump)
247
+ # else:
248
+ # dump = all_gather(self.dump, force_cpu=True)
249
+ # self.dump = sum(dump, [])
250
+
251
+ def accumulate(self, imgIds=None):
252
+ self._lazy_init()
253
+ logging.info(
254
+ f"Coco evaluator: Accumulating on {len(imgIds) if imgIds is not None else 'all'} images"
255
+ )
256
+ if not is_main_process():
257
+ return
258
+
259
+ if imgIds is None:
260
+ for coco_eval in self.coco_evals[0].values():
261
+ accumulate(coco_eval, use_self_eval=self.use_self_evaluate)
262
+
263
+ if imgIds is not None:
264
+ imgIds = set(imgIds)
265
+ for coco_eval in self.coco_evals[0].values():
266
+ p = coco_eval.params
267
+ id_mask = np.array([(i in imgIds) for i in p.imgIds], dtype=bool)
268
+ old_img_ids = p.imgIds
269
+ coco_eval.params.imgIds = np.asarray(p.imgIds)[id_mask]
270
+ old_img_evals = coco_eval.evalImgs
271
+ catIds = p.catIds if p.useCats else [-1]
272
+ coco_eval.evalImgs = list(
273
+ np.asarray(coco_eval.evalImgs)
274
+ .reshape(len(catIds), len(p.areaRng), len(old_img_ids))[
275
+ ..., id_mask
276
+ ]
277
+ .flatten()
278
+ )
279
+ accumulate(coco_eval, use_self_eval=self.use_self_evaluate)
280
+ coco_eval.evalImgs = old_img_evals
281
+ coco_eval.params.imgIds = old_img_ids
282
+
283
+ def summarize(self):
284
+ self._lazy_init()
285
+ logging.info("Coco evaluator: Summarizing")
286
+ if not is_main_process():
287
+ return {}
288
+
289
+ outs = {}
290
+ if self.rarity_buckets is None:
291
+ self.accumulate(self.eval_img_ids)
292
+ for iou_type, coco_eval in self.coco_evals[0].items():
293
+ print("IoU metric: {}".format(iou_type))
294
+ summarize(coco_eval)
295
+
296
+ if "bbox" in self.coco_evals[0]:
297
+ for key, value in zip(*self.coco_evals[0]["bbox"].stats):
298
+ outs[f"coco_eval_bbox_{key}"] = value
299
+ if "segm" in self.coco_evals[0]:
300
+ for key, value in zip(*self.coco_evals[0]["segm"].stats):
301
+ outs[f"coco_eval_masks_{key}"] = value
302
+ else:
303
+ total_stats = {}
304
+ all_keys = {}
305
+ for bucket, img_list in self.rarity_buckets.items():
306
+ self.accumulate(imgIds=img_list)
307
+ bucket_name = RARITY_BUCKETS[bucket]
308
+ for iou_type, coco_eval in self.coco_evals[0].items():
309
+ print(f"IoU metric: {iou_type}. Rarity bucket: {bucket_name}")
310
+ summarize(coco_eval)
311
+
312
+ if "bbox" in self.coco_evals[0]:
313
+ if "bbox" not in total_stats:
314
+ total_stats["bbox"] = np.zeros_like(
315
+ self.coco_evals[0]["bbox"].stats[1]
316
+ )
317
+ all_keys["bbox"] = self.coco_evals[0]["bbox"].stats[0]
318
+ total_stats["bbox"] += self.coco_evals[0]["bbox"].stats[1]
319
+ for key, value in zip(*self.coco_evals[0]["bbox"].stats):
320
+ outs[f"coco_eval_bbox_{bucket_name}_{key}"] = value
321
+ if "segm" in self.coco_evals[0]:
322
+ if "segm" not in total_stats:
323
+ total_stats["segm"] = np.zeros_like(
324
+ self.coco_evals[0]["segm"].stats[1]
325
+ )
326
+ all_keys["segm"] = self.coco_evals[0]["segm"].stats[0]
327
+ total_stats["segm"] += self.coco_evals[0]["segm"].stats[1]
328
+ for key, value in zip(*self.coco_evals[0]["segm"].stats):
329
+ outs[f"coco_eval_masks_{bucket_name}_{key}"] = value
330
+
331
+ if "bbox" in total_stats:
332
+ total_stats["bbox"] /= len(self.rarity_buckets)
333
+ for key, value in zip(all_keys["bbox"], total_stats["bbox"]):
334
+ outs[f"coco_eval_bbox_{key}"] = value
335
+ if "segm" in total_stats:
336
+ total_stats["segm"] /= len(self.rarity_buckets)
337
+ for key, value in zip(all_keys["segm"], total_stats["segm"]):
338
+ outs[f"coco_eval_masks_{key}"] = value
339
+
340
+ # if self.dump is not None:
341
+ # assert self.dump_dir is not None
342
+ # logging.info("Coco evaluator: Dumping the global result file to disk")
343
+ # with g_pathmgr.open(str(Path(self.dump_dir) / "coco_eval.json"), "w") as f:
344
+ # json.dump(self.dump, f)
345
+ return outs
346
+
347
+ def compute_synced(self):
348
+ self._lazy_init()
349
+ self.synchronize_between_processes()
350
+ return self.summarize()
351
+
352
+ def compute(self):
353
+ self._lazy_init()
354
+ return {"": 0.0}
355
+
356
+ def reset(self, cocoeval_cls=COCOeval):
357
+ self.coco_evals = [{} for _ in range(len(self.coco_gts))]
358
+ for i, coco_gt in enumerate(self.coco_gts):
359
+ for iou_type in self.iou_types:
360
+ self.coco_evals[i][iou_type] = cocoeval_cls(coco_gt, iouType=iou_type)
361
+ self.coco_evals[i][iou_type].params.useCats = self.useCats
362
+ self.coco_evals[i][iou_type].params.maxDets = self.maxdets
363
+ if self.use_normalized_areas:
364
+ self.coco_evals[i][iou_type].params.areaRng = [
365
+ [0, 1e5],
366
+ [0, 0.001],
367
+ [0.001, 0.01],
368
+ [0.01, 0.1],
369
+ [0.1, 0.5],
370
+ [0.5, 0.95],
371
+ [0.95, 1e5],
372
+ ]
373
+ self.coco_evals[i][iou_type].params.areaRngLbl = [
374
+ "all",
375
+ "tiny",
376
+ "small",
377
+ "medium",
378
+ "large",
379
+ "huge",
380
+ "whole_image",
381
+ ]
382
+
383
+ self.img_ids = []
384
+ self.eval_imgs = {k: [] for k in self.iou_types}
385
+ if self.dump is not None:
386
+ self.dump = []
387
+
388
+ def write(self, stats):
389
+ self._lazy_init()
390
+ """Write the results in the stats dict"""
391
+ if "bbox" in self.coco_evals[0]:
392
+ stats["coco_eval_bbox"] = self.coco_evals[0]["bbox"].stats.tolist()
393
+ if "segm" in self.coco_evals[0]:
394
+ stats["coco_eval_masks"] = self.coco_evals[0]["segm"].stats.tolist()
395
+ return stats
396
+
397
+ def prepare(self, predictions, iou_type):
398
+ self._lazy_init()
399
+ if iou_type == "bbox":
400
+ return self.prepare_for_coco_detection(predictions)
401
+ elif iou_type == "segm":
402
+ return self.prepare_for_coco_segmentation(predictions)
403
+ elif iou_type == "keypoints":
404
+ return self.prepare_for_coco_keypoint(predictions)
405
+ else:
406
+ raise ValueError("Unknown iou type {}".format(iou_type))
407
+
408
+ def prepare_for_coco_detection(self, predictions):
409
+ self._lazy_init()
410
+ coco_results = []
411
+ for original_id, prediction in predictions.items():
412
+ if len(prediction) == 0:
413
+ continue
414
+
415
+ boxes = prediction["boxes"]
416
+ boxes = convert_to_xywh(boxes).tolist()
417
+ scores = prediction["scores"].tolist()
418
+ labels = prediction["labels"].tolist()
419
+
420
+ coco_results.extend(
421
+ [
422
+ {
423
+ "image_id": original_id,
424
+ "category_id": labels[k],
425
+ "bbox": box,
426
+ "score": scores[k],
427
+ }
428
+ for k, box in enumerate(boxes)
429
+ ]
430
+ )
431
+ return coco_results
432
+
433
+ @torch.no_grad()
434
+ def prepare_for_coco_segmentation(self, predictions):
435
+ self._lazy_init()
436
+ coco_results = []
437
+ for original_id, prediction in predictions.items():
438
+ if len(prediction) == 0:
439
+ continue
440
+
441
+ scores = prediction["scores"].tolist()
442
+ labels = prediction["labels"].tolist()
443
+ boundaries, dilated_boundaries = None, None
444
+ if "boundaries" in prediction:
445
+ boundaries = prediction["boundaries"]
446
+ dilated_boundaries = prediction["dilated_boundaries"]
447
+ assert dilated_boundaries is not None
448
+ assert len(scores) == len(boundaries)
449
+
450
+ if "masks_rle" in prediction:
451
+ rles = prediction["masks_rle"]
452
+ areas = []
453
+ for rle in rles:
454
+ cur_area = mask_utils.area(rle)
455
+ h, w = rle["size"]
456
+ areas.append(cur_area / (h * w))
457
+ else:
458
+ masks = prediction["masks"]
459
+
460
+ masks = masks > 0.5
461
+ h, w = masks.shape[-2:]
462
+
463
+ areas = masks.flatten(1).sum(1) / (h * w)
464
+ areas = areas.tolist()
465
+
466
+ rles = rle_encode(masks.squeeze(1))
467
+
468
+ # memory clean
469
+ del masks
470
+ del prediction["masks"]
471
+
472
+ assert len(areas) == len(rles) == len(scores)
473
+ for k, rle in enumerate(rles):
474
+ payload = {
475
+ "image_id": original_id,
476
+ "category_id": labels[k],
477
+ "segmentation": rle,
478
+ "score": scores[k],
479
+ "area": areas[k],
480
+ }
481
+ if boundaries is not None:
482
+ payload["boundary"] = boundaries[k]
483
+ payload["dilated_boundary"] = dilated_boundaries[k]
484
+
485
+ coco_results.append(payload)
486
+
487
+ return coco_results
488
+
489
+ def prepare_for_coco_keypoint(self, predictions):
490
+ self._lazy_init()
491
+ coco_results = []
492
+ for original_id, prediction in predictions.items():
493
+ if len(prediction) == 0:
494
+ continue
495
+
496
+ boxes = prediction["boxes"]
497
+ boxes = convert_to_xywh(boxes).tolist()
498
+ scores = prediction["scores"].tolist()
499
+ labels = prediction["labels"].tolist()
500
+ keypoints = prediction["keypoints"]
501
+ keypoints = keypoints.flatten(start_dim=1).tolist()
502
+
503
+ coco_results.extend(
504
+ [
505
+ {
506
+ "image_id": original_id,
507
+ "category_id": labels[k],
508
+ "keypoints": keypoint,
509
+ "score": scores[k],
510
+ }
511
+ for k, keypoint in enumerate(keypoints)
512
+ ]
513
+ )
514
+ return coco_results
515
+
516
+
517
+ def convert_to_xywh(boxes):
518
+ xmin, ymin, xmax, ymax = boxes.unbind(-1)
519
+ return torch.stack((xmin, ymin, xmax - xmin, ymax - ymin), dim=-1)
520
+
521
+
522
+ def merge(img_ids, eval_imgs, gather_pred_via_filesys=False):
523
+ if gather_pred_via_filesys:
524
+ # only gather the predictions to rank 0 (other ranks will receive empty
525
+ # lists for `all_img_ids` and `all_eval_imgs`, which should be OK as
526
+ # merging and evaluation are only done on rank 0)
527
+ all_img_ids = gather_to_rank_0_via_filesys(img_ids)
528
+ all_eval_imgs = gather_to_rank_0_via_filesys(eval_imgs)
529
+ else:
530
+ all_img_ids = all_gather(img_ids, force_cpu=True)
531
+ all_eval_imgs = all_gather(eval_imgs, force_cpu=True)
532
+ if not is_main_process():
533
+ return None, None
534
+
535
+ merged_img_ids = []
536
+ for p in all_img_ids:
537
+ merged_img_ids.extend(p)
538
+
539
+ merged_eval_imgs = []
540
+ for p in all_eval_imgs:
541
+ merged_eval_imgs.append(p)
542
+
543
+ merged_img_ids = np.array(merged_img_ids)
544
+ merged_eval_imgs = np.concatenate(merged_eval_imgs, 2)
545
+
546
+ # keep only unique (and in sorted order) images
547
+ merged_img_ids, idx = np.unique(merged_img_ids, return_index=True)
548
+ merged_eval_imgs = merged_eval_imgs[..., idx]
549
+
550
+ return merged_img_ids, merged_eval_imgs
551
+
552
+
553
+ def create_common_coco_eval(
554
+ coco_eval,
555
+ img_ids,
556
+ eval_imgs,
557
+ use_self_evaluate,
558
+ gather_pred_via_filesys=False,
559
+ metrics_dump_dir=None,
560
+ ):
561
+ img_ids, eval_imgs = merge(img_ids, eval_imgs, gather_pred_via_filesys)
562
+ if not is_main_process():
563
+ return
564
+ if metrics_dump_dir is not None:
565
+ dumped_file = (
566
+ Path(metrics_dump_dir) / f"coco_eval_img_metrics_{get_rank()}.json"
567
+ )
568
+ logging.info(f"COCO evaluator: Dumping local predictions to {dumped_file}")
569
+ with g_pathmgr.open(str(dumped_file), "w") as f:
570
+ json.dump(eval_imgs.squeeze(), f, default=lambda x: x.tolist())
571
+ img_ids = list(img_ids)
572
+
573
+ # If some images were not predicted, we need to create dummy detections for them
574
+ missing_img_ids = set(coco_eval.cocoGt.getImgIds()) - set(img_ids)
575
+ if len(missing_img_ids) > 0:
576
+ print(f"WARNING: {len(missing_img_ids)} images were not predicted!")
577
+ coco_eval.cocoDt = COCO()
578
+ coco_eval.params.imgIds = list(missing_img_ids)
579
+ new_img_ids, new_eval_imgs = evaluate(coco_eval, use_self_evaluate)
580
+ img_ids.extend(new_img_ids)
581
+ eval_imgs = np.concatenate((eval_imgs, new_eval_imgs), axis=2)
582
+
583
+ eval_imgs = list(eval_imgs.flatten())
584
+ assert len(img_ids) == len(coco_eval.cocoGt.getImgIds())
585
+
586
+ coco_eval.evalImgs = eval_imgs
587
+ coco_eval.params.imgIds = img_ids
588
+ coco_eval._paramsEval = copy.deepcopy(coco_eval.params)
589
+
590
+
591
+ #################################################################
592
+ # From pycocotools, just removed the prints and fixed
593
+ # a Python3 bug about unicode not defined
594
+ #################################################################
595
+
596
+
597
+ # Copy of COCO prepare, but doesn't convert anntoRLE
598
+ def segmentation_prepare(self):
599
+ """
600
+ Prepare ._gts and ._dts for evaluation based on params
601
+ :return: None
602
+ """
603
+ p = self.params
604
+ if p.useCats:
605
+ gts = self.cocoGt.loadAnns(
606
+ self.cocoGt.getAnnIds(imgIds=p.imgIds, catIds=p.catIds)
607
+ )
608
+ dts = self.cocoDt.loadAnns(
609
+ self.cocoDt.getAnnIds(imgIds=p.imgIds, catIds=p.catIds)
610
+ )
611
+ else:
612
+ gts = self.cocoGt.loadAnns(self.cocoGt.getAnnIds(imgIds=p.imgIds))
613
+ dts = self.cocoDt.loadAnns(self.cocoDt.getAnnIds(imgIds=p.imgIds))
614
+
615
+ for gt in gts:
616
+ gt["ignore"] = gt["ignore"] if "ignore" in gt else 0
617
+ gt["ignore"] = "iscrowd" in gt and gt["iscrowd"]
618
+ if p.iouType == "keypoints":
619
+ gt["ignore"] = (gt["num_keypoints"] == 0) or gt["ignore"]
620
+ self._gts = defaultdict(list) # gt for evaluation
621
+ self._dts = defaultdict(list) # dt for evaluation
622
+ for gt in gts:
623
+ self._gts[gt["image_id"], gt["category_id"]].append(gt)
624
+ for dt in dts:
625
+ self._dts[dt["image_id"], dt["category_id"]].append(dt)
626
+ self.evalImgs = defaultdict(list) # per-image per-category evaluation results
627
+ self.eval = {} # accumulated evaluation results
628
+
629
+
630
+ def evaluate(self, use_self_evaluate):
631
+ """
632
+ Run per image evaluation on given images and store results (a list of dict) in self.evalImgs
633
+ :return: None
634
+ """
635
+ # tic = time.time()
636
+ # print('Running per image evaluation...', use_self_evaluate)
637
+ p = self.params
638
+ # add backward compatibility if useSegm is specified in params
639
+ if p.useSegm is not None:
640
+ p.iouType = "segm" if p.useSegm == 1 else "bbox"
641
+ print(
642
+ "useSegm (deprecated) is not None. Running {} evaluation".format(p.iouType)
643
+ )
644
+ # print('Evaluate annotation type *{}*'.format(p.iouType))
645
+ p.imgIds = list(np.unique(p.imgIds))
646
+ if p.useCats:
647
+ p.catIds = list(np.unique(p.catIds))
648
+ p.maxDets = sorted(p.maxDets)
649
+ self.params = p
650
+
651
+ self._prepare()
652
+ # loop through images, area range, max detection number
653
+ catIds = p.catIds if p.useCats else [-1]
654
+
655
+ if p.iouType == "segm" or p.iouType == "bbox":
656
+ computeIoU = self.computeIoU
657
+ elif p.iouType == "keypoints":
658
+ computeIoU = self.computeOks
659
+ self.ious = {
660
+ (imgId, catId): computeIoU(imgId, catId)
661
+ for imgId in p.imgIds
662
+ for catId in catIds
663
+ }
664
+
665
+ maxDet = p.maxDets[-1]
666
+ if use_self_evaluate:
667
+ evalImgs = [
668
+ self.evaluateImg(imgId, catId, areaRng, maxDet)
669
+ for catId in catIds
670
+ for areaRng in p.areaRng
671
+ for imgId in p.imgIds
672
+ ]
673
+ # this is NOT in the pycocotools code, but could be done outside
674
+ evalImgs = np.asarray(evalImgs).reshape(
675
+ len(catIds), len(p.areaRng), len(p.imgIds)
676
+ )
677
+ return p.imgIds, evalImgs
678
+
679
+ # <<<< Beginning of code differences with original COCO API
680
+ # def convert_instances_to_cpp(instances, is_det=False):
681
+ # # Convert annotations for a list of instances in an image to a format that's fast
682
+ # # to access in C++
683
+ # instances_cpp = []
684
+ # for instance in instances:
685
+ # instance_cpp = _CPP.InstanceAnnotation(
686
+ # int(instance["id"]),
687
+ # instance["score"] if is_det else instance.get("score", 0.0),
688
+ # instance["area"],
689
+ # bool(instance.get("iscrowd", 0)),
690
+ # bool(instance.get("ignore", 0)),
691
+ # )
692
+ # instances_cpp.append(instance_cpp)
693
+ # return instances_cpp
694
+
695
+ # # Convert GT annotations, detections, and IOUs to a format that's fast to access in C++
696
+ # ground_truth_instances = [
697
+ # [convert_instances_to_cpp(self._gts[imgId, catId]) for catId in p.catIds]
698
+ # for imgId in p.imgIds
699
+ # ]
700
+ # detected_instances = [
701
+ # [
702
+ # convert_instances_to_cpp(self._dts[imgId, catId], is_det=True)
703
+ # for catId in p.catIds
704
+ # ]
705
+ # for imgId in p.imgIds
706
+ # ]
707
+ # ious = [[self.ious[imgId, catId] for catId in catIds] for imgId in p.imgIds]
708
+
709
+ # if not p.useCats:
710
+ # # For each image, flatten per-category lists into a single list
711
+ # ground_truth_instances = [
712
+ # [[o for c in i for o in c]] for i in ground_truth_instances
713
+ # ]
714
+ # detected_instances = [[[o for c in i for o in c]] for i in detected_instances]
715
+
716
+ # # Call C++ implementation of self.evaluateImgs()
717
+ # _evalImgs_cpp = _CPP.COCOevalEvaluateImages(
718
+ # p.areaRng, maxDet, p.iouThrs, ious, ground_truth_instances, detected_instances
719
+ # )
720
+
721
+ # self._paramsEval = copy.deepcopy(self.params)
722
+ # evalImgs = np.asarray(_evalImgs_cpp).reshape(
723
+ # len(catIds), len(p.areaRng), len(p.imgIds)
724
+ # )
725
+ # return p.imgIds, evalImgs
726
+
727
+
728
+ #################################################################
729
+ # end of straight copy from pycocotools, just removing the prints
730
+ #################################################################
731
+
732
+
733
+ #################################################################
734
+ # From pycocotools, but disabled mask->box conversion which is
735
+ # pointless
736
+ #################################################################
737
+ def loadRes(self, resFile):
738
+ """
739
+ Load result file and return a result api object.
740
+ :param resFile (str) : file name of result file
741
+ :return: res (obj) : result api object
742
+ """
743
+ res = COCO()
744
+ res.dataset["images"] = [img for img in self.dataset["images"]]
745
+
746
+ if type(resFile) == str:
747
+ anns = json.load(open(resFile))
748
+ elif type(resFile) == np.ndarray:
749
+ anns = self.loadNumpyAnnotations(resFile)
750
+ else:
751
+ anns = resFile
752
+ assert type(anns) == list, "results in not an array of objects"
753
+ annsImgIds = [ann["image_id"] for ann in anns]
754
+ assert set(annsImgIds) == (set(annsImgIds) & set(self.getImgIds())), (
755
+ "Results do not correspond to current coco set"
756
+ )
757
+ if "caption" in anns[0]:
758
+ imgIds = set([img["id"] for img in res.dataset["images"]]) & set(
759
+ [ann["image_id"] for ann in anns]
760
+ )
761
+ res.dataset["images"] = [
762
+ img for img in res.dataset["images"] if img["id"] in imgIds
763
+ ]
764
+ for id, ann in enumerate(anns):
765
+ ann["id"] = id + 1
766
+ elif "bbox" in anns[0] and not anns[0]["bbox"] == []:
767
+ res.dataset["categories"] = copy.deepcopy(self.dataset["categories"])
768
+ for id, ann in enumerate(anns):
769
+ bb = ann["bbox"]
770
+ x1, x2, y1, y2 = [bb[0], bb[0] + bb[2], bb[1], bb[1] + bb[3]]
771
+ if "segmentation" not in ann:
772
+ ann["segmentation"] = [[x1, y1, x1, y2, x2, y2, x2, y1]]
773
+ ann["area"] = bb[2] * bb[3]
774
+ ann["id"] = id + 1
775
+ ann["iscrowd"] = 0
776
+ elif "segmentation" in anns[0]:
777
+ res.dataset["categories"] = copy.deepcopy(self.dataset["categories"])
778
+ for id, ann in enumerate(anns):
779
+ # now only support compressed RLE format as segmentation results
780
+ # ann["area"] = mask_util.area(ann["segmentation"])
781
+ # The following lines are disabled because they are pointless
782
+ # if not 'bbox' in ann:
783
+ # ann['bbox'] = maskUtils.toBbox(ann['segmentation'])
784
+ ann["id"] = id + 1
785
+ ann["iscrowd"] = 0
786
+ elif "keypoints" in anns[0]:
787
+ res.dataset["categories"] = copy.deepcopy(self.dataset["categories"])
788
+ for id, ann in enumerate(anns):
789
+ s = ann["keypoints"]
790
+ x = s[0::3]
791
+ y = s[1::3]
792
+ x0, x1, y0, y1 = np.min(x), np.max(x), np.min(y), np.max(y)
793
+ ann["area"] = (x1 - x0) * (y1 - y0)
794
+ ann["id"] = id + 1
795
+ ann["bbox"] = [x0, y0, x1 - x0, y1 - y0]
796
+
797
+ res.dataset["annotations"] = anns
798
+ res.createIndex()
799
+ return res
800
+
801
+
802
+ #################################################################
803
+ # end of straight copy from pycocotools
804
+ #################################################################
805
+
806
+
807
+ #################################################################
808
+ # From pycocotools, but added handling of custom area rngs, and returns stat keys
809
+ #################################################################
810
+ def summarize(self):
811
+ """
812
+ Compute and display summary metrics for evaluation results.
813
+ Note this functin can *only* be applied on the default parameter setting
814
+ """
815
+
816
+ def _summarize(ap=1, iouThr=None, areaRng="all", maxDets=100):
817
+ p = self.params
818
+ iStr = " {:<18} {} @[ IoU={:<9} | area={:>6s} | maxDets={:>3d} ] = {:0.3f}"
819
+ titleStr = "Average Precision" if ap == 1 else "Average Recall"
820
+ typeStr = "(AP)" if ap == 1 else "(AR)"
821
+ iouStr = (
822
+ "{:0.2f}:{:0.2f}".format(p.iouThrs[0], p.iouThrs[-1])
823
+ if iouThr is None
824
+ else "{:0.2f}".format(iouThr)
825
+ )
826
+
827
+ aind = [i for i, aRng in enumerate(p.areaRngLbl) if aRng == areaRng]
828
+ mind = [i for i, mDet in enumerate(p.maxDets) if mDet == maxDets]
829
+ if ap == 1:
830
+ # dimension of precision: [TxRxKxAxM]
831
+ s = self.eval["precision"]
832
+ # IoU
833
+ if iouThr is not None:
834
+ t = np.where(iouThr == p.iouThrs)[0]
835
+ s = s[t]
836
+ s = s[:, :, :, aind, mind]
837
+ else:
838
+ # dimension of recall: [TxKxAxM]
839
+ s = self.eval["recall"]
840
+ if iouThr is not None:
841
+ t = np.where(iouThr == p.iouThrs)[0]
842
+ s = s[t]
843
+ s = s[:, :, aind, mind]
844
+ if len(s[s > -1]) == 0:
845
+ mean_s = -1
846
+ else:
847
+ mean_s = np.mean(s[s > -1])
848
+ print(iStr.format(titleStr, typeStr, iouStr, areaRng, maxDets, mean_s))
849
+ return mean_s
850
+
851
+ def _summarizeDets():
852
+ nb_results = 6 + (len(self.params.areaRng) - 1) * 2
853
+ assert len(self.params.areaRng) == len(self.params.areaRngLbl)
854
+ stats = np.zeros((nb_results,))
855
+ keys = ["AP", "AP_50", "AP_75"]
856
+ stats[0] = _summarize(1, maxDets=self.params.maxDets[2])
857
+ stats[1] = _summarize(1, iouThr=0.5, maxDets=self.params.maxDets[2])
858
+ stats[2] = _summarize(1, iouThr=0.75, maxDets=self.params.maxDets[2])
859
+ cur_id = 3
860
+ for area in self.params.areaRngLbl[1:]:
861
+ stats[cur_id] = _summarize(1, areaRng=area, maxDets=self.params.maxDets[2])
862
+ cur_id += 1
863
+ keys.append(f"AP_{area}")
864
+ stats[cur_id] = _summarize(0, maxDets=self.params.maxDets[0])
865
+ cur_id += 1
866
+ stats[cur_id] = _summarize(0, maxDets=self.params.maxDets[1])
867
+ cur_id += 1
868
+ stats[cur_id] = _summarize(0, maxDets=self.params.maxDets[2])
869
+ cur_id += 1
870
+ keys += ["AR", "AR_50", "AR_75"]
871
+
872
+ for area in self.params.areaRngLbl[1:]:
873
+ stats[cur_id] = _summarize(0, areaRng=area, maxDets=self.params.maxDets[2])
874
+ cur_id += 1
875
+ keys.append(f"AR_{area}")
876
+ assert len(stats) == len(keys)
877
+ return keys, stats
878
+
879
+ if not self.eval:
880
+ raise Exception("Please run accumulate() first")
881
+ self.stats = _summarizeDets()
882
+
883
+
884
+ #################################################################
885
+ # end of straight copy from pycocotools
886
+ #################################################################
887
+
888
+
889
+ #################################################################
890
+ # From https://github.com/facebookresearch/detectron2/blob/main/detectron2/evaluation/fast_eval_api.py
891
+ # with slight adjustments
892
+ #################################################################
893
+ def accumulate(self, use_self_eval=False):
894
+ """
895
+ Accumulate per image evaluation results and store the result in self.eval. Does not
896
+ support changing parameter settings from those used by self.evaluate()
897
+ """
898
+ if use_self_eval:
899
+ self.accumulate()
900
+ return
901
+ # CPP code is disabled
902
+ # self.eval = _CPP.COCOevalAccumulate(self.params, self.evalImgs)
903
+
904
+ # # recall is num_iou_thresholds X num_categories X num_area_ranges X num_max_detections
905
+ # self.eval["recall"] = np.array(self.eval["recall"]).reshape(
906
+ # self.eval["counts"][:1] + self.eval["counts"][2:]
907
+ # )
908
+
909
+ # # precision and scores are num_iou_thresholds X num_recall_thresholds X num_categories X
910
+ # # num_area_ranges X num_max_detections
911
+ # self.eval["precision"] = np.array(self.eval["precision"]).reshape(
912
+ # self.eval["counts"]
913
+ # )
914
+ # self.eval["scores"] = np.array(self.eval["scores"]).reshape(self.eval["counts"])
third_party/GraspGen/sam3/sam3/eval/coco_eval_offline.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ """
6
+ This evaluator is meant for regular COCO mAP evaluation, for example on the COCO val set.
7
+
8
+ For Category mAP, we need the model to make predictions for all the categories on every single image.
9
+ In general, since the number of classes can be big, and the API model makes predictions individually for each pair (image, class),
10
+ we may need to split the inference process for a given image in several chunks.
11
+ """
12
+
13
+ import logging
14
+ from collections import defaultdict
15
+
16
+ import torch
17
+ from pycocotools.coco import COCO
18
+ from pycocotools.cocoeval import COCOeval
19
+ from sam3.train.utils.distributed import is_main_process
20
+
21
+ try:
22
+ from tidecv import datasets, TIDE
23
+
24
+ HAS_TIDE = True
25
+ except ImportError:
26
+ HAS_TIDE = False
27
+ print("WARNING: TIDE not installed. Detailed analysis will not be available.")
28
+
29
+
30
+ # the COCO detection metrics (https://github.com/cocodataset/cocoapi/blob/8c9bcc3cf640524c4c20a9c40e89cb6a2f2fa0e9/PythonAPI/pycocotools/cocoeval.py#L460-L471)
31
+ COCO_METRICS = [
32
+ "AP",
33
+ "AP_50",
34
+ "AP_75",
35
+ "AP_small",
36
+ "AP_medium",
37
+ "AP_large",
38
+ "AR_maxDets@1",
39
+ "AR_maxDets@10",
40
+ "AR_maxDets@100",
41
+ "AR_small",
42
+ "AR_medium",
43
+ "AR_large",
44
+ ]
45
+
46
+
47
+ def convert_to_xywh(boxes):
48
+ """Convert bounding boxes from xyxy format to xywh format."""
49
+ xmin, ymin, xmax, ymax = boxes.unbind(-1)
50
+ return torch.stack((xmin, ymin, xmax - xmin, ymax - ymin), dim=-1)
51
+
52
+
53
+ class HeapElement:
54
+ """Utility class to make a heap with a custom comparator"""
55
+
56
+ def __init__(self, val):
57
+ self.val = val
58
+
59
+ def __lt__(self, other):
60
+ return self.val["score"] < other.val["score"]
61
+
62
+
63
+ class COCOevalCustom(COCOeval):
64
+ """
65
+ This is a slightly modified version of the original COCO API with added support for positive split evaluation.
66
+ """
67
+
68
+ def __init__(
69
+ self, cocoGt=None, cocoDt=None, iouType="segm", dt_only_positive=False
70
+ ):
71
+ super().__init__(cocoGt, cocoDt, iouType)
72
+ self.dt_only_positive = dt_only_positive
73
+
74
+ def _prepare(self):
75
+ """
76
+ Prepare ._gts and ._dts for evaluation based on params
77
+ :return: None
78
+ """
79
+
80
+ def _toMask(anns, coco):
81
+ # modify ann['segmentation'] by reference
82
+ for ann in anns:
83
+ rle = coco.annToRLE(ann)
84
+ ann["segmentation"] = rle
85
+
86
+ p = self.params
87
+ if p.useCats:
88
+ gts = self.cocoGt.loadAnns(
89
+ self.cocoGt.getAnnIds(imgIds=p.imgIds, catIds=p.catIds)
90
+ )
91
+ dts = self.cocoDt.loadAnns(
92
+ self.cocoDt.getAnnIds(imgIds=p.imgIds, catIds=p.catIds)
93
+ )
94
+ else:
95
+ gts = self.cocoGt.loadAnns(self.cocoGt.getAnnIds(imgIds=p.imgIds))
96
+ dts = self.cocoDt.loadAnns(self.cocoDt.getAnnIds(imgIds=p.imgIds))
97
+
98
+ # convert ground truth to mask if iouType == 'segm'
99
+ if p.iouType == "segm":
100
+ _toMask(gts, self.cocoGt)
101
+ _toMask(dts, self.cocoDt)
102
+ # set ignore flag
103
+ for gt in gts:
104
+ gt["ignore"] = gt["ignore"] if "ignore" in gt else 0
105
+ gt["ignore"] = "iscrowd" in gt and gt["iscrowd"]
106
+ if p.iouType == "keypoints":
107
+ gt["ignore"] = (gt["num_keypoints"] == 0) or gt["ignore"]
108
+ self._gts = defaultdict(list) # gt for evaluation
109
+ self._dts = defaultdict(list) # dt for evaluation
110
+
111
+ _gts_cat_ids = defaultdict(set) # gt for evaluation on positive split
112
+ for gt in gts:
113
+ self._gts[gt["image_id"], gt["category_id"]].append(gt)
114
+ _gts_cat_ids[gt["image_id"]].add(gt["category_id"])
115
+
116
+ #### BEGIN MODIFICATION ####
117
+ for dt in dts:
118
+ if (
119
+ self.dt_only_positive
120
+ and dt["category_id"] not in _gts_cat_ids[dt["image_id"]]
121
+ ):
122
+ continue
123
+ self._dts[dt["image_id"], dt["category_id"]].append(dt)
124
+ #### END MODIFICATION ####
125
+ self.evalImgs = defaultdict(list) # per-image per-category evaluation results
126
+ self.eval = {} # accumulated evaluation results
127
+
128
+
129
+ class CocoEvaluatorOfflineWithPredFileEvaluators:
130
+ def __init__(
131
+ self,
132
+ gt_path,
133
+ tide: bool = True,
134
+ iou_type: str = "bbox",
135
+ positive_split=False,
136
+ ):
137
+ self.gt_path = gt_path
138
+ self.tide_enabled = HAS_TIDE and tide
139
+ self.positive_split = positive_split
140
+ self.iou_type = iou_type
141
+
142
+ def evaluate(self, dumped_file):
143
+ if not is_main_process():
144
+ return {}
145
+
146
+ logging.info("OfflineCoco evaluator: Loading groundtruth")
147
+ self.gt = COCO(self.gt_path)
148
+
149
+ # Creating the result file
150
+ logging.info("Coco evaluator: Creating the result file")
151
+ cocoDt = self.gt.loadRes(str(dumped_file))
152
+
153
+ # Run the evaluation
154
+ logging.info("Coco evaluator: Running evaluation")
155
+ coco_eval = COCOevalCustom(
156
+ self.gt, cocoDt, iouType=self.iou_type, dt_only_positive=self.positive_split
157
+ )
158
+ coco_eval.evaluate()
159
+ coco_eval.accumulate()
160
+ coco_eval.summarize()
161
+
162
+ outs = {}
163
+ for i, value in enumerate(coco_eval.stats):
164
+ outs[f"coco_eval_{self.iou_type}_{COCO_METRICS[i]}"] = value
165
+
166
+ if self.tide_enabled:
167
+ logging.info("Coco evaluator: Loading TIDE")
168
+ self.tide_gt = datasets.COCO(self.gt_path)
169
+ self.tide = TIDE(mode="mask" if self.iou_type == "segm" else "bbox")
170
+
171
+ # Run TIDE
172
+ logging.info("Coco evaluator: Running TIDE")
173
+ self.tide.evaluate(
174
+ self.tide_gt, datasets.COCOResult(str(dumped_file)), name="coco_eval"
175
+ )
176
+ self.tide.summarize()
177
+ for k, v in self.tide.get_main_errors()["coco_eval"].items():
178
+ outs[f"coco_eval_{self.iou_type}_TIDE_{k}"] = v
179
+
180
+ for k, v in self.tide.get_special_errors()["coco_eval"].items():
181
+ outs[f"coco_eval_{self.iou_type}_TIDE_{k}"] = v
182
+
183
+ return outs
third_party/GraspGen/sam3/sam3/eval/conversion_util.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+ import json
5
+ import os
6
+ from collections import defaultdict
7
+
8
+ from tqdm import tqdm
9
+
10
+
11
+ def convert_ytbvis_to_cocovid_gt(ann_json, save_path=None):
12
+ """Convert YouTube VIS dataset to COCO-style video instance segmentation format.
13
+
14
+ Args:
15
+ ann_json (str): Path to YouTube VIS annotation JSON file
16
+ save_path (str): path to save converted COCO-style JSON
17
+ """
18
+ # Initialize COCO structure
19
+ VIS = {
20
+ "info": {},
21
+ "images": [],
22
+ "videos": [],
23
+ "tracks": [],
24
+ "annotations": [],
25
+ "categories": [],
26
+ "licenses": [],
27
+ }
28
+
29
+ # Load original annotations
30
+ official_anns = json.load(open(ann_json))
31
+ VIS["categories"] = official_anns["categories"] # Direct copy categories
32
+
33
+ # Initialize counters
34
+ records = dict(img_id=1, ann_id=1)
35
+
36
+ # Create video-to-annotations mapping
37
+ vid_to_anns = defaultdict(list)
38
+ for ann in official_anns["annotations"]:
39
+ vid_to_anns[ann["video_id"]].append(ann)
40
+
41
+ # Create tracks directly
42
+ VIS["tracks"] = [
43
+ {
44
+ "id": ann["id"],
45
+ "category_id": ann["category_id"],
46
+ "video_id": ann["video_id"],
47
+ }
48
+ for ann in official_anns["annotations"]
49
+ ]
50
+
51
+ # Process videos
52
+ for video_info in tqdm(official_anns["videos"]):
53
+ # Create video entry
54
+ video = {
55
+ "id": video_info["id"],
56
+ "name": os.path.dirname(video_info["file_names"][0]),
57
+ "width": video_info["width"],
58
+ "height": video_info["height"],
59
+ "length": video_info["length"],
60
+ "neg_category_ids": [],
61
+ "not_exhaustive_category_ids": [],
62
+ }
63
+ VIS["videos"].append(video)
64
+
65
+ # Process frames
66
+ num_frames = len(video_info["file_names"])
67
+ for frame_idx in range(num_frames):
68
+ # Create image entry
69
+ image = {
70
+ "id": records["img_id"],
71
+ "video_id": video_info["id"],
72
+ "file_name": video_info["file_names"][frame_idx],
73
+ "width": video_info["width"],
74
+ "height": video_info["height"],
75
+ "frame_index": frame_idx,
76
+ "frame_id": frame_idx,
77
+ }
78
+ VIS["images"].append(image)
79
+
80
+ # Process annotations for this frame
81
+ if video_info["id"] in vid_to_anns:
82
+ for ann in vid_to_anns[video_info["id"]]:
83
+ bbox = ann["bboxes"][frame_idx]
84
+ if bbox is None:
85
+ continue
86
+
87
+ # Create annotation entry
88
+ annotation = {
89
+ "id": records["ann_id"],
90
+ "video_id": video_info["id"],
91
+ "image_id": records["img_id"],
92
+ "track_id": ann["id"],
93
+ "category_id": ann["category_id"],
94
+ "bbox": bbox,
95
+ "area": ann["areas"][frame_idx],
96
+ "segmentation": ann["segmentations"][frame_idx],
97
+ "iscrowd": ann["iscrowd"],
98
+ }
99
+ VIS["annotations"].append(annotation)
100
+ records["ann_id"] += 1
101
+
102
+ records["img_id"] += 1
103
+
104
+ # Print summary
105
+ print(f"Converted {len(VIS['videos'])} videos")
106
+ print(f"Converted {len(VIS['images'])} images")
107
+ print(f"Created {len(VIS['tracks'])} tracks")
108
+ print(f"Created {len(VIS['annotations'])} annotations")
109
+
110
+ if save_path is None:
111
+ return VIS
112
+
113
+ # Save output
114
+ save_dir = os.path.dirname(save_path)
115
+ os.makedirs(save_dir, exist_ok=True)
116
+ json.dump(VIS, open(save_path, "w"))
117
+
118
+ return VIS
119
+
120
+
121
+ def convert_ytbvis_to_cocovid_pred(
122
+ youtubevis_pred_path: str, converted_dataset_path: str, output_path: str
123
+ ) -> None:
124
+ """
125
+ Convert YouTubeVIS predictions to COCO format with video_id preservation
126
+
127
+ Args:
128
+ youtubevis_pred_path: Path to YouTubeVIS prediction JSON
129
+ converted_dataset_path: Path to converted COCO dataset JSON
130
+ output_path: Path to save COCO format predictions
131
+ """
132
+
133
+ # Load YouTubeVIS predictions
134
+ with open(youtubevis_pred_path) as f:
135
+ ytv_predictions = json.load(f)
136
+
137
+ # Load converted dataset for image ID mapping
138
+ with open(converted_dataset_path) as f:
139
+ coco_dataset = json.load(f)
140
+
141
+ # Create (video_id, frame_idx) -> image_id mapping
142
+ image_id_map = {
143
+ (img["video_id"], img["frame_index"]): img["id"]
144
+ for img in coco_dataset["images"]
145
+ }
146
+
147
+ coco_annotations = []
148
+ track_id_counter = 1 # Unique track ID generator
149
+
150
+ for pred in tqdm(ytv_predictions):
151
+ video_id = pred["video_id"]
152
+ category_id = pred["category_id"]
153
+ bboxes = pred["bboxes"]
154
+ segmentations = pred.get("segmentations", []) # Get segmentations if available
155
+ areas = pred.get("areas", []) # Get areas if available
156
+ score = pred["score"]
157
+
158
+ # Assign unique track ID for this prediction
159
+ track_id = track_id_counter
160
+ track_id_counter += 1
161
+
162
+ # Ensure segmentations and areas have the same length as bboxes
163
+ if len(segmentations) == 0:
164
+ segmentations = [None] * len(bboxes)
165
+ if len(areas) == 0:
166
+ areas = [None] * len(bboxes)
167
+
168
+ for frame_idx, (bbox, segmentation, area_from_pred) in enumerate(
169
+ zip(bboxes, segmentations, areas)
170
+ ):
171
+ # Skip frames with missing objects (None or zero bbox)
172
+ if bbox is None or all(x == 0 for x in bbox):
173
+ continue
174
+
175
+ # Get corresponding image ID from mapping
176
+ image_id = image_id_map.get((video_id, frame_idx))
177
+ if image_id is None:
178
+ raise RuntimeError(
179
+ f"prediction {video_id=}, {frame_idx=} does not match any images in the converted COCO format"
180
+ )
181
+
182
+ # Extract bbox coordinates
183
+ x, y, w, h = bbox
184
+
185
+ # Calculate area - use area from prediction if available, otherwise from bbox
186
+ if area_from_pred is not None and area_from_pred > 0:
187
+ area = area_from_pred
188
+ else:
189
+ area = w * h
190
+
191
+ # Create COCO annotation with video_id
192
+ coco_annotation = {
193
+ "image_id": int(image_id),
194
+ "video_id": video_id, # Added video_id field
195
+ "track_id": track_id,
196
+ "category_id": category_id,
197
+ "bbox": [float(x), float(y), float(w), float(h)],
198
+ "area": float(area),
199
+ "iscrowd": 0,
200
+ "score": float(score),
201
+ }
202
+
203
+ # Add segmentation if available
204
+ if segmentation is not None:
205
+ coco_annotation["segmentation"] = segmentation
206
+
207
+ coco_annotations.append(coco_annotation)
208
+
209
+ # Save output
210
+ with open(output_path, "w") as f:
211
+ json.dump(coco_annotations, f)
212
+
213
+ print(f"Converted {len(coco_annotations)} predictions to COCO format with video_id")
third_party/GraspGen/sam3/sam3/eval/demo_eval.py ADDED
@@ -0,0 +1,658 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ """
6
+ This evaluator is based upon COCO evaluation, but evaluates the model in a "demo" setting.
7
+ This means that the model's predictions are thresholded and evaluated as "hard" predictions.
8
+ """
9
+
10
+ import logging
11
+ from typing import Optional
12
+
13
+ import numpy as np
14
+ import pycocotools.mask as maskUtils
15
+ from pycocotools.cocoeval import COCOeval
16
+ from sam3.eval.coco_eval import CocoEvaluator
17
+ from sam3.train.masks_ops import compute_F_measure
18
+ from sam3.train.utils.distributed import is_main_process
19
+ from scipy.optimize import linear_sum_assignment
20
+
21
+
22
+ class DemoEval(COCOeval):
23
+ """
24
+ This evaluator is based upon COCO evaluation, but evaluates the model in a "demo" setting.
25
+ This means that the model's predictions are thresholded and evaluated as "hard" predictions.
26
+ """
27
+
28
+ def __init__(
29
+ self,
30
+ coco_gt=None,
31
+ coco_dt=None,
32
+ iouType="bbox",
33
+ threshold=0.5,
34
+ compute_JnF=False,
35
+ ):
36
+ """
37
+ Args:
38
+ coco_gt (COCO): ground truth COCO API
39
+ coco_dt (COCO): detections COCO API
40
+ iou_type (str): type of IoU to evaluate
41
+ threshold (float): threshold for predictions
42
+ """
43
+ super().__init__(coco_gt, coco_dt, iouType)
44
+ self.threshold = threshold
45
+
46
+ self.params.useCats = False
47
+ self.params.areaRng = [[0**2, 1e5**2]]
48
+ self.params.areaRngLbl = ["all"]
49
+ self.params.maxDets = [100000]
50
+ self.compute_JnF = compute_JnF
51
+
52
+ def computeIoU(self, imgId, catId):
53
+ # Same as the original COCOeval.computeIoU, but without sorting
54
+ p = self.params
55
+ if p.useCats:
56
+ gt = self._gts[imgId, catId]
57
+ dt = self._dts[imgId, catId]
58
+ else:
59
+ gt = [_ for cId in p.catIds for _ in self._gts[imgId, cId]]
60
+ dt = [_ for cId in p.catIds for _ in self._dts[imgId, cId]]
61
+ if len(gt) == 0 and len(dt) == 0:
62
+ return []
63
+
64
+ if p.iouType == "segm":
65
+ g = [g["segmentation"] for g in gt]
66
+ d = [d["segmentation"] for d in dt]
67
+ elif p.iouType == "bbox":
68
+ g = [g["bbox"] for g in gt]
69
+ d = [d["bbox"] for d in dt]
70
+ else:
71
+ raise Exception("unknown iouType for iou computation")
72
+
73
+ # compute iou between each dt and gt region
74
+ iscrowd = [int(o["iscrowd"]) for o in gt]
75
+ ious = maskUtils.iou(d, g, iscrowd)
76
+ return ious
77
+
78
+ def evaluateImg(self, imgId, catId, aRng, maxDet):
79
+ """
80
+ perform evaluation for single category and image
81
+ :return: dict (single image results)
82
+ """
83
+ p = self.params
84
+ assert not p.useCats, "This evaluator does not support per-category evaluation."
85
+ assert catId == -1
86
+ all_gts = [_ for cId in p.catIds for _ in self._gts[imgId, cId]]
87
+ keep_gt = np.array([not g["ignore"] for g in all_gts], dtype=bool)
88
+ gt = [g for g in all_gts if not g["ignore"]]
89
+ all_dts = [_ for cId in p.catIds for _ in self._dts[imgId, cId]]
90
+ keep_dt = np.array([d["score"] >= self.threshold for d in all_dts], dtype=bool)
91
+ dt = [d for d in all_dts if d["score"] >= self.threshold]
92
+ if len(gt) == 0 and len(dt) == 0:
93
+ # This is a "true negative" case, where there are no GTs and no predictions
94
+ # The box-level metrics are ill-defined, so we don't add them to this dict
95
+ return {
96
+ "image_id": imgId,
97
+ "IL_TP": 0,
98
+ "IL_TN": 1,
99
+ "IL_FP": 0,
100
+ "IL_FN": 0,
101
+ "IL_perfect_neg": np.ones((len(p.iouThrs),), dtype=np.int64),
102
+ "num_dt": len(dt),
103
+ }
104
+
105
+ if len(gt) > 0 and len(dt) == 0:
106
+ # This is a "false negative" case, where there are GTs but no predictions
107
+ return {
108
+ "image_id": imgId,
109
+ "IL_TP": 0,
110
+ "IL_TN": 0,
111
+ "IL_FP": 0,
112
+ "IL_FN": 1,
113
+ "TPs": np.zeros((len(p.iouThrs),), dtype=np.int64),
114
+ "FPs": np.zeros((len(p.iouThrs),), dtype=np.int64),
115
+ "FNs": np.ones((len(p.iouThrs),), dtype=np.int64) * len(gt),
116
+ "local_F1s": np.zeros((len(p.iouThrs),), dtype=np.int64),
117
+ "local_positive_F1s": np.zeros((len(p.iouThrs),), dtype=np.int64),
118
+ "IL_perfect_pos": np.zeros((len(p.iouThrs),), dtype=np.int64),
119
+ "num_dt": len(dt),
120
+ }
121
+
122
+ # Load pre-computed ious
123
+ ious = self.ious[(imgId, catId)]
124
+
125
+ # compute matching
126
+ if len(ious) == 0:
127
+ ious = np.zeros((len(dt), len(gt)))
128
+ else:
129
+ ious = ious[keep_dt, :][:, keep_gt]
130
+ assert ious.shape == (len(dt), len(gt))
131
+
132
+ matched_dt, matched_gt = linear_sum_assignment(-ious)
133
+
134
+ match_scores = ious[matched_dt, matched_gt]
135
+
136
+ if self.compute_JnF and len(match_scores) > 0:
137
+ j_score = match_scores.mean()
138
+ f_measure = 0
139
+ for dt_id, gt_id in zip(matched_dt, matched_gt):
140
+ f_measure += compute_F_measure(
141
+ gt_boundary_rle=gt[gt_id]["boundary"],
142
+ gt_dilated_boundary_rle=gt[gt_id]["dilated_boundary"],
143
+ dt_boundary_rle=dt[dt_id]["boundary"],
144
+ dt_dilated_boundary_rle=dt[dt_id]["dilated_boundary"],
145
+ )
146
+ f_measure /= len(match_scores) + 1e-9
147
+ JnF = (j_score + f_measure) * 0.5
148
+ else:
149
+ j_score = f_measure = JnF = -1
150
+
151
+ TPs, FPs, FNs = [], [], []
152
+ IL_perfect = []
153
+ for thresh in p.iouThrs:
154
+ TP = (match_scores >= thresh).sum()
155
+ FP = len(dt) - TP
156
+ FN = len(gt) - TP
157
+ assert FP >= 0 and FN >= 0, (
158
+ f"FP: {FP}, FN: {FN}, TP: {TP}, match_scores: {match_scores}, len(dt): {len(dt)}, len(gt): {len(gt)}, ious: {ious}"
159
+ )
160
+ TPs.append(TP)
161
+ FPs.append(FP)
162
+ FNs.append(FN)
163
+
164
+ if FP == FN and FP == 0:
165
+ IL_perfect.append(1)
166
+ else:
167
+ IL_perfect.append(0)
168
+
169
+ TPs = np.array(TPs, dtype=np.int64)
170
+ FPs = np.array(FPs, dtype=np.int64)
171
+ FNs = np.array(FNs, dtype=np.int64)
172
+ IL_perfect = np.array(IL_perfect, dtype=np.int64)
173
+
174
+ # compute precision recall and F1
175
+ precision = TPs / (TPs + FPs + 1e-4)
176
+ assert np.all(precision <= 1)
177
+ recall = TPs / (TPs + FNs + 1e-4)
178
+ assert np.all(recall <= 1)
179
+ F1 = 2 * precision * recall / (precision + recall + 1e-4)
180
+
181
+ result = {
182
+ "image_id": imgId,
183
+ "TPs": TPs,
184
+ "FPs": FPs,
185
+ "FNs": FNs,
186
+ "local_F1s": F1,
187
+ "IL_TP": (len(gt) > 0) and (len(dt) > 0),
188
+ "IL_FP": (len(gt) == 0) and (len(dt) > 0),
189
+ "IL_TN": (len(gt) == 0) and (len(dt) == 0),
190
+ "IL_FN": (len(gt) > 0) and (len(dt) == 0),
191
+ ("IL_perfect_pos" if len(gt) > 0 else "IL_perfect_neg"): IL_perfect,
192
+ "F": f_measure,
193
+ "J": j_score,
194
+ "J&F": JnF,
195
+ "num_dt": len(dt),
196
+ }
197
+ if len(gt) > 0 and len(dt) > 0:
198
+ result["local_positive_F1s"] = F1
199
+ return result
200
+
201
+ def accumulate(self, p=None):
202
+ """
203
+ Accumulate per image evaluation results and store the result in self.eval
204
+ :param p: input params for evaluation
205
+ :return: None
206
+ """
207
+ if not self.evalImgs:
208
+ print("Please run evaluate() first")
209
+ # allows input customized parameters
210
+ if p is None:
211
+ p = self.params
212
+
213
+ setImgIds = set(p.imgIds)
214
+
215
+ # TPs, FPs, FNs
216
+ TPs = np.zeros((len(p.iouThrs),), dtype=np.int64)
217
+ FPs = np.zeros((len(p.iouThrs),), dtype=np.int64)
218
+ pmFPs = np.zeros((len(p.iouThrs),), dtype=np.int64)
219
+ FNs = np.zeros((len(p.iouThrs),), dtype=np.int64)
220
+ local_F1s = np.zeros((len(p.iouThrs),), dtype=np.float64)
221
+
222
+ # Image level metrics
223
+ IL_TPs = 0
224
+ IL_FPs = 0
225
+ IL_TNs = 0
226
+ IL_FNs = 0
227
+ IL_perfects_neg = np.zeros((len(p.iouThrs),), dtype=np.int64)
228
+ IL_perfects_pos = np.zeros((len(p.iouThrs),), dtype=np.int64)
229
+
230
+ # JnF metric
231
+ total_J = 0
232
+ total_F = 0
233
+ total_JnF = 0
234
+
235
+ valid_img_count = 0
236
+ total_pos_count = 0
237
+ total_neg_count = 0
238
+ valid_J_count = 0
239
+ valid_F1_count = 0
240
+ valid_F1_count_w0dt = 0
241
+ for res in self.evalImgs:
242
+ if res["image_id"] not in setImgIds:
243
+ continue
244
+ IL_TPs += res["IL_TP"]
245
+ IL_FPs += res["IL_FP"]
246
+ IL_TNs += res["IL_TN"]
247
+ IL_FNs += res["IL_FN"]
248
+ if "IL_perfect_neg" in res:
249
+ IL_perfects_neg += res["IL_perfect_neg"]
250
+ total_neg_count += 1
251
+ else:
252
+ assert "IL_perfect_pos" in res
253
+ IL_perfects_pos += res["IL_perfect_pos"]
254
+ total_pos_count += 1
255
+
256
+ if "TPs" not in res:
257
+ continue
258
+
259
+ TPs += res["TPs"]
260
+ FPs += res["FPs"]
261
+ FNs += res["FNs"]
262
+ valid_img_count += 1
263
+
264
+ if "local_positive_F1s" in res:
265
+ local_F1s += res["local_positive_F1s"]
266
+ pmFPs += res["FPs"]
267
+ valid_F1_count_w0dt += 1
268
+ if res["num_dt"] > 0:
269
+ valid_F1_count += 1
270
+
271
+ if "J" in res and res["J"] > -1e-9:
272
+ total_J += res["J"]
273
+ total_F += res["F"]
274
+ total_JnF += res["J&F"]
275
+ valid_J_count += 1
276
+
277
+ # compute precision recall and F1
278
+ precision = TPs / (TPs + FPs + 1e-4)
279
+ positive_micro_precision = TPs / (TPs + pmFPs + 1e-4)
280
+ assert np.all(precision <= 1)
281
+ recall = TPs / (TPs + FNs + 1e-4)
282
+ assert np.all(recall <= 1)
283
+ F1 = 2 * precision * recall / (precision + recall + 1e-4)
284
+ positive_micro_F1 = (
285
+ 2
286
+ * positive_micro_precision
287
+ * recall
288
+ / (positive_micro_precision + recall + 1e-4)
289
+ )
290
+
291
+ IL_rec = IL_TPs / (IL_TPs + IL_FNs + 1e-6)
292
+ IL_prec = IL_TPs / (IL_TPs + IL_FPs + 1e-6)
293
+ IL_F1 = 2 * IL_prec * IL_rec / (IL_prec + IL_rec + 1e-6)
294
+ IL_FPR = IL_FPs / (IL_FPs + IL_TNs + 1e-6)
295
+ IL_MCC = float(IL_TPs * IL_TNs - IL_FPs * IL_FNs) / (
296
+ (
297
+ float(IL_TPs + IL_FPs)
298
+ * float(IL_TPs + IL_FNs)
299
+ * float(IL_TNs + IL_FPs)
300
+ * float(IL_TNs + IL_FNs)
301
+ )
302
+ ** 0.5
303
+ + 1e-6
304
+ )
305
+ IL_perfect_pos = IL_perfects_pos / (total_pos_count + 1e-9)
306
+ IL_perfect_neg = IL_perfects_neg / (total_neg_count + 1e-9)
307
+
308
+ total_J = total_J / (valid_J_count + 1e-9)
309
+ total_F = total_F / (valid_J_count + 1e-9)
310
+ total_JnF = total_JnF / (valid_J_count + 1e-9)
311
+
312
+ self.eval = {
313
+ "params": p,
314
+ "TPs": TPs,
315
+ "FPs": FPs,
316
+ "positive_micro_FPs": pmFPs,
317
+ "FNs": FNs,
318
+ "precision": precision,
319
+ "positive_micro_precision": positive_micro_precision,
320
+ "recall": recall,
321
+ "F1": F1,
322
+ "positive_micro_F1": positive_micro_F1,
323
+ "positive_macro_F1": local_F1s / valid_F1_count,
324
+ "positive_w0dt_macro_F1": local_F1s / valid_F1_count_w0dt,
325
+ "IL_recall": IL_rec,
326
+ "IL_precision": IL_prec,
327
+ "IL_F1": IL_F1,
328
+ "IL_FPR": IL_FPR,
329
+ "IL_MCC": IL_MCC,
330
+ "IL_perfect_pos": IL_perfect_pos,
331
+ "IL_perfect_neg": IL_perfect_neg,
332
+ "J": total_J,
333
+ "F": total_F,
334
+ "J&F": total_JnF,
335
+ }
336
+ self.eval["CGF1"] = self.eval["positive_macro_F1"] * self.eval["IL_MCC"]
337
+ self.eval["CGF1_w0dt"] = (
338
+ self.eval["positive_w0dt_macro_F1"] * self.eval["IL_MCC"]
339
+ )
340
+ self.eval["CGF1_micro"] = self.eval["positive_micro_F1"] * self.eval["IL_MCC"]
341
+
342
+ def summarize(self):
343
+ """
344
+ Compute and display summary metrics for evaluation results.
345
+ Note this functin can *only* be applied on the default parameter setting
346
+ """
347
+ if not self.eval:
348
+ raise Exception("Please run accumulate() first")
349
+
350
+ def _summarize(iouThr=None, metric=""):
351
+ p = self.params
352
+ iStr = " {:<18} @[ IoU={:<9}] = {:0.3f}"
353
+ titleStr = "Average " + metric
354
+ iouStr = (
355
+ "{:0.2f}:{:0.2f}".format(p.iouThrs[0], p.iouThrs[-1])
356
+ if iouThr is None
357
+ else "{:0.2f}".format(iouThr)
358
+ )
359
+
360
+ s = self.eval[metric]
361
+ # IoU
362
+ if iouThr is not None:
363
+ t = np.where(iouThr == p.iouThrs)[0]
364
+ s = s[t]
365
+
366
+ if len(s[s > -1]) == 0:
367
+ mean_s = -1
368
+ else:
369
+ mean_s = np.mean(s[s > -1])
370
+ print(iStr.format(titleStr, iouStr, mean_s))
371
+ return mean_s
372
+
373
+ def _summarize_single(metric=""):
374
+ titleStr = "Average " + metric
375
+ iStr = " {:<35} = {:0.3f}"
376
+ s = self.eval[metric]
377
+ print(iStr.format(titleStr, s))
378
+ return s
379
+
380
+ def _summarizeDets():
381
+ # note: the index of these metrics are also used in video Demo F1 evaluation
382
+ # when adding new metrics, please update the index in video Demo F1 evaluation
383
+ # in "evaluate" method of the "VideoDemoF1Evaluator" class
384
+ stats = np.zeros((len(DEMO_METRICS),))
385
+ stats[0] = _summarize(metric="CGF1")
386
+ stats[1] = _summarize(metric="precision")
387
+ stats[2] = _summarize(metric="recall")
388
+ stats[3] = _summarize(metric="F1")
389
+ stats[4] = _summarize(metric="positive_macro_F1")
390
+ stats[5] = _summarize_single(metric="IL_precision")
391
+ stats[6] = _summarize_single(metric="IL_recall")
392
+ stats[7] = _summarize_single(metric="IL_F1")
393
+ stats[8] = _summarize_single(metric="IL_FPR")
394
+ stats[9] = _summarize_single(metric="IL_MCC")
395
+ stats[10] = _summarize(metric="IL_perfect_pos")
396
+ stats[11] = _summarize(metric="IL_perfect_neg")
397
+ stats[12] = _summarize(iouThr=0.5, metric="CGF1")
398
+ stats[13] = _summarize(iouThr=0.5, metric="precision")
399
+ stats[14] = _summarize(iouThr=0.5, metric="recall")
400
+ stats[15] = _summarize(iouThr=0.5, metric="F1")
401
+ stats[16] = _summarize(iouThr=0.5, metric="positive_macro_F1")
402
+ stats[17] = _summarize(iouThr=0.5, metric="IL_perfect_pos")
403
+ stats[18] = _summarize(iouThr=0.5, metric="IL_perfect_neg")
404
+ stats[19] = _summarize(iouThr=0.75, metric="CGF1")
405
+ stats[20] = _summarize(iouThr=0.75, metric="precision")
406
+ stats[21] = _summarize(iouThr=0.75, metric="recall")
407
+ stats[22] = _summarize(iouThr=0.75, metric="F1")
408
+ stats[23] = _summarize(iouThr=0.75, metric="positive_macro_F1")
409
+ stats[24] = _summarize(iouThr=0.75, metric="IL_perfect_pos")
410
+ stats[25] = _summarize(iouThr=0.75, metric="IL_perfect_neg")
411
+ stats[26] = _summarize_single(metric="J")
412
+ stats[27] = _summarize_single(metric="F")
413
+ stats[28] = _summarize_single(metric="J&F")
414
+ stats[29] = _summarize(metric="CGF1_micro")
415
+ stats[30] = _summarize(metric="positive_micro_precision")
416
+ stats[31] = _summarize(metric="positive_micro_F1")
417
+ stats[32] = _summarize(iouThr=0.5, metric="CGF1_micro")
418
+ stats[33] = _summarize(iouThr=0.5, metric="positive_micro_precision")
419
+ stats[34] = _summarize(iouThr=0.5, metric="positive_micro_F1")
420
+ stats[35] = _summarize(iouThr=0.75, metric="CGF1_micro")
421
+ stats[36] = _summarize(iouThr=0.75, metric="positive_micro_precision")
422
+ stats[37] = _summarize(iouThr=0.75, metric="positive_micro_F1")
423
+ stats[38] = _summarize(metric="CGF1_w0dt")
424
+ stats[39] = _summarize(metric="positive_w0dt_macro_F1")
425
+ stats[40] = _summarize(iouThr=0.5, metric="CGF1_w0dt")
426
+ stats[41] = _summarize(iouThr=0.5, metric="positive_w0dt_macro_F1")
427
+ stats[42] = _summarize(iouThr=0.75, metric="CGF1_w0dt")
428
+ stats[43] = _summarize(iouThr=0.75, metric="positive_w0dt_macro_F1")
429
+ return stats
430
+
431
+ summarize = _summarizeDets
432
+ self.stats = summarize()
433
+
434
+
435
+ DEMO_METRICS = [
436
+ "CGF1",
437
+ "Precision",
438
+ "Recall",
439
+ "F1",
440
+ "Macro_F1",
441
+ "IL_Precision",
442
+ "IL_Recall",
443
+ "IL_F1",
444
+ "IL_FPR",
445
+ "IL_MCC",
446
+ "IL_perfect_pos",
447
+ "IL_perfect_neg",
448
+ "CGF1@0.5",
449
+ "Precision@0.5",
450
+ "Recall@0.5",
451
+ "F1@0.5",
452
+ "Macro_F1@0.5",
453
+ "IL_perfect_pos@0.5",
454
+ "IL_perfect_neg@0.5",
455
+ "CGF1@0.75",
456
+ "Precision@0.75",
457
+ "Recall@0.75",
458
+ "F1@0.75",
459
+ "Macro_F1@0.75",
460
+ "IL_perfect_pos@0.75",
461
+ "IL_perfect_neg@0.75",
462
+ "J",
463
+ "F",
464
+ "J&F",
465
+ "CGF1_micro",
466
+ "positive_micro_Precision",
467
+ "positive_micro_F1",
468
+ "CGF1_micro@0.5",
469
+ "positive_micro_Precision@0.5",
470
+ "positive_micro_F1@0.5",
471
+ "CGF1_micro@0.75",
472
+ "positive_micro_Precision@0.75",
473
+ "positive_micro_F1@0.75",
474
+ "CGF1_w0dt",
475
+ "positive_w0dt_macro_F1",
476
+ "CGF1_w0dt@0.5",
477
+ "positive_w0dt_macro_F1@0.5",
478
+ "CGF1_w0dt@0.75",
479
+ "positive_w0dt_macro_F1@0.75",
480
+ ]
481
+
482
+
483
+ class DemoEvaluator(CocoEvaluator):
484
+ def __init__(
485
+ self,
486
+ coco_gt,
487
+ iou_types,
488
+ dump_dir: Optional[str],
489
+ postprocessor,
490
+ threshold=0.5,
491
+ average_by_rarity=False,
492
+ gather_pred_via_filesys=False,
493
+ exhaustive_only=False,
494
+ all_exhaustive_only=True,
495
+ compute_JnF=False,
496
+ metrics_dump_dir: Optional[str] = None,
497
+ ):
498
+ self.iou_types = iou_types
499
+ self.threshold = threshold
500
+ super().__init__(
501
+ coco_gt=coco_gt,
502
+ iou_types=iou_types,
503
+ useCats=False,
504
+ dump_dir=dump_dir,
505
+ postprocessor=postprocessor,
506
+ # average_by_rarity=average_by_rarity,
507
+ gather_pred_via_filesys=gather_pred_via_filesys,
508
+ exhaustive_only=exhaustive_only,
509
+ all_exhaustive_only=all_exhaustive_only,
510
+ metrics_dump_dir=metrics_dump_dir,
511
+ )
512
+
513
+ self.use_self_evaluate = True
514
+ self.compute_JnF = compute_JnF
515
+
516
+ def _lazy_init(self):
517
+ if self.initialized:
518
+ return
519
+ super()._lazy_init()
520
+ self.use_self_evaluate = True
521
+ self.reset()
522
+
523
+ def select_best_scoring(self, scorings):
524
+ # This function is used for "oracle" type evaluation.
525
+ # It accepts the evaluation results with respect to several ground truths, and picks the best
526
+ if len(scorings) == 1:
527
+ return scorings[0]
528
+
529
+ assert scorings[0].ndim == 3, (
530
+ f"Expecting results in [numCats, numAreas, numImgs] format, got {scorings[0].shape}"
531
+ )
532
+ assert scorings[0].shape[0] == 1, (
533
+ f"Expecting a single category, got {scorings[0].shape[0]}"
534
+ )
535
+
536
+ for scoring in scorings:
537
+ assert scoring.shape == scorings[0].shape, (
538
+ f"Shape mismatch: {scoring.shape}, {scorings[0].shape}"
539
+ )
540
+
541
+ selected_imgs = []
542
+ for img_id in range(scorings[0].shape[-1]):
543
+ best = scorings[0][:, :, img_id]
544
+
545
+ for scoring in scorings[1:]:
546
+ current = scoring[:, :, img_id]
547
+ if "local_F1s" in best[0, 0] and "local_F1s" in current[0, 0]:
548
+ # we were able to compute a F1 score for this particular image in both evaluations
549
+ # best["local_F1s"] contains the results at various IoU thresholds. We simply take the average for comparision
550
+ best_score = best[0, 0]["local_F1s"].mean()
551
+ current_score = current[0, 0]["local_F1s"].mean()
552
+ if current_score > best_score:
553
+ best = current
554
+
555
+ else:
556
+ # If we're here, it means that in that in some evaluation we were not able to get a valid local F1
557
+ # This happens when both the predictions and targets are empty. In that case, we can assume it's a perfect prediction
558
+ if "local_F1s" not in current[0, 0]:
559
+ best = current
560
+ selected_imgs.append(best)
561
+ result = np.stack(selected_imgs, axis=-1)
562
+ assert result.shape == scorings[0].shape
563
+ return result
564
+
565
+ def summarize(self):
566
+ self._lazy_init()
567
+ logging.info("Demo evaluator: Summarizing")
568
+ if not is_main_process():
569
+ return {}
570
+ outs = {}
571
+ prefix = "oracle_" if len(self.coco_evals) > 1 else ""
572
+ # if self.rarity_buckets is None:
573
+ self.accumulate(self.eval_img_ids)
574
+ for iou_type, coco_eval in self.coco_evals[0].items():
575
+ print("Demo metric, IoU type={}".format(iou_type))
576
+ coco_eval.summarize()
577
+
578
+ if "bbox" in self.coco_evals[0]:
579
+ for i, value in enumerate(self.coco_evals[0]["bbox"].stats):
580
+ outs[f"coco_eval_bbox_{prefix}{DEMO_METRICS[i]}"] = value
581
+ if "segm" in self.coco_evals[0]:
582
+ for i, value in enumerate(self.coco_evals[0]["segm"].stats):
583
+ outs[f"coco_eval_masks_{prefix}{DEMO_METRICS[i]}"] = value
584
+ # else:
585
+ # total_stats = {}
586
+ # for bucket, img_list in self.rarity_buckets.items():
587
+ # self.accumulate(imgIds=img_list)
588
+ # bucket_name = RARITY_BUCKETS[bucket]
589
+ # for iou_type, coco_eval in self.coco_evals[0].items():
590
+ # print(
591
+ # "Demo metric, IoU type={}, Rarity bucket={}".format(
592
+ # iou_type, bucket_name
593
+ # )
594
+ # )
595
+ # coco_eval.summarize()
596
+
597
+ # if "bbox" in self.coco_evals[0]:
598
+ # if "bbox" not in total_stats:
599
+ # total_stats["bbox"] = np.zeros_like(
600
+ # self.coco_evals[0]["bbox"].stats
601
+ # )
602
+ # total_stats["bbox"] += self.coco_evals[0]["bbox"].stats
603
+ # for i, value in enumerate(self.coco_evals[0]["bbox"].stats):
604
+ # outs[
605
+ # f"coco_eval_bbox_{bucket_name}_{prefix}{DEMO_METRICS[i]}"
606
+ # ] = value
607
+ # if "segm" in self.coco_evals[0]:
608
+ # if "segm" not in total_stats:
609
+ # total_stats["segm"] = np.zeros_like(
610
+ # self.coco_evals[0]["segm"].stats
611
+ # )
612
+ # total_stats["segm"] += self.coco_evals[0]["segm"].stats
613
+ # for i, value in enumerate(self.coco_evals[0]["segm"].stats):
614
+ # outs[
615
+ # f"coco_eval_masks_{bucket_name}_{prefix}{DEMO_METRICS[i]}"
616
+ # ] = value
617
+
618
+ # if "bbox" in total_stats:
619
+ # total_stats["bbox"] /= len(self.rarity_buckets)
620
+ # for i, value in enumerate(total_stats["bbox"]):
621
+ # outs[f"coco_eval_bbox_{prefix}{DEMO_METRICS[i]}"] = value
622
+ # if "segm" in total_stats:
623
+ # total_stats["segm"] /= len(self.rarity_buckets)
624
+ # for i, value in enumerate(total_stats["segm"]):
625
+ # outs[f"coco_eval_masks_{prefix}{DEMO_METRICS[i]}"] = value
626
+
627
+ return outs
628
+
629
+ def accumulate(self, imgIds=None):
630
+ self._lazy_init()
631
+ logging.info(
632
+ f"demo evaluator: Accumulating on {len(imgIds) if imgIds is not None else 'all'} images"
633
+ )
634
+ if not is_main_process():
635
+ return
636
+
637
+ if imgIds is not None:
638
+ for coco_eval in self.coco_evals[0].values():
639
+ coco_eval.params.imgIds = list(imgIds)
640
+
641
+ for coco_eval in self.coco_evals[0].values():
642
+ coco_eval.accumulate()
643
+
644
+ def reset(self):
645
+ self.coco_evals = [{} for _ in range(len(self.coco_gts))]
646
+ for i, coco_gt in enumerate(self.coco_gts):
647
+ for iou_type in self.iou_types:
648
+ self.coco_evals[i][iou_type] = DemoEval(
649
+ coco_gt=coco_gt,
650
+ iouType=iou_type,
651
+ threshold=self.threshold,
652
+ compute_JnF=self.compute_JnF,
653
+ )
654
+ self.coco_evals[i][iou_type].useCats = False
655
+ self.img_ids = []
656
+ self.eval_imgs = {k: [] for k in self.iou_types}
657
+ if self.dump is not None:
658
+ self.dump = []
third_party/GraspGen/sam3/sam3/eval/saco_veval_eval.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+ import argparse
5
+ import json
6
+ import os
7
+ from collections import defaultdict
8
+
9
+ from iopath.common.file_io import g_pathmgr
10
+ from sam3.eval.saco_veval_evaluators import (
11
+ VideoCGF1Evaluator,
12
+ VideoPhraseApEvaluator,
13
+ VideoPhraseHotaEvaluator,
14
+ VideoTetaEvaluator,
15
+ YTVISPredFileEvaluator,
16
+ )
17
+
18
+
19
+ class VEvalEvaluator:
20
+ def __init__(self, gt_annot_file: str, eval_res_file: str):
21
+ self.gt_annot_file = gt_annot_file
22
+ self.eval_res_file = eval_res_file
23
+ self.evaluators = [
24
+ # mAP
25
+ YTVISPredFileEvaluator(gt_annot_file),
26
+ # Phrase AP
27
+ VideoPhraseApEvaluator(gt_annot_file),
28
+ # TETA
29
+ VideoTetaEvaluator(gt_annot_file, use_mask=True, is_exhaustive=True),
30
+ # HOTA
31
+ VideoPhraseHotaEvaluator(gt_annot_file),
32
+ # cgF1
33
+ VideoCGF1Evaluator(gt_annot_file),
34
+ ]
35
+
36
+ def run_eval(self, pred_file: str):
37
+ dataset_results = {}
38
+ video_np_results = defaultdict(dict)
39
+ for evaluator in self.evaluators:
40
+ d_res, v_np_res = evaluator.evaluate(pred_file)
41
+ dataset_results.update(d_res)
42
+ for (video_id, category_id), res in v_np_res.items():
43
+ video_np_results[(video_id, category_id)].update(res)
44
+
45
+ if len(dataset_results) == 0:
46
+ dataset_results = {"": 0.0}
47
+
48
+ formatted_video_np_results = [
49
+ {"video_id": video_id, "category_id": category_id, **res}
50
+ for (video_id, category_id), res in video_np_results.items()
51
+ ]
52
+ eval_metrics = {
53
+ "dataset_results": dataset_results,
54
+ "video_np_results": formatted_video_np_results,
55
+ }
56
+
57
+ with g_pathmgr.open(self.eval_res_file, "w") as f:
58
+ json.dump(eval_metrics, f)
59
+
60
+ return eval_metrics
61
+
62
+
63
+ def run_main_all(dataset_name, args):
64
+ gt_annot_file = os.path.join(args.gt_annot_dir, dataset_name + ".json")
65
+ pred_file = os.path.join(args.pred_dir, dataset_name + "_preds.json")
66
+ eval_res_file = os.path.join(args.eval_res_dir, dataset_name + "_eval_res.json")
67
+ print(f"=== Running evaluation for Pred {pred_file} vs GT {gt_annot_file} ===")
68
+ veval_evaluator = VEvalEvaluator(
69
+ gt_annot_file=gt_annot_file, eval_res_file=eval_res_file
70
+ )
71
+ _ = veval_evaluator.run_eval(pred_file=pred_file)
72
+
73
+ print(f"=== Results saved to {eval_res_file} ===")
74
+
75
+
76
+ def main_all(args):
77
+ saco_veval_dataset_names = [
78
+ "saco_veval_sav_test",
79
+ "saco_veval_sav_val",
80
+ "saco_veval_yt1b_test",
81
+ "saco_veval_yt1b_val",
82
+ "saco_veval_smartglasses_test",
83
+ "saco_veval_smartglasses_val",
84
+ ]
85
+
86
+ # multiprocessing may not really work as inner evaluator also using multiprocessing
87
+ # so we just for loop
88
+ for dataset_name in saco_veval_dataset_names:
89
+ print(f"=== Running evaluation for dataset {dataset_name} ===")
90
+ run_main_all(dataset_name=dataset_name, args=args)
91
+
92
+
93
+ def main_one(args):
94
+ gt_annot_file = args.gt_annot_file
95
+ pred_file = args.pred_file
96
+ eval_res_file = args.eval_res_file
97
+
98
+ print(f"=== Running evaluation for Pred {pred_file} vs GT {gt_annot_file} ===")
99
+ veval_evaluator = VEvalEvaluator(
100
+ gt_annot_file=gt_annot_file, eval_res_file=eval_res_file
101
+ )
102
+ _ = veval_evaluator.run_eval(pred_file=pred_file)
103
+
104
+ print(f"=== Results saved to {eval_res_file} ===")
105
+
106
+
107
+ def main():
108
+ parser = argparse.ArgumentParser(description="Run video grounding evaluators")
109
+
110
+ # Create subparsers for different commands
111
+ subparsers = parser.add_subparsers(dest="command", required=True)
112
+
113
+ # Run evaluation for all datasets
114
+ all_parser = subparsers.add_parser("all", help="Run evaluation for all datasets")
115
+ all_parser.add_argument(
116
+ "--gt_annot_dir",
117
+ type=str,
118
+ help="Directory that contains the ground truth annotation files",
119
+ )
120
+ all_parser.add_argument(
121
+ "--pred_dir",
122
+ type=str,
123
+ help="Directory that contains the prediction files",
124
+ )
125
+ all_parser.add_argument(
126
+ "--eval_res_dir",
127
+ type=str,
128
+ help="Directory that contains the eval results files",
129
+ )
130
+ all_parser.set_defaults(func=main_all)
131
+
132
+ # Run evaluation for one dataset
133
+ one_parser = subparsers.add_parser("one", help="Run evaluation for one dataset")
134
+ one_parser.add_argument(
135
+ "--gt_annot_file",
136
+ type=str,
137
+ help="Path to the ground truth annotation file",
138
+ )
139
+ one_parser.add_argument(
140
+ "--pred_file",
141
+ type=str,
142
+ help="Path to the prediction file",
143
+ )
144
+ one_parser.add_argument(
145
+ "--eval_res_file",
146
+ type=str,
147
+ help="Path to the eval results file",
148
+ )
149
+ one_parser.set_defaults(func=main_one)
150
+
151
+ # Parse and dispatch
152
+ args = parser.parse_args()
153
+ args.func(args)
154
+
155
+
156
+ if __name__ == "__main__":
157
+ main()
third_party/GraspGen/sam3/sam3/eval/ytvis_eval.py ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+ import copy
5
+ import gc
6
+ import logging
7
+ import os
8
+ from collections import defaultdict
9
+ from operator import xor
10
+ from pathlib import Path
11
+ from typing import List, Optional
12
+
13
+ import numpy as np
14
+ import pycocotools.mask as mask_util
15
+ import torch
16
+ from pycocotools.cocoeval import COCOeval
17
+ from sam3.eval.cgf1_eval import CGF1Eval
18
+ from sam3.eval.coco_eval_offline import convert_to_xywh
19
+ from sam3.model.box_ops import box_xywh_inter_union
20
+ from sam3.train.masks_ops import rle_encode
21
+ from sam3.train.utils import distributed as dist
22
+ from typing_extensions import override
23
+
24
+ try:
25
+ import rapidjson as json
26
+ except ModuleNotFoundError:
27
+ import json
28
+
29
+ from iopath.common.file_io import g_pathmgr
30
+
31
+
32
+ class YTVISevalMixin:
33
+ """
34
+ Identical to COCOeval but adapts computeIoU to compute IoU between tracklets/masklets.
35
+ """
36
+
37
+ @override
38
+ def _prepare(self):
39
+ """
40
+ Copied from cocoeval.py but doesn't convert masks to RLEs (we assume they already are RLEs)
41
+ """
42
+ p = self.params
43
+ if p.useCats:
44
+ gts = self.cocoGt.loadAnns(
45
+ self.cocoGt.getAnnIds(imgIds=p.imgIds, catIds=p.catIds)
46
+ )
47
+ dts = self.cocoDt.loadAnns(
48
+ self.cocoDt.getAnnIds(imgIds=p.imgIds, catIds=p.catIds)
49
+ )
50
+ else:
51
+ gts = self.cocoGt.loadAnns(self.cocoGt.getAnnIds(imgIds=p.imgIds))
52
+ dts = self.cocoDt.loadAnns(self.cocoDt.getAnnIds(imgIds=p.imgIds))
53
+
54
+ # set ignore flag
55
+ for gt in gts:
56
+ gt["ignore"] = gt["ignore"] if "ignore" in gt else 0
57
+ gt["ignore"] = "iscrowd" in gt and gt["iscrowd"]
58
+ if p.iouType == "keypoints":
59
+ gt["ignore"] = (gt["num_keypoints"] == 0) or gt["ignore"]
60
+ self._gts = defaultdict(list) # gt for evaluation
61
+ self._dts = defaultdict(list) # dt for evaluation
62
+ for gt in gts:
63
+ self._gts[gt["image_id"], gt["category_id"]].append(gt)
64
+ for dt in dts:
65
+ self._dts[dt["image_id"], dt["category_id"]].append(dt)
66
+ self.evalImgs = defaultdict(list) # per-image per-category evaluation results
67
+ self.eval = {} # accumulated evaluation results
68
+
69
+ def computeIoU(self, imgId, catId):
70
+ """
71
+ Compute IoU between tracklets. Copied from cocoeval.py but adapted for videos (in YT-VIS format)
72
+ """
73
+ p = self.params
74
+ if p.useCats:
75
+ gt = self._gts[imgId, catId]
76
+ dt = self._dts[imgId, catId]
77
+ else:
78
+ gt = [_ for cId in p.catIds for _ in self._gts[imgId, cId]]
79
+ dt = [_ for cId in p.catIds for _ in self._dts[imgId, cId]]
80
+ if len(gt) == 0 or len(dt) == 0:
81
+ return []
82
+
83
+ # For class mAP and phrase AP evaluation, we sort the detections in descending order of scores (as in COCOeval).
84
+ # For demo F1 evaluation, we DO NOT sort the detections (but match them with GTs via Hungarian matching).
85
+ assert hasattr(self, "sort_inds_by_scores_in_iou"), (
86
+ "subclasses that inherits YTVISevalMixin should set `self.sort_inds_by_scores_in_iou` "
87
+ "(True for class mAP and phrase AP, False for demo F1)"
88
+ )
89
+ if self.sort_inds_by_scores_in_iou:
90
+ inds = np.argsort([-d["score"] for d in dt], kind="mergesort")
91
+ dt = [dt[i] for i in inds]
92
+ if len(dt) > p.maxDets[-1]:
93
+ dt = dt[0 : p.maxDets[-1]]
94
+
95
+ if p.iouType == "segm":
96
+ g = [g["segmentations"] for g in gt]
97
+ d = [d["segmentations"] for d in dt]
98
+ elif p.iouType == "bbox":
99
+ g = [g["bboxes"] for g in gt]
100
+ d = [d["bboxes"] for d in dt]
101
+ else:
102
+ raise Exception("unknown iouType for iou computation")
103
+
104
+ def iou_tracklets(preds, gts):
105
+ preds = torch.tensor(preds)
106
+ gts = torch.tensor(gts)
107
+ inter, union = box_xywh_inter_union(
108
+ preds.unsqueeze(1), gts.unsqueeze(0)
109
+ ) # Num preds x Num GTS x Num frames
110
+ inter = inter.sum(-1)
111
+ union = union.sum(-1)
112
+ assert (union > 0).all(), (
113
+ "There exists a tracklet with zero GTs across time. This is suspicious"
114
+ )
115
+ return inter / union
116
+
117
+ def iou_masklets(preds, gts):
118
+ inter = 0
119
+ union = 0
120
+ for p_i, gt_i in zip(preds, gts):
121
+ if p_i and gt_i:
122
+ # Compute areas of intersection and union
123
+ inter += mask_util.area(
124
+ mask_util.merge([p_i, gt_i], intersect=True)
125
+ )
126
+ union += mask_util.area(
127
+ mask_util.merge([p_i, gt_i], intersect=False)
128
+ )
129
+ elif gt_i:
130
+ union += mask_util.area(gt_i)
131
+ elif p_i:
132
+ union += mask_util.area(p_i)
133
+ if union > 0:
134
+ iou = inter / union
135
+ assert iou >= 0 and iou <= 1, "Encountered an error in IoU computation"
136
+ else:
137
+ assert np.isclose(inter, 0) and np.isclose(union, 0), (
138
+ "Encountered an error in IoU computation"
139
+ )
140
+ iou = 1
141
+ return iou
142
+
143
+ if p.iouType == "segm":
144
+ ious = [[iou_masklets(d_i, g_i) for g_i in g] for d_i in d]
145
+ else:
146
+ ious = iou_tracklets(d, g)
147
+ return np.array(ious)
148
+
149
+
150
+ class YTVISeval(YTVISevalMixin, COCOeval):
151
+ # For class mAP and phrase AP evaluation, we sort the detections in descending order of scores (as in COCOeval).
152
+ sort_inds_by_scores_in_iou = True
153
+
154
+
155
+ class VideoDemoF1Eval(YTVISevalMixin, CGF1Eval):
156
+ # For demo F1 evaluation, we DO NOT sort the detections (but match them with GTs via Hungarian matching).
157
+ sort_inds_by_scores_in_iou = False
158
+
159
+
160
+ class YTVISResultsWriter:
161
+ """
162
+ Gather and dumps predictions in YT-VIS format.
163
+ Expected flow of API calls: reset() -> N * update() -> compute_synced()
164
+ """
165
+
166
+ def __init__(
167
+ self,
168
+ dump_file: str,
169
+ postprocessor,
170
+ gather_pred_via_filesys=False,
171
+ pred_file_evaluators: Optional[List] = None,
172
+ save_per_frame_scores: bool = False,
173
+ write_eval_metrics_file: bool = True,
174
+ eval_metrics_file_suffix: str = ".sam3_eval_metrics",
175
+ ):
176
+ self.dump_file = dump_file
177
+ self.dump = []
178
+ self.postprocessor = postprocessor
179
+ self.gather_pred_via_filesys = gather_pred_via_filesys
180
+ if dist.is_main_process():
181
+ dirname = os.path.dirname(self.dump_file)
182
+ if not os.path.exists(dirname):
183
+ os.makedirs(dirname, exist_ok=True)
184
+ logging.info(f"Creating folder: {dirname}")
185
+
186
+ # the evaluation hooks to be applied to the prediction files
187
+ self.pred_file_evaluators = pred_file_evaluators or []
188
+ self.save_per_frame_scores = save_per_frame_scores
189
+ # in addition to the prediction file, we also write the evaluation metrics
190
+ # for easier debugging and analysis (stored in another eval_metrics_file
191
+ # so that we can keep the dumped prediction file under YT-VIS format)
192
+ self.write_eval_metrics_file = write_eval_metrics_file
193
+ if self.write_eval_metrics_file:
194
+ self.eval_metrics_file = self.dump_file + eval_metrics_file_suffix
195
+ os.makedirs(os.path.dirname(self.eval_metrics_file), exist_ok=True)
196
+
197
+ def _dump_vid_preds(self, results):
198
+ dumped_results = copy.deepcopy(results)
199
+ self.dump.extend(dumped_results)
200
+
201
+ def prepare(self, predictions):
202
+ ytvis_results = []
203
+ for video_id, prediction in predictions.items():
204
+ if len(prediction) == 0:
205
+ continue
206
+ for k in ["boxes", "scores", "labels"]:
207
+ assert k in prediction, (
208
+ f"Expected predictions to have `{k}` key, available keys are {prediction.keys()}"
209
+ )
210
+ if self.save_per_frame_scores:
211
+ assert "per_frame_scores" in prediction, (
212
+ f"Expected predictions to have `per_frame_scores` key, available keys are {prediction.keys()}"
213
+ )
214
+ assert xor("masks" in prediction, "masks_rle" in prediction), (
215
+ f"Expected predictions to have either `masks` key or `masks_rle` key, available keys are {prediction.keys()}"
216
+ )
217
+
218
+ boxes = prediction["boxes"]
219
+ boxes = convert_to_xywh(boxes).tolist()
220
+ scores = prediction["scores"].tolist()
221
+ labels = prediction["labels"].tolist()
222
+ if "masks" in prediction:
223
+ masks = prediction["masks"].squeeze(2)
224
+ assert masks.ndim == 4, (
225
+ "Expected masks to be of shape(N_preds,T_frames,H,W)"
226
+ )
227
+
228
+ areas = [mask.flatten(1).sum(1).tolist() for mask in masks]
229
+ rles = [rle_encode(masklet) for masklet in masks]
230
+
231
+ # memory clean
232
+ del masks
233
+ del prediction["masks"]
234
+ elif "masks_rle" in prediction:
235
+ rles = prediction.pop("masks_rle")
236
+ areas = [
237
+ [0 if rle is None else rle.pop("area") for rle in rles_per_obj]
238
+ for rles_per_obj in rles
239
+ ]
240
+ else:
241
+ raise ValueError(
242
+ "Expected either `masks` or `masks_rle` key in the predictions."
243
+ )
244
+
245
+ new_results = [
246
+ {
247
+ "video_id": video_id,
248
+ "category_id": track_label,
249
+ "bboxes": track_boxes,
250
+ "score": track_score,
251
+ "segmentations": track_masks,
252
+ "areas": track_areas,
253
+ }
254
+ for (
255
+ track_boxes,
256
+ track_masks,
257
+ track_areas,
258
+ track_score,
259
+ track_label,
260
+ ) in zip(boxes, rles, areas, scores, labels)
261
+ ]
262
+ # Optionally, save per-frame scores
263
+ if self.save_per_frame_scores:
264
+ per_frame_scores = prediction["per_frame_scores"].tolist()
265
+ for res, track_per_frame_scores in zip(new_results, per_frame_scores):
266
+ res["per_frame_scores"] = track_per_frame_scores
267
+
268
+ ytvis_results.extend(new_results)
269
+
270
+ return ytvis_results
271
+
272
+ def set_sync_device(self, device: torch.device):
273
+ self._sync_device = device
274
+
275
+ def update(self, *args, **kwargs):
276
+ predictions = self.postprocessor.process_results(*args, **kwargs)
277
+ results = self.prepare(predictions)
278
+ self._dump_vid_preds(results)
279
+
280
+ def _dump_preds(self):
281
+ if not dist.is_main_process():
282
+ self.dump = []
283
+ gc.collect()
284
+ return
285
+ dumped_file = Path(self.dump_file)
286
+ logging.info(f"YTVIS evaluator: Dumping predictions to {dumped_file}")
287
+ with g_pathmgr.open(str(dumped_file), "w") as f:
288
+ json.dump(self.dump, f)
289
+ self.dump = []
290
+ gc.collect()
291
+ return str(dumped_file)
292
+
293
+ def synchronize_between_processes(self):
294
+ logging.info("YT-VIS evaluator: Synchronizing between processes")
295
+ dump_dict = self._dedup_pre_gather(self.dump)
296
+ if self.gather_pred_via_filesys:
297
+ dump_dict_all_gpus = dist.gather_to_rank_0_via_filesys(dump_dict)
298
+ else:
299
+ dump_dict_all_gpus = dist.all_gather(dump_dict, force_cpu=True)
300
+ self.dump = self._dedup_post_gather(dump_dict_all_gpus)
301
+ logging.info(f"Gathered all {len(self.dump)} predictions")
302
+
303
+ def _dedup_pre_gather(self, predictions):
304
+ """
305
+ Organize the predictions as a dict-of-list using (video_id, category_id) as keys
306
+ for deduplication after gathering them across GPUs.
307
+
308
+ During evaluation, PyTorch data loader under `drop_last: False` would wrap
309
+ around the dataset length to be a multiple of world size (GPU num) and duplicate
310
+ the remaining batches. This causes the same test sample to appear simultaneously
311
+ in multiple GPUs, resulting in duplicated predictions being saved into prediction
312
+ files. These duplicates are then counted as false positives under detection mAP
313
+ metrics (since a ground truth can be matched with only one prediction).
314
+
315
+ For example, if there are 4 GPUs and 6 samples [A1, A2, B1, B2, C1, C2], the data
316
+ loader (under `drop_last: False`) would load it by wrapping it around like
317
+ `[A1, A2, B1, B2, C1, C2, *A1*, *A2*]` to make a multiple of 4 and then split it as
318
+
319
+ - GPU 0: A1, C1
320
+ - GPU 1: A2, C2
321
+ - GPU 3: B1, **A1**
322
+ - GPU 4: B2, **A2**
323
+ (as in DistributedSampler in https://github.com/pytorch/pytorch/blob/521588519da9f4876d90ddd7a17c10d0eca89dc6/torch/utils/data/distributed.py#L116-L124)
324
+
325
+ so the predictions on A1 and A2 will occur twice in the final gathered outputs
326
+ in the prediction file (and counted as false positives). This also affects our
327
+ YT-VIS official val evaluation, but to a lesser extent than YT-VIS dev since
328
+ the latter is much smaller and more susceptible to false positives.
329
+
330
+ So we to deduplicate this. The tricky part is that we cannot deduplicate them
331
+ simply using video id, given that we are sharding the classes in each video
332
+ across multiple batches (with 20 prompts per batch) in our "orig_cats" eval dbs.
333
+
334
+ The solution is to deduplicate based on (video_id, category_id) tuple as keys.
335
+ We organize the predictions as a dict-of-list using (video_id, category_id) as
336
+ keys on each GPU, with the list of masklets under this (video_id, category_id)
337
+ on this GPU as values. Then, we all-gather this dict-of-list across GPUs and
338
+ if a key (video_id, category_id) appears in multiple GPUs, we only take the
339
+ prediction masklet list from one GPU.
340
+ """
341
+ prediction_dict = defaultdict(list)
342
+ for p in predictions:
343
+ prediction_dict[(p["video_id"], p["category_id"])].append(p)
344
+ return prediction_dict
345
+
346
+ def _dedup_post_gather(self, list_of_prediction_dict):
347
+ """
348
+ Deduplicate the predictions from all GPUs. See `_dedup_pre_gather` for details.
349
+ """
350
+ dedup_prediction_dict = {}
351
+ duplication_keys = []
352
+ for prediction_dict in list_of_prediction_dict:
353
+ for k, v in prediction_dict.items():
354
+ if k not in dedup_prediction_dict:
355
+ dedup_prediction_dict[k] = v
356
+ else:
357
+ duplication_keys.append(k)
358
+
359
+ logging.info(
360
+ f"skipped {len(duplication_keys)} duplicated predictions in YTVISResultsWriter "
361
+ f"with the following (video_id, category_id) tuples: {duplication_keys}"
362
+ )
363
+ dedup_predictions = sum(dedup_prediction_dict.values(), [])
364
+ return dedup_predictions
365
+
366
+ def compute_synced(
367
+ self,
368
+ ):
369
+ self.synchronize_between_processes()
370
+ dumped_file = self._dump_preds()
371
+ if not dist.is_main_process():
372
+ return {"": 0.0}
373
+
374
+ # run evaluation hooks on the prediction file
375
+ meters = {}
376
+ all_video_np_level_results = defaultdict(dict)
377
+ for evaluator in self.pred_file_evaluators:
378
+ gc.collect()
379
+ results, video_np_level_results = evaluator.evaluate(dumped_file)
380
+ meters.update(results)
381
+ for (video_id, category_id), res in video_np_level_results.items():
382
+ all_video_np_level_results[(video_id, category_id)].update(res)
383
+
384
+ gc.collect()
385
+ if self.write_eval_metrics_file:
386
+ # convert the nested dict of {(video_id, category_id): per_sample_metric_dict}
387
+ # to a list of per-sample metric dicts (with video_id and category_id) for JSON,
388
+ # as JSON doesn't allow using tuples like (video_id, category_id) as dict keys
389
+ video_np_level_metrics = [
390
+ {"video_id": video_id, "category_id": category_id, **res}
391
+ for (video_id, category_id), res in all_video_np_level_results.items()
392
+ ]
393
+ eval_metrics = {
394
+ "dataset_level_metrics": meters,
395
+ "video_np_level_metrics": video_np_level_metrics,
396
+ }
397
+ with g_pathmgr.open(self.eval_metrics_file, "w") as f:
398
+ json.dump(eval_metrics, f)
399
+ logging.info(
400
+ f"YTVIS evaluator: Dumped evaluation metrics to {self.eval_metrics_file}"
401
+ )
402
+
403
+ if len(meters) == 0:
404
+ meters = {"": 0.0}
405
+ return meters
406
+
407
+ def compute(self):
408
+ return {"": 0.0}
409
+
410
+ def reset(self, *args, **kwargs):
411
+ self.dump = []
third_party/GraspGen/sam3/sam3/logger.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+ import logging
5
+ import os
6
+
7
+ LOG_LEVELS = {
8
+ "DEBUG": logging.DEBUG,
9
+ "INFO": logging.INFO,
10
+ "WARNING": logging.WARNING,
11
+ "ERROR": logging.ERROR,
12
+ "CRITICAL": logging.CRITICAL,
13
+ }
14
+
15
+
16
+ class ColoredFormatter(logging.Formatter):
17
+ """A command line formatter with different colors for each level."""
18
+
19
+ def __init__(self):
20
+ super().__init__()
21
+ reset = "\033[0m"
22
+ colors = {
23
+ logging.DEBUG: f"{reset}\033[36m", # cyan,
24
+ logging.INFO: f"{reset}\033[32m", # green
25
+ logging.WARNING: f"{reset}\033[33m", # yellow
26
+ logging.ERROR: f"{reset}\033[31m", # red
27
+ logging.CRITICAL: f"{reset}\033[35m", # magenta
28
+ }
29
+ fmt_str = "{color}%(levelname)s %(asctime)s %(process)d %(filename)s:%(lineno)4d:{reset} %(message)s"
30
+ self.formatters = {
31
+ level: logging.Formatter(fmt_str.format(color=color, reset=reset))
32
+ for level, color in colors.items()
33
+ }
34
+ self.default_formatter = self.formatters[logging.INFO]
35
+
36
+ def format(self, record):
37
+ formatter = self.formatters.get(record.levelno, self.default_formatter)
38
+ return formatter.format(record)
39
+
40
+
41
+ def get_logger(name, level=logging.INFO):
42
+ """A command line logger."""
43
+ if "LOG_LEVEL" in os.environ:
44
+ level = os.environ["LOG_LEVEL"].upper()
45
+ assert level in LOG_LEVELS, (
46
+ f"Invalid LOG_LEVEL: {level}, must be one of {list(LOG_LEVELS.keys())}"
47
+ )
48
+ level = LOG_LEVELS[level]
49
+ logger = logging.getLogger(name)
50
+ logger.setLevel(level)
51
+ logger.propagate = False
52
+ ch = logging.StreamHandler()
53
+ ch.setLevel(level)
54
+ ch.setFormatter(ColoredFormatter())
55
+ logger.addHandler(ch)
56
+ return logger
third_party/GraspGen/sam3/sam3/model_builder.py ADDED
@@ -0,0 +1,802 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ import os
6
+ from typing import Optional
7
+
8
+ import pkg_resources
9
+ import torch
10
+ import torch.nn as nn
11
+ from huggingface_hub import hf_hub_download
12
+ from iopath.common.file_io import g_pathmgr
13
+ from sam3.model.decoder import (
14
+ TransformerDecoder,
15
+ TransformerDecoderLayer,
16
+ TransformerDecoderLayerv2,
17
+ TransformerEncoderCrossAttention,
18
+ )
19
+ from sam3.model.encoder import TransformerEncoderFusion, TransformerEncoderLayer
20
+ from sam3.model.geometry_encoders import SequenceGeometryEncoder
21
+ from sam3.model.maskformer_segmentation import PixelDecoder, UniversalSegmentationHead
22
+ from sam3.model.memory import (
23
+ CXBlock,
24
+ SimpleFuser,
25
+ SimpleMaskDownSampler,
26
+ SimpleMaskEncoder,
27
+ )
28
+ from sam3.model.model_misc import (
29
+ DotProductScoring,
30
+ MLP,
31
+ MultiheadAttentionWrapper as MultiheadAttention,
32
+ TransformerWrapper,
33
+ )
34
+ from sam3.model.necks import Sam3DualViTDetNeck
35
+ from sam3.model.position_encoding import PositionEmbeddingSine
36
+ from sam3.model.sam1_task_predictor import SAM3InteractiveImagePredictor
37
+ from sam3.model.sam3_image import Sam3Image, Sam3ImageOnVideoMultiGPU
38
+ from sam3.model.sam3_tracking_predictor import Sam3TrackerPredictor
39
+ from sam3.model.sam3_video_inference import Sam3VideoInferenceWithInstanceInteractivity
40
+ from sam3.model.sam3_video_predictor import Sam3VideoPredictorMultiGPU
41
+ from sam3.model.text_encoder_ve import VETextEncoder
42
+ from sam3.model.tokenizer_ve import SimpleTokenizer
43
+ from sam3.model.vitdet import ViT
44
+ from sam3.model.vl_combiner import SAM3VLBackbone
45
+ from sam3.sam.transformer import RoPEAttention
46
+
47
+
48
+ # Setup TensorFloat-32 for Ampere GPUs if available
49
+ def _setup_tf32() -> None:
50
+ """Enable TensorFloat-32 for Ampere GPUs if available."""
51
+ if torch.cuda.is_available():
52
+ device_props = torch.cuda.get_device_properties(0)
53
+ if device_props.major >= 8:
54
+ torch.backends.cuda.matmul.allow_tf32 = True
55
+ torch.backends.cudnn.allow_tf32 = True
56
+
57
+
58
+ _setup_tf32()
59
+
60
+
61
+ def _create_position_encoding(precompute_resolution=None):
62
+ """Create position encoding for visual backbone."""
63
+ return PositionEmbeddingSine(
64
+ num_pos_feats=256,
65
+ normalize=True,
66
+ scale=None,
67
+ temperature=10000,
68
+ precompute_resolution=precompute_resolution,
69
+ )
70
+
71
+
72
+ def _create_vit_backbone(compile_mode=None):
73
+ """Create ViT backbone for visual feature extraction."""
74
+ return ViT(
75
+ img_size=1008,
76
+ pretrain_img_size=336,
77
+ patch_size=14,
78
+ embed_dim=1024,
79
+ depth=32,
80
+ num_heads=16,
81
+ mlp_ratio=4.625,
82
+ norm_layer="LayerNorm",
83
+ drop_path_rate=0.1,
84
+ qkv_bias=True,
85
+ use_abs_pos=True,
86
+ tile_abs_pos=True,
87
+ global_att_blocks=(7, 15, 23, 31),
88
+ rel_pos_blocks=(),
89
+ use_rope=True,
90
+ use_interp_rope=True,
91
+ window_size=24,
92
+ pretrain_use_cls_token=True,
93
+ retain_cls_token=False,
94
+ ln_pre=True,
95
+ ln_post=False,
96
+ return_interm_layers=False,
97
+ bias_patch_embed=False,
98
+ compile_mode=compile_mode,
99
+ )
100
+
101
+
102
+ def _create_vit_neck(position_encoding, vit_backbone, enable_inst_interactivity=False):
103
+ """Create ViT neck for feature pyramid."""
104
+ return Sam3DualViTDetNeck(
105
+ position_encoding=position_encoding,
106
+ d_model=256,
107
+ scale_factors=[4.0, 2.0, 1.0, 0.5],
108
+ trunk=vit_backbone,
109
+ add_sam2_neck=enable_inst_interactivity,
110
+ )
111
+
112
+
113
+ def _create_vl_backbone(vit_neck, text_encoder):
114
+ """Create visual-language backbone."""
115
+ return SAM3VLBackbone(visual=vit_neck, text=text_encoder, scalp=1)
116
+
117
+
118
+ def _create_transformer_encoder() -> TransformerEncoderFusion:
119
+ """Create transformer encoder with its layer."""
120
+ encoder_layer = TransformerEncoderLayer(
121
+ activation="relu",
122
+ d_model=256,
123
+ dim_feedforward=2048,
124
+ dropout=0.1,
125
+ pos_enc_at_attn=True,
126
+ pos_enc_at_cross_attn_keys=False,
127
+ pos_enc_at_cross_attn_queries=False,
128
+ pre_norm=True,
129
+ self_attention=MultiheadAttention(
130
+ num_heads=8,
131
+ dropout=0.1,
132
+ embed_dim=256,
133
+ batch_first=True,
134
+ ),
135
+ cross_attention=MultiheadAttention(
136
+ num_heads=8,
137
+ dropout=0.1,
138
+ embed_dim=256,
139
+ batch_first=True,
140
+ ),
141
+ )
142
+
143
+ encoder = TransformerEncoderFusion(
144
+ layer=encoder_layer,
145
+ num_layers=6,
146
+ d_model=256,
147
+ num_feature_levels=1,
148
+ frozen=False,
149
+ use_act_checkpoint=True,
150
+ add_pooled_text_to_img_feat=False,
151
+ pool_text_with_mask=True,
152
+ )
153
+ return encoder
154
+
155
+
156
+ def _create_transformer_decoder() -> TransformerDecoder:
157
+ """Create transformer decoder with its layer."""
158
+ decoder_layer = TransformerDecoderLayer(
159
+ activation="relu",
160
+ d_model=256,
161
+ dim_feedforward=2048,
162
+ dropout=0.1,
163
+ cross_attention=MultiheadAttention(
164
+ num_heads=8,
165
+ dropout=0.1,
166
+ embed_dim=256,
167
+ ),
168
+ n_heads=8,
169
+ use_text_cross_attention=True,
170
+ )
171
+
172
+ decoder = TransformerDecoder(
173
+ layer=decoder_layer,
174
+ num_layers=6,
175
+ num_queries=200,
176
+ return_intermediate=True,
177
+ box_refine=True,
178
+ num_o2m_queries=0,
179
+ dac=True,
180
+ boxRPB="log",
181
+ d_model=256,
182
+ frozen=False,
183
+ interaction_layer=None,
184
+ dac_use_selfatt_ln=True,
185
+ resolution=1008,
186
+ stride=14,
187
+ use_act_checkpoint=True,
188
+ presence_token=True,
189
+ )
190
+ return decoder
191
+
192
+
193
+ def _create_dot_product_scoring():
194
+ """Create dot product scoring module."""
195
+ prompt_mlp = MLP(
196
+ input_dim=256,
197
+ hidden_dim=2048,
198
+ output_dim=256,
199
+ num_layers=2,
200
+ dropout=0.1,
201
+ residual=True,
202
+ out_norm=nn.LayerNorm(256),
203
+ )
204
+ return DotProductScoring(d_model=256, d_proj=256, prompt_mlp=prompt_mlp)
205
+
206
+
207
+ def _create_segmentation_head(compile_mode=None):
208
+ """Create segmentation head with pixel decoder."""
209
+ pixel_decoder = PixelDecoder(
210
+ num_upsampling_stages=3,
211
+ interpolation_mode="nearest",
212
+ hidden_dim=256,
213
+ compile_mode=compile_mode,
214
+ )
215
+
216
+ cross_attend_prompt = MultiheadAttention(
217
+ num_heads=8,
218
+ dropout=0,
219
+ embed_dim=256,
220
+ )
221
+
222
+ segmentation_head = UniversalSegmentationHead(
223
+ hidden_dim=256,
224
+ upsampling_stages=3,
225
+ aux_masks=False,
226
+ presence_head=False,
227
+ dot_product_scorer=None,
228
+ act_ckpt=True,
229
+ cross_attend_prompt=cross_attend_prompt,
230
+ pixel_decoder=pixel_decoder,
231
+ )
232
+ return segmentation_head
233
+
234
+
235
+ def _create_geometry_encoder():
236
+ """Create geometry encoder with all its components."""
237
+ # Create position encoding for geometry encoder
238
+ geo_pos_enc = _create_position_encoding()
239
+ # Create CX block for fuser
240
+ cx_block = CXBlock(
241
+ dim=256,
242
+ kernel_size=7,
243
+ padding=3,
244
+ layer_scale_init_value=1.0e-06,
245
+ use_dwconv=True,
246
+ )
247
+ # Create geometry encoder layer
248
+ geo_layer = TransformerEncoderLayer(
249
+ activation="relu",
250
+ d_model=256,
251
+ dim_feedforward=2048,
252
+ dropout=0.1,
253
+ pos_enc_at_attn=False,
254
+ pre_norm=True,
255
+ self_attention=MultiheadAttention(
256
+ num_heads=8,
257
+ dropout=0.1,
258
+ embed_dim=256,
259
+ batch_first=False,
260
+ ),
261
+ pos_enc_at_cross_attn_queries=False,
262
+ pos_enc_at_cross_attn_keys=True,
263
+ cross_attention=MultiheadAttention(
264
+ num_heads=8,
265
+ dropout=0.1,
266
+ embed_dim=256,
267
+ batch_first=False,
268
+ ),
269
+ )
270
+
271
+ # Create geometry encoder
272
+ input_geometry_encoder = SequenceGeometryEncoder(
273
+ pos_enc=geo_pos_enc,
274
+ encode_boxes_as_points=False,
275
+ points_direct_project=True,
276
+ points_pool=True,
277
+ points_pos_enc=True,
278
+ boxes_direct_project=True,
279
+ boxes_pool=True,
280
+ boxes_pos_enc=True,
281
+ d_model=256,
282
+ num_layers=3,
283
+ layer=geo_layer,
284
+ use_act_ckpt=True,
285
+ add_cls=True,
286
+ add_post_encode_proj=True,
287
+ )
288
+ return input_geometry_encoder
289
+
290
+
291
+ def _create_sam3_model(
292
+ backbone,
293
+ transformer,
294
+ input_geometry_encoder,
295
+ segmentation_head,
296
+ dot_prod_scoring,
297
+ inst_interactive_predictor,
298
+ eval_mode,
299
+ ):
300
+ """Create the SAM3 image model."""
301
+ common_params = {
302
+ "backbone": backbone,
303
+ "transformer": transformer,
304
+ "input_geometry_encoder": input_geometry_encoder,
305
+ "segmentation_head": segmentation_head,
306
+ "num_feature_levels": 1,
307
+ "o2m_mask_predict": True,
308
+ "dot_prod_scoring": dot_prod_scoring,
309
+ "use_instance_query": False,
310
+ "multimask_output": True,
311
+ "inst_interactive_predictor": inst_interactive_predictor,
312
+ }
313
+
314
+ matcher = None
315
+ if not eval_mode:
316
+ from sam3.train.matcher import BinaryHungarianMatcherV2
317
+
318
+ matcher = BinaryHungarianMatcherV2(
319
+ focal=True,
320
+ cost_class=2.0,
321
+ cost_bbox=5.0,
322
+ cost_giou=2.0,
323
+ alpha=0.25,
324
+ gamma=2,
325
+ stable=False,
326
+ )
327
+ common_params["matcher"] = matcher
328
+ model = Sam3Image(**common_params)
329
+
330
+ return model
331
+
332
+
333
+ def _create_tracker_maskmem_backbone():
334
+ """Create the SAM3 Tracker memory encoder."""
335
+ # Position encoding for mask memory backbone
336
+ position_encoding = PositionEmbeddingSine(
337
+ num_pos_feats=64,
338
+ normalize=True,
339
+ scale=None,
340
+ temperature=10000,
341
+ precompute_resolution=1008,
342
+ )
343
+
344
+ # Mask processing components
345
+ mask_downsampler = SimpleMaskDownSampler(
346
+ kernel_size=3, stride=2, padding=1, interpol_size=[1152, 1152]
347
+ )
348
+
349
+ cx_block_layer = CXBlock(
350
+ dim=256,
351
+ kernel_size=7,
352
+ padding=3,
353
+ layer_scale_init_value=1.0e-06,
354
+ use_dwconv=True,
355
+ )
356
+
357
+ fuser = SimpleFuser(layer=cx_block_layer, num_layers=2)
358
+
359
+ maskmem_backbone = SimpleMaskEncoder(
360
+ out_dim=64,
361
+ position_encoding=position_encoding,
362
+ mask_downsampler=mask_downsampler,
363
+ fuser=fuser,
364
+ )
365
+
366
+ return maskmem_backbone
367
+
368
+
369
+ def _create_tracker_transformer():
370
+ """Create the SAM3 Tracker transformer components."""
371
+ # Self attention
372
+ self_attention = RoPEAttention(
373
+ embedding_dim=256,
374
+ num_heads=1,
375
+ downsample_rate=1,
376
+ dropout=0.1,
377
+ rope_theta=10000.0,
378
+ feat_sizes=[72, 72],
379
+ use_fa3=False,
380
+ use_rope_real=False,
381
+ )
382
+
383
+ # Cross attention
384
+ cross_attention = RoPEAttention(
385
+ embedding_dim=256,
386
+ num_heads=1,
387
+ downsample_rate=1,
388
+ dropout=0.1,
389
+ kv_in_dim=64,
390
+ rope_theta=10000.0,
391
+ feat_sizes=[72, 72],
392
+ rope_k_repeat=True,
393
+ use_fa3=False,
394
+ use_rope_real=False,
395
+ )
396
+
397
+ # Encoder layer
398
+ encoder_layer = TransformerDecoderLayerv2(
399
+ cross_attention_first=False,
400
+ activation="relu",
401
+ dim_feedforward=2048,
402
+ dropout=0.1,
403
+ pos_enc_at_attn=False,
404
+ pre_norm=True,
405
+ self_attention=self_attention,
406
+ d_model=256,
407
+ pos_enc_at_cross_attn_keys=True,
408
+ pos_enc_at_cross_attn_queries=False,
409
+ cross_attention=cross_attention,
410
+ )
411
+
412
+ # Encoder
413
+ encoder = TransformerEncoderCrossAttention(
414
+ remove_cross_attention_layers=[],
415
+ batch_first=True,
416
+ d_model=256,
417
+ frozen=False,
418
+ pos_enc_at_input=True,
419
+ layer=encoder_layer,
420
+ num_layers=4,
421
+ use_act_checkpoint=False,
422
+ )
423
+
424
+ # Transformer wrapper
425
+ transformer = TransformerWrapper(
426
+ encoder=encoder,
427
+ decoder=None,
428
+ d_model=256,
429
+ )
430
+
431
+ return transformer
432
+
433
+
434
+ def build_tracker(
435
+ apply_temporal_disambiguation: bool, with_backbone: bool = False, compile_mode=None
436
+ ) -> Sam3TrackerPredictor:
437
+ """
438
+ Build the SAM3 Tracker module for video tracking.
439
+
440
+ Returns:
441
+ Sam3TrackerPredictor: Wrapped SAM3 Tracker module
442
+ """
443
+
444
+ # Create model components
445
+ maskmem_backbone = _create_tracker_maskmem_backbone()
446
+ transformer = _create_tracker_transformer()
447
+ backbone = None
448
+ if with_backbone:
449
+ vision_backbone = _create_vision_backbone(compile_mode=compile_mode)
450
+ backbone = SAM3VLBackbone(scalp=1, visual=vision_backbone, text=None)
451
+ # Create the Tracker module
452
+ model = Sam3TrackerPredictor(
453
+ image_size=1008,
454
+ num_maskmem=7,
455
+ backbone=backbone,
456
+ backbone_stride=14,
457
+ transformer=transformer,
458
+ maskmem_backbone=maskmem_backbone,
459
+ # SAM parameters
460
+ multimask_output_in_sam=True,
461
+ # Evaluation
462
+ forward_backbone_per_frame_for_eval=True,
463
+ trim_past_non_cond_mem_for_eval=False,
464
+ # Multimask
465
+ multimask_output_for_tracking=True,
466
+ multimask_min_pt_num=0,
467
+ multimask_max_pt_num=1,
468
+ # Additional settings
469
+ always_start_from_first_ann_frame=False,
470
+ # Mask overlap
471
+ non_overlap_masks_for_mem_enc=False,
472
+ non_overlap_masks_for_output=False,
473
+ max_cond_frames_in_attn=4,
474
+ offload_output_to_cpu_for_eval=False,
475
+ # SAM decoder settings
476
+ sam_mask_decoder_extra_args={
477
+ "dynamic_multimask_via_stability": True,
478
+ "dynamic_multimask_stability_delta": 0.05,
479
+ "dynamic_multimask_stability_thresh": 0.98,
480
+ },
481
+ clear_non_cond_mem_around_input=True,
482
+ fill_hole_area=0,
483
+ use_memory_selection=apply_temporal_disambiguation,
484
+ )
485
+
486
+ return model
487
+
488
+
489
+ def _create_text_encoder(bpe_path: str) -> VETextEncoder:
490
+ """Create SAM3 text encoder."""
491
+ tokenizer = SimpleTokenizer(bpe_path=bpe_path)
492
+ return VETextEncoder(
493
+ tokenizer=tokenizer,
494
+ d_model=256,
495
+ width=1024,
496
+ heads=16,
497
+ layers=24,
498
+ )
499
+
500
+
501
+ def _create_vision_backbone(
502
+ compile_mode=None, enable_inst_interactivity=True
503
+ ) -> Sam3DualViTDetNeck:
504
+ """Create SAM3 visual backbone with ViT and neck."""
505
+ # Position encoding
506
+ position_encoding = _create_position_encoding(precompute_resolution=1008)
507
+ # ViT backbone
508
+ vit_backbone: ViT = _create_vit_backbone(compile_mode=compile_mode)
509
+ vit_neck: Sam3DualViTDetNeck = _create_vit_neck(
510
+ position_encoding,
511
+ vit_backbone,
512
+ enable_inst_interactivity=enable_inst_interactivity,
513
+ )
514
+ # Visual neck
515
+ return vit_neck
516
+
517
+
518
+ def _create_sam3_transformer(has_presence_token: bool = True) -> TransformerWrapper:
519
+ """Create SAM3 transformer encoder and decoder."""
520
+ encoder: TransformerEncoderFusion = _create_transformer_encoder()
521
+ decoder: TransformerDecoder = _create_transformer_decoder()
522
+
523
+ return TransformerWrapper(encoder=encoder, decoder=decoder, d_model=256)
524
+
525
+
526
+ def _load_checkpoint(
527
+ model,
528
+ checkpoint_path="/home/agilex/.cache/modelscope/hub/models/facebook/sam3/sam3.pt",
529
+ ):
530
+ """Load model checkpoint from file."""
531
+ with g_pathmgr.open(checkpoint_path, "rb") as f:
532
+ ckpt = torch.load(f, map_location="cpu", weights_only=True)
533
+ if "model" in ckpt and isinstance(ckpt["model"], dict):
534
+ ckpt = ckpt["model"]
535
+ sam3_image_ckpt = {
536
+ k.replace("detector.", ""): v for k, v in ckpt.items() if "detector" in k
537
+ }
538
+ if model.inst_interactive_predictor is not None:
539
+ sam3_image_ckpt.update(
540
+ {
541
+ k.replace("tracker.", "inst_interactive_predictor.model."): v
542
+ for k, v in ckpt.items()
543
+ if "tracker" in k
544
+ }
545
+ )
546
+ missing_keys, _ = model.load_state_dict(sam3_image_ckpt, strict=False)
547
+ if len(missing_keys) > 0:
548
+ print(
549
+ f"loaded {checkpoint_path} and found "
550
+ f"missing and/or unexpected keys:\n{missing_keys=}"
551
+ )
552
+
553
+
554
+ def _setup_device_and_mode(model, device, eval_mode):
555
+ """Setup model device and evaluation mode."""
556
+ if device == "cuda":
557
+ model = model.cuda()
558
+ if eval_mode:
559
+ model.eval()
560
+ return model
561
+
562
+
563
+ def build_sam3_image_model(
564
+ bpe_path=None,
565
+ device="cuda" if torch.cuda.is_available() else "cpu",
566
+ eval_mode=True,
567
+ checkpoint_path="/home/agilex/.cache/modelscope/hub/models/facebook/sam3/sam3.pt",
568
+ load_from_HF=True,
569
+ enable_segmentation=True,
570
+ enable_inst_interactivity=False,
571
+ compile=False,
572
+ ):
573
+ """
574
+ Build SAM3 image model
575
+
576
+ Args:
577
+ bpe_path: Path to the BPE tokenizer vocabulary
578
+ device: Device to load the model on ('cuda' or 'cpu')
579
+ eval_mode: Whether to set the model to evaluation mode
580
+ checkpoint_path: Optional path to model checkpoint
581
+ enable_segmentation: Whether to enable segmentation head
582
+ enable_inst_interactivity: Whether to enable instance interactivity (SAM 1 task)
583
+ compile_mode: To enable compilation, set to "default"
584
+
585
+ Returns:
586
+ A SAM3 image model
587
+ """
588
+ if bpe_path is None:
589
+ bpe_path = pkg_resources.resource_filename(
590
+ "sam3", "assets/bpe_simple_vocab_16e6.txt.gz"
591
+ )
592
+
593
+ # Create visual components
594
+ compile_mode = "default" if compile else None
595
+ vision_encoder = _create_vision_backbone(
596
+ compile_mode=compile_mode, enable_inst_interactivity=enable_inst_interactivity
597
+ )
598
+
599
+ # Create text components
600
+ text_encoder = _create_text_encoder(bpe_path)
601
+
602
+ # Create visual-language backbone
603
+ backbone = _create_vl_backbone(vision_encoder, text_encoder)
604
+
605
+ # Create transformer components
606
+ transformer = _create_sam3_transformer()
607
+
608
+ # Create dot product scoring
609
+ dot_prod_scoring = _create_dot_product_scoring()
610
+
611
+ # Create segmentation head if enabled
612
+ segmentation_head = (
613
+ _create_segmentation_head(compile_mode=compile_mode)
614
+ if enable_segmentation
615
+ else None
616
+ )
617
+
618
+ # Create geometry encoder
619
+ input_geometry_encoder = _create_geometry_encoder()
620
+ if enable_inst_interactivity:
621
+ sam3_pvs_base = build_tracker(apply_temporal_disambiguation=False)
622
+ inst_predictor = SAM3InteractiveImagePredictor(sam3_pvs_base)
623
+ else:
624
+ inst_predictor = None
625
+ # Create the SAM3 model
626
+ model = _create_sam3_model(
627
+ backbone,
628
+ transformer,
629
+ input_geometry_encoder,
630
+ segmentation_head,
631
+ dot_prod_scoring,
632
+ inst_predictor,
633
+ eval_mode,
634
+ )
635
+ if load_from_HF and checkpoint_path is None:
636
+ checkpoint_path = download_ckpt_from_hf()
637
+ # Load checkpoint if provided
638
+ if checkpoint_path is not None:
639
+ _load_checkpoint(model, checkpoint_path)
640
+
641
+ # Setup device and mode
642
+ model = _setup_device_and_mode(model, device, eval_mode)
643
+
644
+ return model
645
+
646
+
647
+ def download_ckpt_from_hf():
648
+ SAM3_MODEL_ID = "facebook/sam3"
649
+ SAM3_CKPT_NAME = "sam3.pt"
650
+ SAM3_CFG_NAME = "config.json"
651
+ _ = hf_hub_download(repo_id=SAM3_MODEL_ID, filename=SAM3_CFG_NAME)
652
+ checkpoint_path = hf_hub_download(repo_id=SAM3_MODEL_ID, filename=SAM3_CKPT_NAME)
653
+ return checkpoint_path
654
+
655
+
656
+ def build_sam3_video_model(
657
+ checkpoint_path: Optional[
658
+ str
659
+ ] = "/home/agilex/.cache/modelscope/hub/models/facebook/sam3/sam3.pt",
660
+ load_from_HF=True,
661
+ bpe_path: Optional[str] = None,
662
+ has_presence_token: bool = True,
663
+ geo_encoder_use_img_cross_attn: bool = True,
664
+ strict_state_dict_loading: bool = True,
665
+ apply_temporal_disambiguation: bool = True,
666
+ device="cuda" if torch.cuda.is_available() else "cpu",
667
+ compile=False,
668
+ ) -> Sam3VideoInferenceWithInstanceInteractivity:
669
+ """
670
+ Build SAM3 dense tracking model.
671
+
672
+ Args:
673
+ checkpoint_path: Optional path to checkpoint file
674
+ bpe_path: Path to the BPE tokenizer file
675
+
676
+ Returns:
677
+ Sam3VideoInferenceWithInstanceInteractivity: The instantiated dense tracking model
678
+ """
679
+ if bpe_path is None:
680
+ bpe_path = pkg_resources.resource_filename(
681
+ "sam3", "assets/bpe_simple_vocab_16e6.txt.gz"
682
+ )
683
+
684
+ # Build Tracker module
685
+ tracker = build_tracker(apply_temporal_disambiguation=apply_temporal_disambiguation)
686
+
687
+ # Build Detector components
688
+ visual_neck = _create_vision_backbone()
689
+ text_encoder = _create_text_encoder(bpe_path)
690
+ backbone = SAM3VLBackbone(scalp=1, visual=visual_neck, text=text_encoder)
691
+ transformer = _create_sam3_transformer(has_presence_token=has_presence_token)
692
+ segmentation_head: UniversalSegmentationHead = _create_segmentation_head()
693
+ input_geometry_encoder = _create_geometry_encoder()
694
+
695
+ # Create main dot product scoring
696
+ main_dot_prod_mlp = MLP(
697
+ input_dim=256,
698
+ hidden_dim=2048,
699
+ output_dim=256,
700
+ num_layers=2,
701
+ dropout=0.1,
702
+ residual=True,
703
+ out_norm=nn.LayerNorm(256),
704
+ )
705
+ main_dot_prod_scoring = DotProductScoring(
706
+ d_model=256, d_proj=256, prompt_mlp=main_dot_prod_mlp
707
+ )
708
+
709
+ # Build Detector module
710
+ detector = Sam3ImageOnVideoMultiGPU(
711
+ num_feature_levels=1,
712
+ backbone=backbone,
713
+ transformer=transformer,
714
+ segmentation_head=segmentation_head,
715
+ semantic_segmentation_head=None,
716
+ input_geometry_encoder=input_geometry_encoder,
717
+ use_early_fusion=True,
718
+ use_dot_prod_scoring=True,
719
+ dot_prod_scoring=main_dot_prod_scoring,
720
+ supervise_joint_box_scores=has_presence_token,
721
+ )
722
+
723
+ # Build the main SAM3 video model
724
+ if apply_temporal_disambiguation:
725
+ model = Sam3VideoInferenceWithInstanceInteractivity(
726
+ detector=detector,
727
+ tracker=tracker,
728
+ score_threshold_detection=0.5,
729
+ assoc_iou_thresh=0.1,
730
+ det_nms_thresh=0.1,
731
+ new_det_thresh=0.7,
732
+ hotstart_delay=15,
733
+ hotstart_unmatch_thresh=8,
734
+ hotstart_dup_thresh=8,
735
+ suppress_unmatched_only_within_hotstart=True,
736
+ min_trk_keep_alive=-1,
737
+ max_trk_keep_alive=30,
738
+ init_trk_keep_alive=30,
739
+ suppress_overlapping_based_on_recent_occlusion_threshold=0.7,
740
+ suppress_det_close_to_boundary=False,
741
+ fill_hole_area=16,
742
+ recondition_every_nth_frame=16,
743
+ masklet_confirmation_enable=False,
744
+ decrease_trk_keep_alive_for_empty_masklets=False,
745
+ image_size=1008,
746
+ image_mean=(0.5, 0.5, 0.5),
747
+ image_std=(0.5, 0.5, 0.5),
748
+ compile_model=compile,
749
+ )
750
+ else:
751
+ # a version without any heuristics for ablation studies
752
+ model = Sam3VideoInferenceWithInstanceInteractivity(
753
+ detector=detector,
754
+ tracker=tracker,
755
+ score_threshold_detection=0.5,
756
+ assoc_iou_thresh=0.1,
757
+ det_nms_thresh=0.1,
758
+ new_det_thresh=0.7,
759
+ hotstart_delay=0,
760
+ hotstart_unmatch_thresh=0,
761
+ hotstart_dup_thresh=0,
762
+ suppress_unmatched_only_within_hotstart=True,
763
+ min_trk_keep_alive=-1,
764
+ max_trk_keep_alive=30,
765
+ init_trk_keep_alive=30,
766
+ suppress_overlapping_based_on_recent_occlusion_threshold=0.7,
767
+ suppress_det_close_to_boundary=False,
768
+ fill_hole_area=16,
769
+ recondition_every_nth_frame=0,
770
+ masklet_confirmation_enable=False,
771
+ decrease_trk_keep_alive_for_empty_masklets=False,
772
+ image_size=1008,
773
+ image_mean=(0.5, 0.5, 0.5),
774
+ image_std=(0.5, 0.5, 0.5),
775
+ compile_model=compile,
776
+ )
777
+
778
+ # Load checkpoint if provided
779
+ if load_from_HF and checkpoint_path is None:
780
+ checkpoint_path = download_ckpt_from_hf()
781
+ if checkpoint_path is not None:
782
+ with g_pathmgr.open(checkpoint_path, "rb") as f:
783
+ ckpt = torch.load(f, map_location="cpu", weights_only=True)
784
+ if "model" in ckpt and isinstance(ckpt["model"], dict):
785
+ ckpt = ckpt["model"]
786
+
787
+ missing_keys, unexpected_keys = model.load_state_dict(
788
+ ckpt, strict=strict_state_dict_loading
789
+ )
790
+ if missing_keys:
791
+ print(f"Missing keys: {missing_keys}")
792
+ if unexpected_keys:
793
+ print(f"Unexpected keys: {unexpected_keys}")
794
+
795
+ model.to(device=device)
796
+ return model
797
+
798
+
799
+ def build_sam3_video_predictor(*model_args, gpus_to_use=None, **model_kwargs):
800
+ return Sam3VideoPredictorMultiGPU(
801
+ *model_args, gpus_to_use=gpus_to_use, **model_kwargs
802
+ )
third_party/GraspGen/sam3/sam3/visualization_utils.py ADDED
@@ -0,0 +1,943 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+ import json
5
+ import os
6
+ import subprocess
7
+ from pathlib import Path
8
+
9
+ import cv2
10
+ import matplotlib.patches as patches
11
+ import matplotlib.pyplot as plt
12
+ import numpy as np
13
+ import pandas as pd
14
+ import pycocotools.mask as mask_utils
15
+ import torch
16
+ from matplotlib.colors import to_rgb
17
+ from PIL import Image
18
+ from skimage.color import lab2rgb, rgb2lab
19
+ from sklearn.cluster import KMeans
20
+ from torchvision.ops import masks_to_boxes
21
+ from tqdm import tqdm
22
+
23
+
24
+ def generate_colors(n_colors=256, n_samples=5000):
25
+ # Step 1: Random RGB samples
26
+ np.random.seed(42)
27
+ rgb = np.random.rand(n_samples, 3)
28
+ # Step 2: Convert to LAB for perceptual uniformity
29
+ # print(f"Converting {n_samples} RGB samples to LAB color space...")
30
+ lab = rgb2lab(rgb.reshape(1, -1, 3)).reshape(-1, 3)
31
+ # print("Conversion to LAB complete.")
32
+ # Step 3: k-means clustering in LAB
33
+ kmeans = KMeans(n_clusters=n_colors, n_init=10)
34
+ # print(f"Fitting KMeans with {n_colors} clusters on {n_samples} samples...")
35
+ kmeans.fit(lab)
36
+ # print("KMeans fitting complete.")
37
+ centers_lab = kmeans.cluster_centers_
38
+ # Step 4: Convert LAB back to RGB
39
+ colors_rgb = lab2rgb(centers_lab.reshape(1, -1, 3)).reshape(-1, 3)
40
+ colors_rgb = np.clip(colors_rgb, 0, 1)
41
+ return colors_rgb
42
+
43
+
44
+ COLORS = generate_colors(n_colors=128, n_samples=5000)
45
+
46
+
47
+ def show_img_tensor(img_batch, vis_img_idx=0):
48
+ MEAN_IMG = np.array([0.5, 0.5, 0.5])
49
+ STD_IMG = np.array([0.5, 0.5, 0.5])
50
+ im_tensor = img_batch[vis_img_idx].detach().cpu()
51
+ assert im_tensor.dim() == 3
52
+ im_tensor = im_tensor.numpy().transpose((1, 2, 0))
53
+ im_tensor = (im_tensor * STD_IMG) + MEAN_IMG
54
+ im_tensor = np.clip(im_tensor, 0, 1)
55
+ plt.imshow(im_tensor)
56
+
57
+
58
+ def draw_box_on_image(image, box, color=(0, 255, 0)):
59
+ """
60
+ Draws a rectangle on a given PIL image using the provided box coordinates in xywh format.
61
+ :param image: PIL.Image - The image on which to draw the rectangle.
62
+ :param box: tuple - A tuple (x, y, w, h) representing the top-left corner, width, and height of the rectangle.
63
+ :param color: tuple - A tuple (R, G, B) representing the color of the rectangle. Default is red.
64
+ :return: PIL.Image - The image with the rectangle drawn on it.
65
+ """
66
+ # Ensure the image is in RGB mode
67
+ image = image.convert("RGB")
68
+ # Unpack the box coordinates
69
+ x, y, w, h = box
70
+ x, y, w, h = int(x), int(y), int(w), int(h)
71
+ # Get the pixel data
72
+ pixels = image.load()
73
+ # Draw the top and bottom edges
74
+ for i in range(x, x + w):
75
+ pixels[i, y] = color
76
+ pixels[i, y + h - 1] = color
77
+ pixels[i, y + 1] = color
78
+ pixels[i, y + h] = color
79
+ pixels[i, y - 1] = color
80
+ pixels[i, y + h - 2] = color
81
+ # Draw the left and right edges
82
+ for j in range(y, y + h):
83
+ pixels[x, j] = color
84
+ pixels[x + 1, j] = color
85
+ pixels[x - 1, j] = color
86
+ pixels[x + w - 1, j] = color
87
+ pixels[x + w, j] = color
88
+ pixels[x + w - 2, j] = color
89
+ return image
90
+
91
+
92
+ def plot_bbox(
93
+ img_height,
94
+ img_width,
95
+ box,
96
+ box_format="XYXY",
97
+ relative_coords=True,
98
+ color="r",
99
+ linestyle="solid",
100
+ text=None,
101
+ ax=None,
102
+ ):
103
+ if box_format == "XYXY":
104
+ x, y, x2, y2 = box
105
+ w = x2 - x
106
+ h = y2 - y
107
+ elif box_format == "XYWH":
108
+ x, y, w, h = box
109
+ elif box_format == "CxCyWH":
110
+ cx, cy, w, h = box
111
+ x = cx - w / 2
112
+ y = cy - h / 2
113
+ else:
114
+ raise RuntimeError(f"Invalid box_format {box_format}")
115
+
116
+ if relative_coords:
117
+ x *= img_width
118
+ w *= img_width
119
+ y *= img_height
120
+ h *= img_height
121
+
122
+ if ax is None:
123
+ ax = plt.gca()
124
+ rect = patches.Rectangle(
125
+ (x, y),
126
+ w,
127
+ h,
128
+ linewidth=1.5,
129
+ edgecolor=color,
130
+ facecolor="none",
131
+ linestyle=linestyle,
132
+ )
133
+ ax.add_patch(rect)
134
+ if text is not None:
135
+ facecolor = "w"
136
+ ax.text(
137
+ x,
138
+ y - 5,
139
+ text,
140
+ color=color,
141
+ weight="bold",
142
+ fontsize=8,
143
+ bbox={"facecolor": facecolor, "alpha": 0.75, "pad": 2},
144
+ )
145
+
146
+
147
+ def plot_mask(mask, color="r", ax=None):
148
+ im_h, im_w = mask.shape
149
+ mask_img = np.zeros((im_h, im_w, 4), dtype=np.float32)
150
+ mask_img[..., :3] = to_rgb(color)
151
+ mask_img[..., 3] = mask * 0.5
152
+ # Use the provided ax or the current axis
153
+ if ax is None:
154
+ ax = plt.gca()
155
+ ax.imshow(mask_img)
156
+
157
+
158
+ def normalize_bbox(bbox_xywh, img_w, img_h):
159
+ # Assumes bbox_xywh is in XYWH format
160
+ if isinstance(bbox_xywh, list):
161
+ assert (
162
+ len(bbox_xywh) == 4
163
+ ), "bbox_xywh list must have 4 elements. Batching not support except for torch tensors."
164
+ normalized_bbox = bbox_xywh.copy()
165
+ normalized_bbox[0] /= img_w
166
+ normalized_bbox[1] /= img_h
167
+ normalized_bbox[2] /= img_w
168
+ normalized_bbox[3] /= img_h
169
+ else:
170
+ assert isinstance(
171
+ bbox_xywh, torch.Tensor
172
+ ), "Only torch tensors are supported for batching."
173
+ normalized_bbox = bbox_xywh.clone()
174
+ assert (
175
+ normalized_bbox.size(-1) == 4
176
+ ), "bbox_xywh tensor must have last dimension of size 4."
177
+ normalized_bbox[..., 0] /= img_w
178
+ normalized_bbox[..., 1] /= img_h
179
+ normalized_bbox[..., 2] /= img_w
180
+ normalized_bbox[..., 3] /= img_h
181
+ return normalized_bbox
182
+
183
+
184
+ def visualize_frame_output(frame_idx, video_frames, outputs, figsize=(12, 8)):
185
+ plt.figure(figsize=figsize)
186
+ plt.title(f"frame {frame_idx}")
187
+ img = load_frame(video_frames[frame_idx])
188
+ img_H, img_W, _ = img.shape
189
+ plt.imshow(img)
190
+ for i in range(len(outputs["out_probs"])):
191
+ box_xywh = outputs["out_boxes_xywh"][i]
192
+ prob = outputs["out_probs"][i]
193
+ obj_id = outputs["out_obj_ids"][i]
194
+ binary_mask = outputs["out_binary_masks"][i]
195
+ color = COLORS[obj_id % len(COLORS)]
196
+ plot_bbox(
197
+ img_H,
198
+ img_W,
199
+ box_xywh,
200
+ text=f"(id={obj_id}, {prob=:.2f})",
201
+ box_format="XYWH",
202
+ color=color,
203
+ )
204
+ plot_mask(binary_mask, color=color)
205
+
206
+
207
+ def visualize_formatted_frame_output(
208
+ frame_idx,
209
+ video_frames,
210
+ outputs_list,
211
+ titles=None,
212
+ points_list=None,
213
+ points_labels_list=None,
214
+ figsize=(12, 8),
215
+ title_suffix="",
216
+ prompt_info=None,
217
+ ):
218
+ """Visualize up to three sets of segmentation masks on a video frame.
219
+
220
+ Args:
221
+ frame_idx: Frame index to visualize
222
+ image_files: List of image file paths
223
+ outputs_list: List of {frame_idx: {obj_id: mask_tensor}} or single dict {obj_id: mask_tensor}
224
+ titles: List of titles for each set of outputs_list
225
+ points_list: Optional list of point coordinates
226
+ points_labels_list: Optional list of point labels
227
+ figsize: Figure size tuple
228
+ save: Whether to save the visualization to file
229
+ output_dir: Base output directory when saving
230
+ scenario_name: Scenario name for organizing saved files
231
+ title_suffix: Additional title suffix
232
+ prompt_info: Dictionary with prompt information (boxes, points, etc.)
233
+ """
234
+ # Handle single output dict case
235
+ if isinstance(outputs_list, dict) and frame_idx in outputs_list:
236
+ # This is a single outputs dict with frame indices as keys
237
+ outputs_list = [outputs_list]
238
+ elif isinstance(outputs_list, dict) and not any(
239
+ isinstance(k, int) for k in outputs_list.keys()
240
+ ):
241
+ # This is a single frame's outputs {obj_id: mask}
242
+ single_frame_outputs = {frame_idx: outputs_list}
243
+ outputs_list = [single_frame_outputs]
244
+
245
+ num_outputs = len(outputs_list)
246
+ if titles is None:
247
+ titles = [f"Set {i + 1}" for i in range(num_outputs)]
248
+ assert (
249
+ len(titles) == num_outputs
250
+ ), "length of `titles` should match that of `outputs_list` if not None."
251
+
252
+ _, axes = plt.subplots(1, num_outputs, figsize=figsize)
253
+ if num_outputs == 1:
254
+ axes = [axes] # Make it iterable
255
+
256
+ img = load_frame(video_frames[frame_idx])
257
+ img_H, img_W, _ = img.shape
258
+
259
+ for idx in range(num_outputs):
260
+ ax, outputs_set, ax_title = axes[idx], outputs_list[idx], titles[idx]
261
+ ax.set_title(f"Frame {frame_idx} - {ax_title}{title_suffix}")
262
+ ax.imshow(img)
263
+
264
+ if frame_idx in outputs_set:
265
+ _outputs = outputs_set[frame_idx]
266
+ else:
267
+ print(f"Warning: Frame {frame_idx} not found in outputs_set")
268
+ continue
269
+
270
+ if prompt_info and frame_idx == 0: # Show prompts on first frame
271
+ if "boxes" in prompt_info:
272
+ for box in prompt_info["boxes"]:
273
+ # box is in [x, y, w, h] normalized format
274
+ x, y, w, h = box
275
+ plot_bbox(
276
+ img_H,
277
+ img_W,
278
+ [x, y, x + w, y + h], # Convert to XYXY
279
+ box_format="XYXY",
280
+ relative_coords=True,
281
+ color="yellow",
282
+ linestyle="dashed",
283
+ text="PROMPT BOX",
284
+ ax=ax,
285
+ )
286
+
287
+ if "points" in prompt_info and "point_labels" in prompt_info:
288
+ points = np.array(prompt_info["points"])
289
+ labels = np.array(prompt_info["point_labels"])
290
+ # Convert normalized to pixel coordinates
291
+ points_pixel = points * np.array([img_W, img_H])
292
+
293
+ # Draw positive points (green stars)
294
+ pos_points = points_pixel[labels == 1]
295
+ if len(pos_points) > 0:
296
+ ax.scatter(
297
+ pos_points[:, 0],
298
+ pos_points[:, 1],
299
+ color="lime",
300
+ marker="*",
301
+ s=200,
302
+ edgecolor="white",
303
+ linewidth=2,
304
+ label="Positive Points",
305
+ zorder=10,
306
+ )
307
+
308
+ # Draw negative points (red stars)
309
+ neg_points = points_pixel[labels == 0]
310
+ if len(neg_points) > 0:
311
+ ax.scatter(
312
+ neg_points[:, 0],
313
+ neg_points[:, 1],
314
+ color="red",
315
+ marker="*",
316
+ s=200,
317
+ edgecolor="white",
318
+ linewidth=2,
319
+ label="Negative Points",
320
+ zorder=10,
321
+ )
322
+
323
+ objects_drawn = 0
324
+ for obj_id, binary_mask in _outputs.items():
325
+ mask_sum = (
326
+ binary_mask.sum()
327
+ if hasattr(binary_mask, "sum")
328
+ else np.sum(binary_mask)
329
+ )
330
+
331
+ if mask_sum > 0: # Only draw if mask has content
332
+ # Convert to torch tensor if it's not already
333
+ if not isinstance(binary_mask, torch.Tensor):
334
+ binary_mask = torch.tensor(binary_mask)
335
+
336
+ # Find bounding box from mask
337
+ if binary_mask.any():
338
+ box_xyxy = masks_to_boxes(binary_mask.unsqueeze(0)).squeeze()
339
+ box_xyxy = normalize_bbox(box_xyxy, img_W, img_H)
340
+ else:
341
+ # Fallback: create a small box at center
342
+ box_xyxy = [0.45, 0.45, 0.55, 0.55]
343
+
344
+ color = COLORS[obj_id % len(COLORS)]
345
+
346
+ plot_bbox(
347
+ img_H,
348
+ img_W,
349
+ box_xyxy,
350
+ text=f"(id={obj_id})",
351
+ box_format="XYXY",
352
+ color=color,
353
+ ax=ax,
354
+ )
355
+
356
+ # Convert back to numpy for plotting
357
+ mask_np = (
358
+ binary_mask.numpy()
359
+ if isinstance(binary_mask, torch.Tensor)
360
+ else binary_mask
361
+ )
362
+ plot_mask(mask_np, color=color, ax=ax)
363
+ objects_drawn += 1
364
+
365
+ if objects_drawn == 0:
366
+ ax.text(
367
+ 0.5,
368
+ 0.5,
369
+ "No objects detected",
370
+ transform=ax.transAxes,
371
+ fontsize=16,
372
+ ha="center",
373
+ va="center",
374
+ color="red",
375
+ weight="bold",
376
+ )
377
+
378
+ # Draw additional points if provided
379
+ if points_list is not None and points_list[idx] is not None:
380
+ show_points(
381
+ points_list[idx], points_labels_list[idx], ax=ax, marker_size=200
382
+ )
383
+
384
+ ax.axis("off")
385
+
386
+ plt.tight_layout()
387
+ plt.show()
388
+
389
+
390
+ def render_masklet_frame(img, outputs, frame_idx=None, alpha=0.5):
391
+ """
392
+ Overlays masklets and bounding boxes on a single image frame.
393
+ Args:
394
+ img: np.ndarray, shape (H, W, 3), uint8 or float32 in [0,255] or [0,1]
395
+ outputs: dict with keys: out_boxes_xywh, out_probs, out_obj_ids, out_binary_masks
396
+ frame_idx: int or None, for overlaying frame index text
397
+ alpha: float, mask overlay alpha
398
+ Returns:
399
+ overlay: np.ndarray, shape (H, W, 3), uint8
400
+ """
401
+ if img.dtype == np.float32 or img.max() <= 1.0:
402
+ img = (img * 255).astype(np.uint8)
403
+ img = img[..., :3] # drop alpha if present
404
+ height, width = img.shape[:2]
405
+ overlay = img.copy()
406
+
407
+ for i in range(len(outputs["out_probs"])):
408
+ obj_id = outputs["out_obj_ids"][i]
409
+ color = COLORS[obj_id % len(COLORS)]
410
+ color255 = (color * 255).astype(np.uint8)
411
+ mask = outputs["out_binary_masks"][i]
412
+ if mask.shape != img.shape[:2]:
413
+ mask = cv2.resize(
414
+ mask.astype(np.float32),
415
+ (img.shape[1], img.shape[0]),
416
+ interpolation=cv2.INTER_NEAREST,
417
+ )
418
+ mask_bool = mask > 0.5
419
+ for c in range(3):
420
+ overlay[..., c][mask_bool] = (
421
+ alpha * color255[c] + (1 - alpha) * overlay[..., c][mask_bool]
422
+ ).astype(np.uint8)
423
+
424
+ # Draw bounding boxes and text
425
+ for i in range(len(outputs["out_probs"])):
426
+ box_xywh = outputs["out_boxes_xywh"][i]
427
+ obj_id = outputs["out_obj_ids"][i]
428
+ prob = outputs["out_probs"][i]
429
+ color = COLORS[obj_id % len(COLORS)]
430
+ color255 = tuple(int(x * 255) for x in color)
431
+ x, y, w, h = box_xywh
432
+ x1 = int(x * width)
433
+ y1 = int(y * height)
434
+ x2 = int((x + w) * width)
435
+ y2 = int((y + h) * height)
436
+ cv2.rectangle(overlay, (x1, y1), (x2, y2), color255, 2)
437
+ if prob is not None:
438
+ label = f"id={obj_id}, p={prob:.2f}"
439
+ else:
440
+ label = f"id={obj_id}"
441
+ cv2.putText(
442
+ overlay,
443
+ label,
444
+ (x1, max(y1 - 10, 0)),
445
+ cv2.FONT_HERSHEY_SIMPLEX,
446
+ 0.5,
447
+ color255,
448
+ 1,
449
+ cv2.LINE_AA,
450
+ )
451
+
452
+ # Overlay frame index at the top-left corner
453
+ if frame_idx is not None:
454
+ cv2.putText(
455
+ overlay,
456
+ f"Frame {frame_idx}",
457
+ (10, 30),
458
+ cv2.FONT_HERSHEY_SIMPLEX,
459
+ 1.0,
460
+ (255, 255, 255),
461
+ 2,
462
+ cv2.LINE_AA,
463
+ )
464
+
465
+ return overlay
466
+
467
+
468
+ def save_masklet_video(video_frames, outputs, out_path, alpha=0.5, fps=10):
469
+ # Each outputs dict has keys: "out_boxes_xywh", "out_probs", "out_obj_ids", "out_binary_masks"
470
+ # video_frames: list of video frame data, same length as outputs_list
471
+
472
+ # Read first frame to get size
473
+ first_img = load_frame(video_frames[0])
474
+ height, width = first_img.shape[:2]
475
+ if first_img.dtype == np.float32 or first_img.max() <= 1.0:
476
+ first_img = (first_img * 255).astype(np.uint8)
477
+ # Use 'mp4v' for best compatibility with VSCode playback (.mp4 files)
478
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
479
+ writer = cv2.VideoWriter("temp.mp4", fourcc, fps, (width, height))
480
+
481
+ outputs_list = [
482
+ (video_frames[frame_idx], frame_idx, outputs[frame_idx])
483
+ for frame_idx in sorted(outputs.keys())
484
+ ]
485
+
486
+ for frame, frame_idx, frame_outputs in tqdm(outputs_list):
487
+ img = load_frame(frame)
488
+ overlay = render_masklet_frame(
489
+ img, frame_outputs, frame_idx=frame_idx, alpha=alpha
490
+ )
491
+ writer.write(cv2.cvtColor(overlay, cv2.COLOR_RGB2BGR))
492
+
493
+ writer.release()
494
+
495
+ # Re-encode the video for VSCode compatibility using ffmpeg
496
+ subprocess.run(["ffmpeg", "-y", "-i", "temp.mp4", out_path])
497
+ print(f"Re-encoded video saved to {out_path}")
498
+
499
+ os.remove("temp.mp4") # Clean up temporary file
500
+
501
+
502
+ def save_masklet_image(frame, outputs, out_path, alpha=0.5, frame_idx=None):
503
+ """
504
+ Save a single image with masklet overlays.
505
+ """
506
+ img = load_frame(frame)
507
+ overlay = render_masklet_frame(img, outputs, frame_idx=frame_idx, alpha=alpha)
508
+ Image.fromarray(overlay).save(out_path)
509
+ print(f"Overlay image saved to {out_path}")
510
+
511
+
512
+ def prepare_masks_for_visualization(frame_to_output):
513
+ # frame_to_obj_masks --> {frame_idx: {'output_probs': np.array, `out_obj_ids`: np.array, `out_binary_masks`: np.array}}
514
+ for frame_idx, out in frame_to_output.items():
515
+ _processed_out = {}
516
+ for idx, obj_id in enumerate(out["out_obj_ids"].tolist()):
517
+ if out["out_binary_masks"][idx].any():
518
+ _processed_out[obj_id] = out["out_binary_masks"][idx]
519
+ frame_to_output[frame_idx] = _processed_out
520
+ return frame_to_output
521
+
522
+
523
+ def convert_coco_to_masklet_format(
524
+ annotations, img_info, is_prediction=False, score_threshold=0.5
525
+ ):
526
+ """
527
+ Convert COCO format annotations to format expected by render_masklet_frame
528
+ """
529
+ outputs = {
530
+ "out_boxes_xywh": [],
531
+ "out_probs": [],
532
+ "out_obj_ids": [],
533
+ "out_binary_masks": [],
534
+ }
535
+
536
+ img_h, img_w = img_info["height"], img_info["width"]
537
+
538
+ for idx, ann in enumerate(annotations):
539
+ # Get bounding box in relative XYWH format
540
+ if "bbox" in ann:
541
+ bbox = ann["bbox"]
542
+ if max(bbox) > 1.0: # Convert absolute to relative coordinates
543
+ bbox = [
544
+ bbox[0] / img_w,
545
+ bbox[1] / img_h,
546
+ bbox[2] / img_w,
547
+ bbox[3] / img_h,
548
+ ]
549
+ else:
550
+ mask = mask_utils.decode(ann["segmentation"])
551
+ rows = np.any(mask, axis=1)
552
+ cols = np.any(mask, axis=0)
553
+ if np.any(rows) and np.any(cols):
554
+ rmin, rmax = np.where(rows)[0][[0, -1]]
555
+ cmin, cmax = np.where(cols)[0][[0, -1]]
556
+ # Convert to relative XYWH
557
+ bbox = [
558
+ cmin / img_w,
559
+ rmin / img_h,
560
+ (cmax - cmin + 1) / img_w,
561
+ (rmax - rmin + 1) / img_h,
562
+ ]
563
+ else:
564
+ bbox = [0, 0, 0, 0]
565
+
566
+ outputs["out_boxes_xywh"].append(bbox)
567
+
568
+ # Get probability/score
569
+ if is_prediction:
570
+ prob = ann["score"]
571
+ else:
572
+ prob = 1.0 # GT has no probability
573
+ outputs["out_probs"].append(prob)
574
+
575
+ outputs["out_obj_ids"].append(idx)
576
+ mask = mask_utils.decode(ann["segmentation"])
577
+ mask = (mask > score_threshold).astype(np.uint8)
578
+
579
+ outputs["out_binary_masks"].append(mask)
580
+
581
+ return outputs
582
+
583
+
584
+ def save_side_by_side_visualization(img, gt_anns, pred_anns, noun_phrase):
585
+ """
586
+ Create side-by-side visualization of GT and predictions
587
+ """
588
+
589
+ # Create side-by-side visualization
590
+ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 7))
591
+
592
+ main_title = f"Noun phrase: '{noun_phrase}'"
593
+ fig.suptitle(main_title, fontsize=16, fontweight="bold")
594
+
595
+ gt_overlay = render_masklet_frame(img, gt_anns, alpha=0.5)
596
+ ax1.imshow(gt_overlay)
597
+ ax1.set_title("Ground Truth", fontsize=14, fontweight="bold")
598
+ ax1.axis("off")
599
+
600
+ pred_overlay = render_masklet_frame(img, pred_anns, alpha=0.5)
601
+ ax2.imshow(pred_overlay)
602
+ ax2.set_title("Predictions", fontsize=14, fontweight="bold")
603
+ ax2.axis("off")
604
+
605
+ plt.subplots_adjust(top=0.88)
606
+ plt.tight_layout()
607
+
608
+
609
+ def bitget(val, idx):
610
+ return (val >> idx) & 1
611
+
612
+
613
+ def pascal_color_map():
614
+ colormap = np.zeros((512, 3), dtype=int)
615
+ ind = np.arange(512, dtype=int)
616
+ for shift in reversed(list(range(8))):
617
+ for channel in range(3):
618
+ colormap[:, channel] |= bitget(ind, channel) << shift
619
+ ind >>= 3
620
+
621
+ return colormap.astype(np.uint8)
622
+
623
+
624
+ def draw_masks_to_frame(
625
+ frame: np.ndarray, masks: np.ndarray, colors: np.ndarray
626
+ ) -> np.ndarray:
627
+ masked_frame = frame
628
+ for mask, color in zip(masks, colors):
629
+ curr_masked_frame = np.where(mask[..., None], color, masked_frame)
630
+ masked_frame = cv2.addWeighted(masked_frame, 0.75, curr_masked_frame, 0.25, 0)
631
+
632
+ if int(cv2.__version__[0]) > 3:
633
+ contours, _ = cv2.findContours(
634
+ np.array(mask, dtype=np.uint8).copy(),
635
+ cv2.RETR_TREE,
636
+ cv2.CHAIN_APPROX_NONE,
637
+ )
638
+ else:
639
+ _, contours, _ = cv2.findContours(
640
+ np.array(mask, dtype=np.uint8).copy(),
641
+ cv2.RETR_TREE,
642
+ cv2.CHAIN_APPROX_NONE,
643
+ )
644
+
645
+ cv2.drawContours(
646
+ masked_frame, contours, -1, (255, 255, 255), 7
647
+ ) # White outer contour
648
+ cv2.drawContours(
649
+ masked_frame, contours, -1, (0, 0, 0), 5
650
+ ) # Black middle contour
651
+ cv2.drawContours(
652
+ masked_frame, contours, -1, color.tolist(), 3
653
+ ) # Original color inner contour
654
+ return masked_frame
655
+
656
+
657
+ def get_annot_df(file_path: str):
658
+ with open(file_path, "r") as f:
659
+ data = json.load(f)
660
+
661
+ dfs = {}
662
+
663
+ for k, v in data.items():
664
+ if k in ("info", "licenses"):
665
+ dfs[k] = v
666
+ continue
667
+ df = pd.DataFrame(v)
668
+ dfs[k] = df
669
+
670
+ return dfs
671
+
672
+
673
+ def get_annot_dfs(file_list: list[str]):
674
+ dfs = {}
675
+ for annot_file in tqdm(file_list):
676
+ dataset_name = Path(annot_file).stem
677
+ dfs[dataset_name] = get_annot_df(annot_file)
678
+
679
+ return dfs
680
+
681
+
682
+ def get_media_dir(media_dir: str, dataset: str):
683
+ if dataset in ["saco_veval_sav_test", "saco_veval_sav_val"]:
684
+ return os.path.join(media_dir, "saco_sav", "JPEGImages_24fps")
685
+ elif dataset in ["saco_veval_yt1b_test", "saco_veval_yt1b_val"]:
686
+ return os.path.join(media_dir, "saco_yt1b", "JPEGImages_6fps")
687
+ elif dataset in ["saco_veval_smartglasses_test", "saco_veval_smartglasses_val"]:
688
+ return os.path.join(media_dir, "saco_sg", "JPEGImages_6fps")
689
+ elif dataset == "sa_fari_test":
690
+ return os.path.join(media_dir, "sa_fari", "JPEGImages_6fps")
691
+ else:
692
+ raise ValueError(f"Dataset {dataset} not found")
693
+
694
+
695
+ def get_all_annotations_for_frame(
696
+ dataset_df: pd.DataFrame, video_id: int, frame_idx: int, data_dir: str, dataset: str
697
+ ):
698
+ media_dir = os.path.join(data_dir, "media")
699
+
700
+ # Load the annotation and video data
701
+ annot_df = dataset_df["annotations"]
702
+ video_df = dataset_df["videos"]
703
+
704
+ # Get the frame
705
+ video_df_current = video_df[video_df.id == video_id]
706
+ assert (
707
+ len(video_df_current) == 1
708
+ ), f"Expected 1 video row, got {len(video_df_current)}"
709
+ video_row = video_df_current.iloc[0]
710
+ file_name = video_row.file_names[frame_idx]
711
+ file_path = os.path.join(
712
+ get_media_dir(media_dir=media_dir, dataset=dataset), file_name
713
+ )
714
+ frame = cv2.imread(file_path)
715
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
716
+
717
+ # Get the masks and noun phrases annotated in this video in this frame
718
+ annot_df_current_video = annot_df[annot_df.video_id == video_id]
719
+ if len(annot_df_current_video) == 0:
720
+ print(f"No annotations found for video_id {video_id}")
721
+ return frame, None, None
722
+ else:
723
+ empty_mask = np.zeros(frame.shape[:2], dtype=np.uint8)
724
+ mask_np_pairs = annot_df_current_video.apply(
725
+ lambda row: (
726
+ (
727
+ mask_utils.decode(row.segmentations[frame_idx])
728
+ if row.segmentations[frame_idx]
729
+ else empty_mask
730
+ ),
731
+ row.noun_phrase,
732
+ ),
733
+ axis=1,
734
+ )
735
+ # sort based on noun_phrases
736
+ mask_np_pairs = sorted(mask_np_pairs, key=lambda x: x[1])
737
+ masks, noun_phrases = zip(*mask_np_pairs)
738
+
739
+ return frame, masks, noun_phrases
740
+
741
+
742
+ def visualize_prompt_overlay(
743
+ frame_idx,
744
+ video_frames,
745
+ title="Prompt Visualization",
746
+ text_prompt=None,
747
+ point_prompts=None,
748
+ point_labels=None,
749
+ bounding_boxes=None,
750
+ box_labels=None,
751
+ obj_id=None,
752
+ ):
753
+ """Simple prompt visualization function"""
754
+ img = Image.fromarray(load_frame(video_frames[frame_idx]))
755
+ fig, ax = plt.subplots(1, figsize=(6, 4))
756
+ ax.imshow(img)
757
+
758
+ img_w, img_h = img.size
759
+
760
+ if text_prompt:
761
+ ax.text(
762
+ 0.02,
763
+ 0.98,
764
+ f'Text: "{text_prompt}"',
765
+ transform=ax.transAxes,
766
+ fontsize=12,
767
+ color="white",
768
+ weight="bold",
769
+ bbox=dict(boxstyle="round,pad=0.3", facecolor="red", alpha=0.7),
770
+ verticalalignment="top",
771
+ )
772
+
773
+ if point_prompts:
774
+ for i, point in enumerate(point_prompts):
775
+ x, y = point
776
+ # Convert relative to absolute coordinates
777
+ x_img, y_img = x * img_w, y * img_h
778
+
779
+ # Use different colors for positive/negative points
780
+ if point_labels and len(point_labels) > i:
781
+ color = "green" if point_labels[i] == 1 else "red"
782
+ marker = "o" if point_labels[i] == 1 else "x"
783
+ else:
784
+ color = "green"
785
+ marker = "o"
786
+
787
+ ax.plot(
788
+ x_img,
789
+ y_img,
790
+ marker=marker,
791
+ color=color,
792
+ markersize=10,
793
+ markeredgewidth=2,
794
+ markeredgecolor="white",
795
+ )
796
+ ax.text(
797
+ x_img + 5,
798
+ y_img - 5,
799
+ f"P{i + 1}",
800
+ color=color,
801
+ fontsize=10,
802
+ weight="bold",
803
+ bbox=dict(boxstyle="round,pad=0.2", facecolor="white", alpha=0.8),
804
+ )
805
+
806
+ if bounding_boxes:
807
+ for i, box in enumerate(bounding_boxes):
808
+ x, y, w, h = box
809
+ # Convert relative to absolute coordinates
810
+ x_img, y_img = x * img_w, y * img_h
811
+ w_img, h_img = w * img_w, h * img_h
812
+
813
+ # Use different colors for positive/negative boxes
814
+ if box_labels and len(box_labels) > i:
815
+ color = "green" if box_labels[i] == 1 else "red"
816
+ else:
817
+ color = "green"
818
+
819
+ rect = patches.Rectangle(
820
+ (x_img, y_img),
821
+ w_img,
822
+ h_img,
823
+ linewidth=2,
824
+ edgecolor=color,
825
+ facecolor="none",
826
+ )
827
+ ax.add_patch(rect)
828
+ ax.text(
829
+ x_img,
830
+ y_img - 5,
831
+ f"B{i + 1}",
832
+ color=color,
833
+ fontsize=10,
834
+ weight="bold",
835
+ bbox=dict(boxstyle="round,pad=0.2", facecolor="white", alpha=0.8),
836
+ )
837
+
838
+ # Add object ID info if provided
839
+ if obj_id is not None:
840
+ ax.text(
841
+ 0.02,
842
+ 0.02,
843
+ f"Object ID: {obj_id}",
844
+ transform=ax.transAxes,
845
+ fontsize=10,
846
+ color="white",
847
+ weight="bold",
848
+ bbox=dict(boxstyle="round,pad=0.3", facecolor="blue", alpha=0.7),
849
+ verticalalignment="bottom",
850
+ )
851
+
852
+ ax.set_title(title)
853
+ ax.axis("off")
854
+ plt.tight_layout()
855
+ plt.show()
856
+
857
+
858
+ def plot_results(img, results):
859
+ plt.figure(figsize=(12, 8))
860
+ plt.imshow(img)
861
+ nb_objects = len(results["scores"])
862
+ print(f"found {nb_objects} object(s)")
863
+ for i in range(nb_objects):
864
+ color = COLORS[i % len(COLORS)]
865
+ plot_mask(results["masks"][i].squeeze(0).cpu(), color=color)
866
+ w, h = img.size
867
+ prob = results["scores"][i].item()
868
+ plot_bbox(
869
+ h,
870
+ w,
871
+ results["boxes"][i].cpu(),
872
+ text=f"(id={i}, {prob=:.2f})",
873
+ box_format="XYXY",
874
+ color=color,
875
+ relative_coords=False,
876
+ )
877
+
878
+
879
+ def single_visualization(img, anns, title):
880
+ """
881
+ Create a single image visualization with overlays.
882
+ """
883
+ fig, ax = plt.subplots(figsize=(7, 7))
884
+ fig.suptitle(title, fontsize=16, fontweight="bold")
885
+ overlay = render_masklet_frame(img, anns, alpha=0.5)
886
+ ax.imshow(overlay)
887
+ ax.axis("off")
888
+ plt.tight_layout()
889
+
890
+
891
+ def show_mask(mask, ax, obj_id=None, random_color=False):
892
+ if random_color:
893
+ color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)
894
+ else:
895
+ cmap = plt.get_cmap("tab10")
896
+ cmap_idx = 0 if obj_id is None else obj_id
897
+ color = np.array([*cmap(cmap_idx)[:3], 0.6])
898
+ h, w = mask.shape[-2:]
899
+ mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
900
+ ax.imshow(mask_image)
901
+
902
+
903
+ def show_box(box, ax):
904
+ x0, y0 = box[0], box[1]
905
+ w, h = box[2] - box[0], box[3] - box[1]
906
+ ax.add_patch(
907
+ plt.Rectangle((x0, y0), w, h, edgecolor="green", facecolor=(0, 0, 0, 0), lw=2)
908
+ )
909
+
910
+
911
+ def show_points(coords, labels, ax, marker_size=375):
912
+ pos_points = coords[labels == 1]
913
+ neg_points = coords[labels == 0]
914
+ ax.scatter(
915
+ pos_points[:, 0],
916
+ pos_points[:, 1],
917
+ color="green",
918
+ marker="*",
919
+ s=marker_size,
920
+ edgecolor="white",
921
+ linewidth=1.25,
922
+ )
923
+ ax.scatter(
924
+ neg_points[:, 0],
925
+ neg_points[:, 1],
926
+ color="red",
927
+ marker="*",
928
+ s=marker_size,
929
+ edgecolor="white",
930
+ linewidth=1.25,
931
+ )
932
+
933
+
934
+ def load_frame(frame):
935
+ if isinstance(frame, np.ndarray):
936
+ img = frame
937
+ elif isinstance(frame, Image.Image):
938
+ img = np.array(frame)
939
+ elif isinstance(frame, str) and os.path.isfile(frame):
940
+ img = plt.imread(frame)
941
+ else:
942
+ raise ValueError(f"Invalid video frame type: {type(frame)=}")
943
+ return img
third_party/GraspGen/sam3/scripts/extract_odinw_results.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ """This script summarizes odinw results"""
6
+
7
+ """
8
+ python3 scripts/extract_odinw_results.py --res_dir /path/to/results/directory
9
+ Expected directory structure:
10
+ results_directory/
11
+ ├── AerialMaritimeDrone_large/val_stats.json
12
+ ├── Aquarium/val_stats.json
13
+ ├── CottontailRabbits/val_stats.json
14
+ └── ...
15
+ """
16
+ import argparse
17
+ import json
18
+ import os
19
+
20
+ VAL13_SET = [
21
+ "AerialMaritimeDrone_large",
22
+ "Aquarium",
23
+ "CottontailRabbits",
24
+ "EgoHands_generic",
25
+ "NorthAmericaMushrooms",
26
+ "Packages",
27
+ "PascalVOC",
28
+ "Raccoon",
29
+ "ShellfishOpenImages",
30
+ "VehiclesOpenImages",
31
+ "pistols",
32
+ "pothole",
33
+ "thermalDogsAndPeople",
34
+ ]
35
+
36
+ METRIC_NAME = "coco_eval_bbox_AP"
37
+
38
+
39
+ def parse_args():
40
+ parser = argparse.ArgumentParser("ODinW results aggregation script")
41
+
42
+ parser.add_argument(
43
+ "--res_dir",
44
+ required=True,
45
+ type=str,
46
+ help="Parent directory containing subdirectories for each dataset with val_stats.json files",
47
+ )
48
+
49
+ return parser.parse_args()
50
+
51
+
52
+ def main(args):
53
+ # Dictionary to store results for each metric type
54
+ metric_results = {METRIC_NAME: []}
55
+ subset_results = {subset: {} for subset in VAL13_SET}
56
+
57
+ # Process each subset directory
58
+ for subset in VAL13_SET:
59
+ subset_dir = os.path.join(args.res_dir, subset)
60
+ val_stats_path = os.path.join(subset_dir, "val_stats.json")
61
+
62
+ if not os.path.exists(val_stats_path):
63
+ print(f"Warning: {val_stats_path} not found, skipping {subset}")
64
+ continue
65
+
66
+ try:
67
+ res = json.load(open(val_stats_path))
68
+ subset_results[subset] = res
69
+
70
+ # Extract metrics for this subset and group by metric type
71
+ for key, value in res.items():
72
+ if key.endswith(METRIC_NAME):
73
+ metric_results[METRIC_NAME].append(value)
74
+
75
+ except (json.JSONDecodeError, IOError) as e:
76
+ print(f"Error reading {val_stats_path}: {e}")
77
+ continue
78
+
79
+ # Print results
80
+ values = metric_results[METRIC_NAME]
81
+ if values:
82
+ avg = sum(values) / len(values)
83
+ print(f"Average {METRIC_NAME}: {avg:.4f} ({len(values)} datasets)")
84
+
85
+ # Show individual dataset results
86
+ for subset in VAL13_SET:
87
+ if subset in subset_results and subset_results[subset]:
88
+ for res_key, res_value in subset_results[subset].items():
89
+ if res_key.endswith(METRIC_NAME):
90
+ print(f" {subset}: {res_value:.4f}")
91
+ break
92
+ else:
93
+ print(f"No results found for {METRIC_NAME}")
94
+
95
+
96
+ if __name__ == "__main__":
97
+ main(parse_args())
third_party/GraspGen/sam3/scripts/extract_roboflow_vl100_results.py ADDED
@@ -0,0 +1,382 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ """
6
+ Script to extract and analyze training results from Roboflow VL100 experiments.
7
+
8
+ This script processes training logs and configuration files to extract model performance
9
+ metrics and training parameters for analysis and comparison.
10
+ """
11
+
12
+ import argparse
13
+ import json
14
+ import os
15
+ from typing import Any, Dict, List, Optional
16
+
17
+ import pandas as pd
18
+ import yaml
19
+
20
+
21
+ # Constants
22
+ CONFIG_FILENAME = "config_resolved.yaml"
23
+ RESULTS_FILENAME = "val_stats.json"
24
+ BBOX_AP_METRIC = "Meters_train/val_roboflow100/detection/coco_eval_bbox_AP"
25
+
26
+ # Roboflow dataset categories organized by domain
27
+ ROBOFLOW_CATEGORIES = {
28
+ "sports": [
29
+ "actions",
30
+ "aerial-pool",
31
+ "ball",
32
+ "bibdetection",
33
+ "football-player-detection",
34
+ "lacrosse-object-detection",
35
+ ],
36
+ "other": [
37
+ "buoy-onboarding",
38
+ "car-logo-detection",
39
+ "clashroyalechardetector",
40
+ "cod-mw-warzone",
41
+ "countingpills",
42
+ "everdaynew",
43
+ "flir-camera-objects",
44
+ "halo-infinite-angel-videogame",
45
+ "mahjong",
46
+ "new-defects-in-wood",
47
+ "orionproducts",
48
+ "pill",
49
+ "soda-bottles",
50
+ "taco-trash-annotations-in-context",
51
+ "the-dreidel-project",
52
+ ],
53
+ "aerial": [
54
+ "aerial-airport",
55
+ "aerial-cows",
56
+ "aerial-sheep",
57
+ "apoce-aerial-photographs-for-object-detection-of-construction-equipment",
58
+ "electric-pylon-detection-in-rsi",
59
+ "floating-waste",
60
+ "human-detection-in-floods",
61
+ "sssod",
62
+ "uavdet-small",
63
+ "wildfire-smoke",
64
+ "zebrasatasturias",
65
+ ],
66
+ "medical": [
67
+ "canalstenosis",
68
+ "crystal-clean-brain-tumors-mri-dataset",
69
+ "dentalai",
70
+ "inbreast",
71
+ "liver-disease",
72
+ "nih-xray",
73
+ "spinefrxnormalvindr",
74
+ "stomata-cells",
75
+ "train",
76
+ "ufba-425",
77
+ "urine-analysis1",
78
+ "x-ray-id",
79
+ "xray",
80
+ ],
81
+ "document": [
82
+ "activity-diagrams",
83
+ "all-elements",
84
+ "circuit-voltages",
85
+ "invoice-processing",
86
+ "label-printing-defect-version-2",
87
+ "macro-segmentation",
88
+ "paper-parts",
89
+ "signatures",
90
+ "speech-bubbles-detection",
91
+ "wine-labels",
92
+ ],
93
+ "industrial": [
94
+ "-grccs",
95
+ "13-lkc01",
96
+ "2024-frc",
97
+ "aircraft-turnaround-dataset",
98
+ "asphaltdistressdetection",
99
+ "cable-damage",
100
+ "conveyor-t-shirts",
101
+ "dataconvert",
102
+ "deeppcb",
103
+ "defect-detection",
104
+ "fruitjes",
105
+ "infraredimageofpowerequipment",
106
+ "ism-band-packet-detection",
107
+ "l10ul502",
108
+ "needle-base-tip-min-max",
109
+ "recode-waste",
110
+ "screwdetectclassification",
111
+ "smd-components",
112
+ "truck-movement",
113
+ "tube",
114
+ "water-meter",
115
+ "wheel-defect-detection",
116
+ ],
117
+ "flora_fauna": [
118
+ "aquarium-combined",
119
+ "bees",
120
+ "deepfruits",
121
+ "exploratorium-daphnia",
122
+ "grapes-5",
123
+ "grass-weeds",
124
+ "gwhd2021",
125
+ "into-the-vale",
126
+ "jellyfish",
127
+ "marine-sharks",
128
+ "orgharvest",
129
+ "peixos-fish",
130
+ "penguin-finder-seg",
131
+ "pig-detection",
132
+ "roboflow-trained-dataset",
133
+ "sea-cucumbers-new-tiles",
134
+ "thermal-cheetah",
135
+ "tomatoes-2",
136
+ "trail-camera",
137
+ "underwater-objects",
138
+ "varroa-mites-detection--test-set",
139
+ "wb-prova",
140
+ "weeds4",
141
+ ],
142
+ }
143
+
144
+
145
+ def load_jsonl_last_row(file_path: str, keys: List[str]) -> Optional[Dict[str, Any]]:
146
+ """
147
+ Load the last row from a JSONL file and extract specific keys.
148
+
149
+ Args:
150
+ file_path: Path to the JSONL file
151
+ keys: List of keys to extract from the last row
152
+
153
+ Returns:
154
+ Dictionary with extracted key-value pairs, or None if file not found/empty
155
+ """
156
+ if not os.path.exists(file_path):
157
+ print(f"Warning: File not found: {file_path}")
158
+ return None
159
+
160
+ last_row = None
161
+ try:
162
+ with open(file_path, "r") as file:
163
+ for line in file:
164
+ last_row = json.loads(line.strip())
165
+
166
+ if last_row is None:
167
+ print(f"Warning: Empty JSONL file: {file_path}")
168
+ return None
169
+
170
+ return {key: last_row.get(key) for key in keys}
171
+
172
+ except json.JSONDecodeError as e:
173
+ print(f"Error: Failed to parse JSON in {file_path}: {e}")
174
+ return None
175
+ except Exception as e:
176
+ print(f"Error: Failed to read {file_path}: {e}")
177
+ return None
178
+
179
+
180
+ def find_config_files(directory: str, filename: str = CONFIG_FILENAME) -> List[str]:
181
+ """
182
+ Recursively find configuration files with a specific filename.
183
+
184
+ Args:
185
+ directory: Root directory to search
186
+ filename: Target filename to search for
187
+
188
+ Returns:
189
+ List of full paths to matching files
190
+ """
191
+ matching_files = []
192
+ for root, _, files in os.walk(directory):
193
+ # Skip code directories
194
+ if "/code/" in root:
195
+ continue
196
+ if filename in files:
197
+ matching_files.append(os.path.join(root, filename))
198
+ return matching_files
199
+
200
+
201
+ def extract_config_parameters(config_path: str, keys: List[str]) -> Dict[str, Any]:
202
+ """
203
+ Extract specific parameters from a YAML configuration file.
204
+
205
+ Args:
206
+ config_path: Path to the YAML configuration file
207
+ keys: List of keys to extract from the 'scratch' section
208
+
209
+ Returns:
210
+ Dictionary containing extracted parameters
211
+ """
212
+ try:
213
+ with open(config_path, "r") as file:
214
+ data = yaml.safe_load(file)
215
+
216
+ # Extract parameters from scratch section
217
+ scratch_params = {key: data["scratch"].get(key) for key in keys}
218
+
219
+ # Add computed parameters
220
+ launcher = data.get("launcher", {})
221
+ scratch_params["batch_size"] = int(launcher.get("gpus_per_node", 1)) * int(
222
+ launcher.get("num_nodes", 1)
223
+ )
224
+ scratch_params["lr_scale"] = data["scratch"].get("lr_scale")
225
+
226
+ roboflow_train = data.get("roboflow_train", {})
227
+ scratch_params["roboflow_num_images"] = roboflow_train.get("num_images")
228
+
229
+ return scratch_params
230
+
231
+ except Exception as e:
232
+ print(f"Error: Failed to parse config file {config_path}: {e}")
233
+ return {}
234
+
235
+
236
+ def calculate_average(values_dict: Dict[str, float]) -> float:
237
+ """
238
+ Calculate the average of values in a dictionary.
239
+
240
+ Args:
241
+ values_dict: Dictionary with numeric values
242
+
243
+ Returns:
244
+ Average of all values, or 0 if empty
245
+ """
246
+ if not values_dict:
247
+ return 0.0
248
+ return sum(values_dict.values()) / len(values_dict)
249
+
250
+
251
+ def extract_category_results(log_dir: str, categories: List[str]) -> Dict[str, float]:
252
+ """
253
+ Extract bbox AP results for specific categories from log files.
254
+
255
+ Args:
256
+ log_dir: Directory containing category log subdirectories
257
+ categories: List of category names to extract results for
258
+
259
+ Returns:
260
+ Dictionary mapping category names to bbox AP scores
261
+ """
262
+ results = {}
263
+ metric_keys = [BBOX_AP_METRIC]
264
+
265
+ for category in categories:
266
+ result_file = os.path.join(log_dir, f"logs/{category}/{RESULTS_FILENAME}")
267
+ category_result = load_jsonl_last_row(result_file, metric_keys)
268
+
269
+ if category_result is not None and category_result[BBOX_AP_METRIC] is not None:
270
+ results[category] = category_result[BBOX_AP_METRIC]
271
+
272
+ return results
273
+
274
+
275
+ def analyze_experiment_results(config_path: str) -> None:
276
+ """
277
+ Analyze results from a single experiment configuration.
278
+
279
+ Args:
280
+ config_path: Path to the experiment configuration file
281
+ """
282
+ print("=" * 80)
283
+ print(f"Analyzing experiment: {config_path}")
284
+ print("=" * 80)
285
+
286
+ # Extract configuration parameters
287
+ config_keys = [
288
+ "lr_transformer",
289
+ "lr_vision_backbone",
290
+ "lr_language_backbone",
291
+ "max_data_epochs",
292
+ ]
293
+
294
+ config_params = extract_config_parameters(config_path, config_keys)
295
+ print("Configuration Parameters:")
296
+ for key, value in config_params.items():
297
+ print(f" {key}: {value}")
298
+ print()
299
+
300
+ # Extract results for each category
301
+ experiment_dir = os.path.dirname(config_path)
302
+ category_results = {}
303
+ category_averages = {}
304
+ all_scores = []
305
+
306
+ for super_category, categories in ROBOFLOW_CATEGORIES.items():
307
+ category_results[super_category] = extract_category_results(
308
+ experiment_dir, categories
309
+ )
310
+
311
+ if category_results[super_category]:
312
+ category_averages[super_category] = calculate_average(
313
+ category_results[super_category]
314
+ )
315
+ all_scores.extend(category_results[super_category].values())
316
+
317
+ # Print results summary
318
+ print("Results by Category:")
319
+ for super_category, avg_score in category_averages.items():
320
+ num_categories = len(category_results[super_category])
321
+ print(f" {super_category}: {avg_score:.4f} (n={num_categories})")
322
+
323
+ print(f"\nOverall Results:")
324
+ print(f" Weighted average: {calculate_average(category_averages):.4f}")
325
+ print(f" Total categories: {len(all_scores)}")
326
+ print(f" True average: {sum(all_scores) / len(all_scores):.4f}")
327
+ print()
328
+
329
+
330
+ def print_results_table(results_data: List[Dict[str, Any]]) -> None:
331
+ """
332
+ Print results in a formatted table.
333
+
334
+ Args:
335
+ results_data: List of dictionaries containing results data
336
+ """
337
+ if not results_data:
338
+ print("No results data to display.")
339
+ return
340
+
341
+ df = pd.DataFrame(results_data)
342
+ print("\nResults Summary Table:")
343
+ print("=" * 60)
344
+ print(df.to_string(index=False))
345
+
346
+
347
+ def main() -> None:
348
+ """Main function to orchestrate the results extraction and analysis."""
349
+ parser = argparse.ArgumentParser(
350
+ description="Extract and analyze Roboflow VL100 training results"
351
+ )
352
+ parser.add_argument(
353
+ "-p",
354
+ "--path",
355
+ type=str,
356
+ required=True,
357
+ help="Root directory path containing experiment results",
358
+ )
359
+
360
+ args = parser.parse_args()
361
+
362
+ # Find all configuration files
363
+ config_files = find_config_files(args.path, CONFIG_FILENAME)
364
+
365
+ if not config_files:
366
+ print(f"No configuration files found in {args.path}")
367
+ return
368
+
369
+ print(f"Found {len(config_files)} experiment configurations")
370
+ print()
371
+
372
+ # Analyze each experiment
373
+ for config_file in config_files:
374
+ try:
375
+ analyze_experiment_results(config_file)
376
+ except Exception as e:
377
+ print(f"Error analyzing {config_file}: {e}")
378
+ continue
379
+
380
+
381
+ if __name__ == "__main__":
382
+ main()
third_party/tuntunclaw/manipulator_grasp/arm/controller/adaptive_controller/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .adaptive_controller import AdaptiveController
third_party/tuntunclaw/manipulator_grasp/arm/controller/adaptive_controller/adaptive_controller.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from ..controller import Controller
4
+ from arm.robot import Robot
5
+
6
+
7
+ class AdaptiveController(Controller):
8
+ def __init__(self, kds: list, robot: Robot, ts=0.001, filter_coefficient=100.0) -> None:
9
+ super().__init__()
10
+ self._robot = robot
11
+ parameters = self._robot.inertial_parameters
12
+ parameters[0:30] *= 0.8
13
+ self._robot.inertial_parameters = parameters
14
+ self._qd_prev = np.zeros(robot.dof)
15
+ self._dqd_prev = np.zeros(robot.dof)
16
+ self._q_prev = np.zeros(robot.dof)
17
+ self._kds = np.array(kds)
18
+ self._ts = ts
19
+ self._Fai = 5.0 * np.ones(self._robot.dof)
20
+ self._Tau = np.zeros(self._robot.inertial_parameters.size)
21
+ self._Tau[:30] = 0.2
22
+
23
+ def control(self, qd, q):
24
+ dqd: np.ndarray = (qd - self._qd_prev) / self._ts
25
+ ddqd: np.ndarray = (dqd - self._dqd_prev) / self._ts
26
+ dq: np.ndarray = (q - self._q_prev) / self._ts
27
+
28
+ dqr = dqd + self._Fai * (qd - q)
29
+ ddqr = ddqd + self._Fai * (dqd - dq)
30
+
31
+ tau = self._robot.inv_dynamics_adaptive(q, dq, dqr, ddqr) + self._kds * (dqr - dq)
32
+
33
+ self._update(q, dq, dqr, ddqr)
34
+ self._qd_prev = np.array(qd)
35
+ self._dqd_prev = np.array(dqd)
36
+ self._q_prev = np.array(q)
37
+
38
+ return tau
39
+
40
+ def _update(self, q, dq, dqr, ddqr):
41
+ Y = self._robot.get_adaptive_identification_matrix(q, dq, dqr, ddqr)
42
+ r = dqr - dq
43
+ dp = self._Tau * (Y.T @ r)
44
+ self._robot.inertial_parameters += dp * self._ts
third_party/tuntunclaw/manipulator_grasp/arm/controller/computed_torque_controller/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .computed_torque_controller import ComputedTorqueController
third_party/tuntunclaw/manipulator_grasp/arm/controller/computed_torque_controller/computed_torque_controller.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from ..controller import Controller
4
+ from ..pid_controller import PIDController
5
+ from arm.robot import Robot
6
+
7
+
8
+ class ComputedTorqueController(Controller):
9
+
10
+ def __init__(self, kps: list, kis: list, kds: list, robot: Robot, ts=0.001, filter_coefficient=100.0) -> None:
11
+ self._robot = robot
12
+ self._pid_controllers = [PIDController(kps[i], kis[i], kds[i], ts, filter_coefficient) for i in
13
+ range(robot.dof)]
14
+ self._qd_prev = np.zeros(robot.dof)
15
+ self._dqd_prev = np.zeros(robot.dof)
16
+ self._ts = ts
17
+
18
+ def control(self, qd, q):
19
+ dqd: np.ndarray = (qd - self._qd_prev) / self._ts
20
+ ddqd: np.ndarray = (dqd - self._dqd_prev) / self._ts
21
+
22
+ pid_outs = [self._pid_controllers[i].control(qd[i], q[i]) for i in range(self._robot.dof)]
23
+
24
+ self._qd_prev = np.array(qd)
25
+ self._dqd_prev = np.array(dqd)
26
+
27
+ return self._robot.inv_dynamics(qd, dqd, ddqd + pid_outs)
28
+
29
+ def set_qd(self, qd: np.ndarray):
30
+ self._qd_prev = qd.copy()
third_party/tuntunclaw/manipulator_grasp/arm/controller/feedforward_controller/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .feedforward_controller import FeedforwardController
third_party/tuntunclaw/manipulator_grasp/arm/controller/feedforward_controller/feedforward_controller.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from ..controller import Controller
4
+ from ..pid_controller import PIDController
5
+ from arm.robot import Robot
6
+
7
+
8
+ class FeedforwardController(Controller):
9
+ def __init__(self, kps: list, kis: list, kds: list, robot: Robot, ts=0.001, filter_coefficient=100.0) -> None:
10
+ self._robot = robot
11
+ self._pid_controllers = [PIDController(kps[i], kis[i], kds[i], ts, filter_coefficient) for i in range(robot.dof)]
12
+ self._qd_prev = np.zeros(robot.dof)
13
+ self._dqd_prev = np.zeros(robot.dof)
14
+ self._ts = ts
15
+
16
+ def control(self, inpd, inp, qd):
17
+ dqd = (qd - self._qd_prev) / self._ts
18
+ ddqd = (dqd - self._dqd_prev) / self._ts
19
+ feedforward_outs = self._robot.inv_dynamics(qd, dqd, ddqd)
20
+
21
+ pid_outs = [self._pid_controllers[i].control(inpd[i], inp[i]) for i in range(self._robot.dof)]
22
+
23
+ self._qd_prev = np.array(qd)
24
+ self._dqd_prev = np.array(dqd)
25
+
26
+ return feedforward_outs + pid_outs
third_party/tuntunclaw/manipulator_grasp/arm/controller/pid_controller/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .pid_controller import PIDController
third_party/tuntunclaw/manipulator_grasp/arm/controller/pid_controller/pid_controller.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from ..controller import Controller
4
+
5
+
6
+ class PIDController(Controller):
7
+ """
8
+ backward euler and use filtered derivative
9
+ """
10
+
11
+ def __init__(self, kp: float, ki: float, kd: float, ts=0.001, filter_coefficient=100.0):
12
+ self.__kp = kp
13
+ self.__ki = ki
14
+ self.__kd = kd
15
+ self.__filter_coefficient = filter_coefficient
16
+
17
+ self.__ts = ts
18
+ self.__error_prev = 0.0
19
+ self.__error_integral = 0.0
20
+ self.__error_derivative = 0.0
21
+
22
+ def control(self, qd, q):
23
+ error = np.array(qd) - np.array(q)
24
+ self.__error_integral += error * self.__ts
25
+
26
+ # derivative = (inp - self.__prev_input) / self.__ts
27
+ self.__error_derivative = (self.__filter_coefficient * (
28
+ error - self.__error_prev) + self.__error_derivative) / (
29
+ self.__filter_coefficient * self.__ts + 1.0)
30
+ # self.__prev_derivative_out = derivative
31
+ output = self.__kp * error + self.__ki * self.__error_integral + self.__kd * self.__error_derivative
32
+
33
+ self.__error_prev = error
34
+
35
+ return output
36
+
37
+ def reset(self):
38
+ self.__error_prev = 0.0
39
+ self.__error_integral = 0.0
40
+ self.__error_derivative = 0.0
41
+
42
+ @property
43
+ def ts(self):
44
+ return self.__ts
45
+
46
+ @ts.setter
47
+ def ts(self, ts):
48
+ self.__ts = ts
49
+
50
+ @property
51
+ def kp(self):
52
+ return self.__kp
53
+
54
+ @property
55
+ def ki(self):
56
+ return self.__ki
57
+
58
+ @property
59
+ def kd(self):
60
+ return self.__kd
61
+
62
+ @kp.setter
63
+ def kp(self, kp):
64
+ self.__kp = kp
65
+
66
+ @ki.setter
67
+ def ki(self, ki):
68
+ self.__ki = ki
69
+
70
+ @kd.setter
71
+ def kd(self, kd):
72
+ self.__kd = kd
73
+
74
+ def set_parameter(self, kp: float, ki: float, kd: float):
75
+ self.__kp = kp
76
+ self.__ki = ki
77
+ self.__kd = kd
third_party/tuntunclaw/manipulator_grasp/arm/geometry/collision/GJK.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ from typing import Tuple
3
+
4
+ import numpy as np
5
+
6
+ from arm.constanst import MathConst
7
+ from ..simplex import Point, SimplexFactoryPool, SimplexParameter, UnitVector, Support
8
+
9
+
10
+ class GJK:
11
+
12
+ @staticmethod
13
+ def calculate_distance(shape0: Support, shape1: Support) -> float:
14
+
15
+ return GJK.calculate_distance_and_points(shape0, shape1)[0]
16
+
17
+ @staticmethod
18
+ def calculate_distance_and_points(shape0: Support, shape1: Support) -> Tuple[float, Tuple]:
19
+ vec = UnitVector(np.array([1, 0, 0]))
20
+ point0 = shape0.calculate_support_point(vec)
21
+ point1 = shape1.calculate_support_point(-vec)
22
+ point = point0 - point1
23
+
24
+ origin = Point([0, 0, 0])
25
+
26
+ closest_point = point
27
+ comparator = lambda x: np.linalg.norm(x.get_t())
28
+ points = [point]
29
+ points0 = [point0]
30
+ points1 = [point1]
31
+
32
+ coordinates = [1]
33
+
34
+ finish = False
35
+
36
+ while closest_point != origin:
37
+ closest = copy.deepcopy(closest_point)
38
+ vec = -UnitVector(closest_point)
39
+ point0 = shape0.calculate_support_point(vec)
40
+ point1 = shape1.calculate_support_point(-vec)
41
+ point = point0 - point1
42
+
43
+ for point_i in points:
44
+ if np.linalg.norm((point - point_i).get_t()) < MathConst.ERROR:
45
+ finish = True
46
+ break
47
+ if finish:
48
+ break
49
+
50
+ points.append(point)
51
+ points0.append(point0)
52
+ points1.append(point1)
53
+
54
+ if len(points) == 5:
55
+ coordinate_min = min(coordinates)
56
+ coordinate_min_index = coordinates.index(coordinate_min)
57
+ points.pop(coordinate_min_index)
58
+ points0.pop(coordinate_min_index)
59
+ points1.pop(coordinate_min_index)
60
+ break
61
+
62
+ simplex_parameter = SimplexParameter(points)
63
+ simplex = SimplexFactoryPool.create_product(simplex_parameter)
64
+ closest_point = simplex.calculate_closest_point_to_origin()
65
+ coordinates = simplex.calculate_barycentric_coordinates(closest_point)
66
+
67
+ if np.linalg.norm((closest - closest_point).get_t()) < MathConst.EPS:
68
+ break
69
+
70
+ j = 0
71
+ for i, coordinate in enumerate(coordinates):
72
+ if abs(coordinate) < MathConst.EPS:
73
+ points.pop(i - j)
74
+ points0.pop(i - j)
75
+ points1.pop(i - j)
76
+ j = j + 1
77
+
78
+ simplex_parameter = SimplexParameter(points)
79
+ simplex = SimplexFactoryPool.create_product(simplex_parameter)
80
+ coordinates = simplex.calculate_barycentric_coordinates(closest_point)
81
+
82
+ point0 = Point(np.zeros_like(point0.get_t()))
83
+ point1 = Point(np.zeros_like(point1.get_t()))
84
+ for i, coordinate_i in enumerate(coordinates):
85
+ point0 += coordinate_i * points0[i]
86
+ point1 += coordinate_i * points1[i]
87
+
88
+ return np.linalg.norm(closest_point.get_t()), (point0, point1)
89
+
90
+ @staticmethod
91
+ def is_intersecting(shape0: Support, shape1: Support):
92
+ origin = Point([0, 0, 0])
93
+ unit_vector = UnitVector(np.array([1, 0, 0]))
94
+
95
+ point = shape0.calculate_support_point(unit_vector) - shape1.calculate_support_point(-unit_vector)
96
+ points = [point]
97
+ closest_point = point
98
+
99
+ coordinates = [1]
100
+
101
+ while closest_point != origin:
102
+ unit_vector = -UnitVector(closest_point)
103
+ point = shape0.calculate_support_point(unit_vector) - shape1.calculate_support_point(-unit_vector)
104
+ if np.dot(point.get_t(), unit_vector.get_t()) < 0:
105
+ return False
106
+ points.append(point)
107
+
108
+ if len(points) == 5:
109
+ coordinate_min = min(coordinates)
110
+ coordinate_min_index = coordinates.index(coordinate_min)
111
+ points.pop(coordinate_min_index)
112
+ break
113
+
114
+ simplex_parameter = SimplexParameter(points)
115
+ simplex = SimplexFactoryPool.create_product(simplex_parameter)
116
+ closest_point = simplex.calculate_closest_point_to_origin()
117
+ coordinates = simplex.calculate_barycentric_coordinates(closest_point)
118
+
119
+ j = 0
120
+ for i, coordinate in enumerate(coordinates):
121
+ if abs(coordinate) < MathConst.EPS:
122
+ points.pop(i - j)
123
+ j = j + 1
124
+
125
+ return True
third_party/tuntunclaw/manipulator_grasp/arm/geometry/collision/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from .distance2d import Distance2D
2
+ from .intersect2d import Intersect2D
3
+ from .collision2d import Collision2D
4
+ from .GJK import GJK
5
+ from .distance import Distance
6
+ from .colliison import Collision
third_party/tuntunclaw/manipulator_grasp/arm/geometry/collision/colliison.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from ..simplex import Support
2
+ from .GJK import GJK
3
+
4
+
5
+ class Collision:
6
+
7
+ @staticmethod
8
+ def is_collision(shape0: Support, shape1: Support) -> bool:
9
+ return GJK.is_intersecting(shape0, shape1)
third_party/tuntunclaw/manipulator_grasp/arm/geometry/collision/collision2d.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ from typing import Iterable
3
+
4
+ from ..simplex import Point, Line, LineSegment
5
+ from ..shape import Circle2D
6
+ from .intersect2d import Intersect2D
7
+
8
+
9
+ class Collision2D:
10
+ def __init__(self, obstacles: Iterable[Circle2D]) -> None:
11
+ super().__init__()
12
+ self.obstacles = copy.deepcopy(obstacles)
13
+
14
+ def check_point(self, point: Point) -> bool:
15
+ for obstacle in self.obstacles:
16
+ if Intersect2D.check_point_to_circle(point, obstacle):
17
+ return True
18
+ return False
19
+
20
+ def check_line(self, line: Line):
21
+ for obstacle in self.obstacles:
22
+ if Intersect2D.check_line_to_circle(line, obstacle):
23
+ return True
24
+ return False
25
+
26
+ def check_line_segment(self, line_segment: LineSegment):
27
+ for obstacle in self.obstacles:
28
+ if Intersect2D.check_line_segment_to_circle(line_segment, obstacle):
29
+ return True
30
+ return False
third_party/tuntunclaw/manipulator_grasp/arm/geometry/collision/distance.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple
2
+ import numpy as np
3
+ from spatialmath import SE3
4
+
5
+ from ..simplex import Point, Line, LineSegment, Support
6
+ from ..shape import Plane, Brick
7
+ from .GJK import GJK
8
+
9
+
10
+ class Distance:
11
+ @staticmethod
12
+ def point_to_point(point0: Point, point1: Point):
13
+ return np.linalg.norm((point1 - point0).get_t())
14
+
15
+ @staticmethod
16
+ def point_to_plane(point: Point, plane: Plane):
17
+ return np.dot(point.get_t() - plane.get_t(), plane.get_normal_vector())
18
+
19
+ @staticmethod
20
+ def point_to_line(point: Point, line: Line) -> float:
21
+ foot_point, t = Distance.__calculate_foot_point(point, line)
22
+ return np.linalg.norm(point.get_t() - foot_point)
23
+
24
+ @staticmethod
25
+ def point_to_line_segment(point: Point, line_segment: LineSegment) -> float:
26
+ foot_point, t = Distance.__calculate_foot_point(point, line_segment)
27
+
28
+ t = max(0, min(1, t))
29
+
30
+ projection = line_segment.get_point0().get_t() + t * (
31
+ line_segment.get_point1().get_t() - line_segment.get_point0().get_t())
32
+ return np.linalg.norm(point.get_t() - projection)
33
+
34
+ @staticmethod
35
+ def point_to_brick(point: Point, brick: Brick):
36
+ p = brick.base.inv() * SE3.Trans(*point.get_t()).t
37
+ p = p.squeeze()
38
+
39
+ if p[2] < -brick.dimensions[2] / 2.0:
40
+ if p[1] < -brick.dimensions[1] / 2.0:
41
+ if p[0] < -brick.dimensions[0] / 2.0:
42
+ return Distance.point_to_point(point, brick.xn_yn_zn_point)
43
+ if p[0] > brick.dimensions[0] / 2.0:
44
+ return Distance.point_to_point(point, brick.xp_yn_zn_point)
45
+ else:
46
+ return Distance.point_to_line_segment(point, brick.yn_zn_line_segment)
47
+ elif p[1] > brick.dimensions[1] / 2.0:
48
+ if p[0] < -brick.dimensions[0] / 2.0:
49
+ return Distance.point_to_point(point, brick.xp_yn_zn_point)
50
+ if p[0] > brick.dimensions[0] / 2.0:
51
+ return Distance.point_to_point(point, brick.xp_yp_zn_point)
52
+ else:
53
+ return Distance.point_to_line_segment(point, brick.yp_zn_line_segment)
54
+ else:
55
+ if p[0] < -brick.dimensions[0] / 2.0:
56
+ return Distance.point_to_line_segment(point, brick.xn_zn_line_segment)
57
+ if p[0] > brick.dimensions[0] / 2.0:
58
+ return Distance.point_to_line_segment(point, brick.xp_zn_line_segment)
59
+ else:
60
+ return Distance.point_to_plane(point, brick.zn_plane)
61
+ elif p[2] > brick.dimensions[2] / 2.0:
62
+ if p[1] < -brick.dimensions[1] / 2.0:
63
+ if p[0] < -brick.dimensions[0] / 2.0:
64
+ return Distance.point_to_point(point, brick.xn_yn_zp_point)
65
+ if p[0] > brick.dimensions[0] / 2.0:
66
+ return Distance.point_to_point(point, brick.xp_yn_zp_point)
67
+ else:
68
+ return Distance.point_to_line_segment(point, brick.yn_zp_line_segment)
69
+ elif p[1] > brick.dimensions[1] / 2.0:
70
+ if p[0] < -brick.dimensions[0] / 2.0:
71
+ return Distance.point_to_point(point, brick.xp_yn_zp_point)
72
+ if p[0] > brick.dimensions[0] / 2.0:
73
+ return Distance.point_to_point(point, brick.xp_yp_zp_point)
74
+ else:
75
+ return Distance.point_to_line_segment(point, brick.yp_zp_line_segment)
76
+ else:
77
+ if p[0] < -brick.dimensions[0] / 2.0:
78
+ return Distance.point_to_line_segment(point, brick.xn_zp_line_segment)
79
+ if p[0] > brick.dimensions[0] / 2.0:
80
+ return Distance.point_to_line_segment(point, brick.xp_zp_line_segment)
81
+ else:
82
+ return Distance.point_to_plane(point, brick.zp_plane)
83
+ else:
84
+ if p[1] < -brick.dimensions[1] / 2.0:
85
+ if p[0] < -brick.dimensions[0] / 2.0:
86
+ return Distance.point_to_line_segment(point, brick.xn_yn_line_segment)
87
+ if p[0] > brick.dimensions[0] / 2.0:
88
+ return Distance.point_to_line_segment(point, brick.xp_yn_line_segment)
89
+ else:
90
+ return Distance.point_to_plane(point, brick.yn_plane)
91
+ pass
92
+ elif p[1] > brick.dimensions[1] / 2.0:
93
+ if p[0] < -brick.dimensions[0] / 2.0:
94
+ return Distance.point_to_line_segment(point, brick.xn_yp_line_segment)
95
+ if p[0] > brick.dimensions[0] / 2.0:
96
+ return Distance.point_to_line_segment(point, brick.xp_yp_line_segment)
97
+ else:
98
+ return Distance.point_to_plane(point, brick.yp_plane)
99
+ else:
100
+ if p[0] < -brick.dimensions[0] / 2.0:
101
+ return Distance.point_to_plane(point, brick.xn_plane)
102
+ if p[0] > brick.dimensions[0] / 2.0:
103
+ return Distance.point_to_plane(point, brick.xp_plane)
104
+ else:
105
+ return -1.0
106
+ return -1.0
107
+
108
+ @staticmethod
109
+ def line_segment_to_line_segment(line_segment0: LineSegment, line_segment1: LineSegment):
110
+ a = np.power(np.linalg.norm(line_segment0.get_point1().get_t() - line_segment0.get_point0().get_t()), 2)
111
+ b = np.dot(line_segment0.get_point1().get_t() - line_segment0.get_point0().get_t(),
112
+ line_segment1.get_point1().get_t() - line_segment1.get_point0().get_t())
113
+ c = np.power(np.linalg.norm(line_segment1.get_point1().get_t() - line_segment1.get_point0().get_t()), 2)
114
+ d = np.dot(line_segment0.get_point1().get_t() - line_segment0.get_point0().get_t(),
115
+ line_segment0.get_point0().get_t() - line_segment1.get_point0().get_t())
116
+ e = np.dot(line_segment1.get_point1().get_t() - line_segment1.get_point0().get_t(),
117
+ line_segment0.get_point0().get_t() - line_segment1.get_point0().get_t())
118
+ f = np.power(np.linalg.norm(line_segment0.get_point0().get_t() - line_segment1.get_point0().get_t()), 2)
119
+
120
+ det = a * c - np.power(b, 2)
121
+ if det > 0.0:
122
+ bte = b * e
123
+ ctd = c * d
124
+ if bte <= ctd:
125
+ if e <= 0.0:
126
+ s = 1.0 if -d >= a else (-d / a if -d > 0.0 else 0.0)
127
+ t = 0.0
128
+ elif e < c:
129
+ s = 0.0
130
+ t = e / c
131
+ else:
132
+ s = 1.0 if b - d >= a else ((b - d) / a if b - d > 0.0 else 0.0)
133
+ t = 1.0
134
+ else:
135
+ s = bte - ctd
136
+ if s >= det:
137
+ if b + e <= 0.0:
138
+ s = 0.0 if -d <= 0.0 else (-d / a if -d < a else 1.0)
139
+ t = 1.0
140
+ elif b + e < c:
141
+ s = 1.0
142
+ t = (b + e) / c
143
+ else:
144
+ s = (0.0 if b - d <= 0 else ((b - d) / a if b - d < a else 1.0))
145
+ t = 1.0
146
+ else:
147
+ ate = a * e
148
+ btd = b * d
149
+ if ate < btd:
150
+ s = 0.0 if -d <= 0.0 else (1.0 if -d >= a else -d / a)
151
+ t = 0.0
152
+ else:
153
+ t = ate - btd
154
+ if t >= det:
155
+ s = 0.0 if b - d <= 0.0 else (1.0 if b - d >= a else (b - d) / a)
156
+ t = 1.0
157
+ else:
158
+ s /= det
159
+ t /= det
160
+ else:
161
+ if e <= 0.0:
162
+ s = 0.0 if -d <= 0.0 else (1.0 if -d >= a else -d / a)
163
+ t = 0.0
164
+ elif e >= c:
165
+ s = 0.0 if b - d <= 0.0 else (1.0 if b - d >= a else (b - d) / a)
166
+ t = 1.0
167
+ else:
168
+ s = 0.0
169
+ t = e / c
170
+
171
+ distance = np.sqrt(a * np.power(s, 2) - 2 * b * s * t + c * np.power(t, 2) + 2 * d * s - 2 * e * t + f)
172
+
173
+ return distance
174
+
175
+ @staticmethod
176
+ def __calculate_foot_point(point: Point, line: Line) -> tuple:
177
+ v = line.get_point0().get_t()
178
+ w = line.get_point1().get_t()
179
+ p = point.get_t()
180
+
181
+ if np.array_equal(v, w):
182
+ return np.linalg.norm(p - v), 0
183
+ l2 = (w - v).dot(w - v)
184
+
185
+ t = (p - v).dot(w - v) / l2
186
+ foot_point = v + t * (w - v)
187
+ return foot_point, t
188
+
189
+ @staticmethod
190
+ def calculate_distance(shape0: Support, shape1: Support) -> float:
191
+ return GJK.calculate_distance(shape0, shape1)
192
+
193
+ @staticmethod
194
+ def calculate_distance_and_points(shape0: Support, shape1: Support) -> Tuple[float, Tuple]:
195
+ return GJK.calculate_distance_and_points(shape0, shape1)
third_party/tuntunclaw/manipulator_grasp/arm/geometry/collision/distance2d.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from ..simplex import Point, Line, LineSegment
4
+ from ..shape import Circle2D
5
+
6
+
7
+ class Distance2D:
8
+ @staticmethod
9
+ def point_to_point(point0: Point, point1: Point) -> float:
10
+ return np.linalg.norm((point1 - point0).get_t())
11
+
12
+ @staticmethod
13
+ def point_to_line_segment(point: Point, line_segment: LineSegment) -> float:
14
+ foot_point, t = Distance2D.__calculate_foot_point(point, line_segment)
15
+
16
+ t = max(0, min(1, t))
17
+
18
+ projection = line_segment.get_point0().get_t() + t * (
19
+ line_segment.get_point1().get_t() - line_segment.get_point0().get_t())
20
+ return np.linalg.norm(point.get_t() - projection)
21
+
22
+ @staticmethod
23
+ def point_to_line(point: Point, line: Line) -> float:
24
+ foot_point, t = Distance2D.__calculate_foot_point(point, line)
25
+ return np.linalg.norm(point.get_t() - foot_point)
26
+
27
+ @staticmethod
28
+ def point_to_circle(point: Point, circle: Circle2D) -> float:
29
+ return Distance2D.point_to_point(point, circle.get_center()) - circle.get_radius()
30
+
31
+ @staticmethod
32
+ def line_to_circle(line: Line, circle: Circle2D) -> float:
33
+ return Distance2D.point_to_line(circle.get_center(), line) - circle.get_radius()
34
+
35
+ @staticmethod
36
+ def line_segment_to_circle(line_segment: LineSegment, circle: Circle2D) -> float:
37
+ return Distance2D.point_to_line_segment(circle.get_center(), line_segment) - circle.get_radius()
38
+
39
+ @staticmethod
40
+ def __calculate_foot_point(point: Point, line: Line) -> tuple:
41
+ v = line.get_point0().get_t()
42
+ w = line.get_point1().get_t()
43
+ p = point.get_t()
44
+
45
+ if np.array_equal(v, w):
46
+ return np.linalg.norm(p - v), 0
47
+ l2 = (w - v).dot(w - v)
48
+
49
+ t = (p - v).dot(w - v) / l2
50
+ foot_point = v + t * (w - v)
51
+ return foot_point, t
third_party/tuntunclaw/manipulator_grasp/arm/geometry/collision/intersect2d.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ..simplex import Point, Line, LineSegment
2
+ from ..shape import Circle2D
3
+ from .distance2d import Distance2D
4
+
5
+
6
+ class Intersect2D:
7
+
8
+ @staticmethod
9
+ def check_point_to_circle(point: Point, circle: Circle2D) -> bool:
10
+ return Distance2D.point_to_circle(point, circle) <= 0.0
11
+
12
+ @staticmethod
13
+ def check_line_to_circle(line: Line, circle: Circle2D):
14
+ return Distance2D.line_to_circle(line, circle) <= 0.0
15
+
16
+ @staticmethod
17
+ def check_line_segment_to_circle(line_segment: LineSegment, circle: Circle2D):
18
+ return Distance2D.line_segment_to_circle(line_segment, circle) <= 0.0
third_party/tuntunclaw/manipulator_grasp/arm/geometry/rotation/SE3Impl.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import overload, Union, List
2
+
3
+ from spatialmath import SE3, SO3, SE2
4
+ from spatialmath.base import ArrayLike3, SE3Array
5
+
6
+ from .SO3Impl import SO3Impl
7
+
8
+
9
+ class SE3Impl(SE3):
10
+ @overload
11
+ def __init__(self):
12
+ ...
13
+
14
+ @overload
15
+ def __init__(self, x: Union[SE3, SO3, SE2], *, check=True): # copy/promote
16
+ ...
17
+
18
+ @overload
19
+ def __init__(self, x: List[SE3], *, check=True): # import list of SE3
20
+ ...
21
+
22
+ @overload
23
+ def __init__(self, x: float, y: float, z: float, *, check=True): # pure translation
24
+ ...
25
+
26
+ @overload
27
+ def __init__(self, x: ArrayLike3, *, check=True): # pure translation
28
+ ...
29
+
30
+ @overload
31
+ def __init__(self, x: SE3Array, *, check=True): # import native array
32
+ ...
33
+
34
+ @overload
35
+ def __init__(self, x: List[SE3Array], *, check=True): # import native arrays
36
+ ...
37
+
38
+ def __init__(self, x=None, y=None, z=None, *, check=True):
39
+ super().__init__(x, y, z, check=check)
40
+
41
+ def __add__(left, right):
42
+ if isinstance(right, SE3):
43
+ R = SO3Impl(left.R) + SO3Impl(right.R)
44
+ t = left.t + right.t
45
+ T = SE3(t) * SE3(R)
46
+ return SE3Impl(T.A)
47
+ return super().__add__(right)
48
+
49
+ def __sub__(left, right):
50
+ if isinstance(right, SE3):
51
+ R = SO3Impl(left.R) - SO3Impl(right.R)
52
+ t = left.t - right.t
53
+ T = SE3(t) * SE3(R)
54
+ return SE3Impl(T.A)
55
+ return super().__sub__(right)
56
+
57
+ def __mul__(left, right):
58
+ if isinstance(right, SE3):
59
+ return SE3Impl(super().__mul__(right.A))
60
+ elif isinstance(right, (float, int)):
61
+ R = SO3Impl(left.R) * right
62
+ t = left.t * right
63
+ T = SE3(t) * SE3(R)
64
+ return SE3Impl(T.A)
65
+ return super().__mul__(right)
66
+
67
+ def __rmul__(right, left):
68
+ if isinstance(left, SE3):
69
+ return SE3Impl(super().__rmul__(left.A))
70
+ elif isinstance(left, (float, int)):
71
+ R = SO3Impl(right.R) * left
72
+ t = right.t * left
73
+ T = SE3(t) * SE3(R)
74
+ return SE3Impl(T.A)
75
+ return super().__rmul__(left)