Qnancy commited on
Commit
7d9e4fc
·
verified ·
1 Parent(s): e345957

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. Orient_Anything/.gitignore +4 -0
  2. Orient_Anything/LICENSE +395 -0
  3. Orient_Anything/README.md +124 -0
  4. Orient_Anything/Rotation.py +97 -0
  5. Orient_Anything/app.py +72 -0
  6. Orient_Anything/inference.py +49 -0
  7. Orient_Anything/paths.py +4 -0
  8. Orient_Anything/requirements.txt +9 -0
  9. Orient_Anything/utils.py +304 -0
  10. Orient_Anything/vision_tower.py +164 -0
  11. external/Grounded-Segment-Anything/.gitmodules +7 -0
  12. external/Grounded-Segment-Anything/CITATION.cff +8 -0
  13. external/Grounded-Segment-Anything/Dockerfile +30 -0
  14. external/Grounded-Segment-Anything/LICENSE +201 -0
  15. external/Grounded-Segment-Anything/Makefile +43 -0
  16. external/Grounded-Segment-Anything/README.md +808 -0
  17. external/Grounded-Segment-Anything/automatic_label_simple_demo.py +166 -0
  18. external/Grounded-Segment-Anything/grounded_sam_3d_box.ipynb +0 -0
  19. external/Grounded-Segment-Anything/grounded_sam_colab_demo.ipynb +0 -0
  20. external/Grounded-Segment-Anything/grounded_sam_demo.py +242 -0
  21. external/Grounded-Segment-Anything/grounded_sam_osx_demo.py +299 -0
  22. external/Grounded-Segment-Anything/grounding_dino_demo.py +31 -0
  23. external/Grounded-Segment-Anything/predict.py +288 -0
  24. external/Grounded-Segment-Anything/requirements.txt +23 -0
  25. external/Metric3D/.gitignore +5 -0
  26. external/Metric3D/LICENSE +24 -0
  27. external/Metric3D/README.md +396 -0
  28. external/Metric3D/hubconf.py +227 -0
  29. external/Metric3D/requirements_v1.txt +15 -0
  30. external/Metric3D/requirements_v2.txt +16 -0
  31. external/Metric3D/test.sh +15 -0
  32. external/Metric3D/test_kitti.sh +5 -0
  33. external/Metric3D/test_nyu.sh +5 -0
  34. external/Metric3D/test_vit.sh +5 -0
  35. external/WildCamera/LICENSE +201 -0
  36. external/WildCamera/README.md +310 -0
  37. external/WildCamera/hubconf.py +18 -0
  38. processor/__init__.py +0 -0
  39. processor/captions.py +92 -0
  40. processor/pointcloud.py +476 -0
  41. processor/prompt.py +277 -0
  42. processor/prompt_CR.py +687 -0
  43. processor/prompt_ImageEditbench.py +1055 -0
  44. processor/prompt_T2Ibench.py +1296 -0
  45. processor/prompt_utils.py +131 -0
  46. processor/segment.py +238 -0
  47. utils/__init__.py +0 -0
  48. utils/logger.py +159 -0
  49. visualizer/__pycache__/som.cpython-310.pyc +0 -0
  50. visualizer/som.py +1429 -0
Orient_Anything/.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ **/__pycache__
2
+ .gradio
3
+ .locks
4
+ models*
Orient_Anything/LICENSE ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Attribution 4.0 International
2
+
3
+ =======================================================================
4
+
5
+ Creative Commons Corporation ("Creative Commons") is not a law firm and
6
+ does not provide legal services or legal advice. Distribution of
7
+ Creative Commons public licenses does not create a lawyer-client or
8
+ other relationship. Creative Commons makes its licenses and related
9
+ information available on an "as-is" basis. Creative Commons gives no
10
+ warranties regarding its licenses, any material licensed under their
11
+ terms and conditions, or any related information. Creative Commons
12
+ disclaims all liability for damages resulting from their use to the
13
+ fullest extent possible.
14
+
15
+ Using Creative Commons Public Licenses
16
+
17
+ Creative Commons public licenses provide a standard set of terms and
18
+ conditions that creators and other rights holders may use to share
19
+ original works of authorship and other material subject to copyright
20
+ and certain other rights specified in the public license below. The
21
+ following considerations are for informational purposes only, are not
22
+ exhaustive, and do not form part of our licenses.
23
+
24
+ Considerations for licensors: Our public licenses are
25
+ intended for use by those authorized to give the public
26
+ permission to use material in ways otherwise restricted by
27
+ copyright and certain other rights. Our licenses are
28
+ irrevocable. Licensors should read and understand the terms
29
+ and conditions of the license they choose before applying it.
30
+ Licensors should also secure all rights necessary before
31
+ applying our licenses so that the public can reuse the
32
+ material as expected. Licensors should clearly mark any
33
+ material not subject to the license. This includes other CC-
34
+ licensed material, or material used under an exception or
35
+ limitation to copyright. More considerations for licensors:
36
+ wiki.creativecommons.org/Considerations_for_licensors
37
+
38
+ Considerations for the public: By using one of our public
39
+ licenses, a licensor grants the public permission to use the
40
+ licensed material under specified terms and conditions. If
41
+ the licensor's permission is not necessary for any reason--for
42
+ example, because of any applicable exception or limitation to
43
+ copyright--then that use is not regulated by the license. Our
44
+ licenses grant only permissions under copyright and certain
45
+ other rights that a licensor has authority to grant. Use of
46
+ the licensed material may still be restricted for other
47
+ reasons, including because others have copyright or other
48
+ rights in the material. A licensor may make special requests,
49
+ such as asking that all changes be marked or described.
50
+ Although not required by our licenses, you are encouraged to
51
+ respect those requests where reasonable. More considerations
52
+ for the public:
53
+ wiki.creativecommons.org/Considerations_for_licensees
54
+
55
+ =======================================================================
56
+
57
+ Creative Commons Attribution 4.0 International Public License
58
+
59
+ By exercising the Licensed Rights (defined below), You accept and agree
60
+ to be bound by the terms and conditions of this Creative Commons
61
+ Attribution 4.0 International Public License ("Public License"). To the
62
+ extent this Public License may be interpreted as a contract, You are
63
+ granted the Licensed Rights in consideration of Your acceptance of
64
+ these terms and conditions, and the Licensor grants You such rights in
65
+ consideration of benefits the Licensor receives from making the
66
+ Licensed Material available under these terms and conditions.
67
+
68
+
69
+ Section 1 -- Definitions.
70
+
71
+ a. Adapted Material means material subject to Copyright and Similar
72
+ Rights that is derived from or based upon the Licensed Material
73
+ and in which the Licensed Material is translated, altered,
74
+ arranged, transformed, or otherwise modified in a manner requiring
75
+ permission under the Copyright and Similar Rights held by the
76
+ Licensor. For purposes of this Public License, where the Licensed
77
+ Material is a musical work, performance, or sound recording,
78
+ Adapted Material is always produced where the Licensed Material is
79
+ synched in timed relation with a moving image.
80
+
81
+ b. Adapter's License means the license You apply to Your Copyright
82
+ and Similar Rights in Your contributions to Adapted Material in
83
+ accordance with the terms and conditions of this Public License.
84
+
85
+ c. Copyright and Similar Rights means copyright and/or similar rights
86
+ closely related to copyright including, without limitation,
87
+ performance, broadcast, sound recording, and Sui Generis Database
88
+ Rights, without regard to how the rights are labeled or
89
+ categorized. For purposes of this Public License, the rights
90
+ specified in Section 2(b)(1)-(2) are not Copyright and Similar
91
+ Rights.
92
+
93
+ d. Effective Technological Measures means those measures that, in the
94
+ absence of proper authority, may not be circumvented under laws
95
+ fulfilling obligations under Article 11 of the WIPO Copyright
96
+ Treaty adopted on December 20, 1996, and/or similar international
97
+ agreements.
98
+
99
+ e. Exceptions and Limitations means fair use, fair dealing, and/or
100
+ any other exception or limitation to Copyright and Similar Rights
101
+ that applies to Your use of the Licensed Material.
102
+
103
+ f. Licensed Material means the artistic or literary work, database,
104
+ or other material to which the Licensor applied this Public
105
+ License.
106
+
107
+ g. Licensed Rights means the rights granted to You subject to the
108
+ terms and conditions of this Public License, which are limited to
109
+ all Copyright and Similar Rights that apply to Your use of the
110
+ Licensed Material and that the Licensor has authority to license.
111
+
112
+ h. Licensor means the individual(s) or entity(ies) granting rights
113
+ under this Public License.
114
+
115
+ i. Share means to provide material to the public by any means or
116
+ process that requires permission under the Licensed Rights, such
117
+ as reproduction, public display, public performance, distribution,
118
+ dissemination, communication, or importation, and to make material
119
+ available to the public including in ways that members of the
120
+ public may access the material from a place and at a time
121
+ individually chosen by them.
122
+
123
+ j. Sui Generis Database Rights means rights other than copyright
124
+ resulting from Directive 96/9/EC of the European Parliament and of
125
+ the Council of 11 March 1996 on the legal protection of databases,
126
+ as amended and/or succeeded, as well as other essentially
127
+ equivalent rights anywhere in the world.
128
+
129
+ k. You means the individual or entity exercising the Licensed Rights
130
+ under this Public License. Your has a corresponding meaning.
131
+
132
+
133
+ Section 2 -- Scope.
134
+
135
+ a. License grant.
136
+
137
+ 1. Subject to the terms and conditions of this Public License,
138
+ the Licensor hereby grants You a worldwide, royalty-free,
139
+ non-sublicensable, non-exclusive, irrevocable license to
140
+ exercise the Licensed Rights in the Licensed Material to:
141
+
142
+ a. reproduce and Share the Licensed Material, in whole or
143
+ in part; and
144
+
145
+ b. produce, reproduce, and Share Adapted Material.
146
+
147
+ 2. Exceptions and Limitations. For the avoidance of doubt, where
148
+ Exceptions and Limitations apply to Your use, this Public
149
+ License does not apply, and You do not need to comply with
150
+ its terms and conditions.
151
+
152
+ 3. Term. The term of this Public License is specified in Section
153
+ 6(a).
154
+
155
+ 4. Media and formats; technical modifications allowed. The
156
+ Licensor authorizes You to exercise the Licensed Rights in
157
+ all media and formats whether now known or hereafter created,
158
+ and to make technical modifications necessary to do so. The
159
+ Licensor waives and/or agrees not to assert any right or
160
+ authority to forbid You from making technical modifications
161
+ necessary to exercise the Licensed Rights, including
162
+ technical modifications necessary to circumvent Effective
163
+ Technological Measures. For purposes of this Public License,
164
+ simply making modifications authorized by this Section 2(a)
165
+ (4) never produces Adapted Material.
166
+
167
+ 5. Downstream recipients.
168
+
169
+ a. Offer from the Licensor -- Licensed Material. Every
170
+ recipient of the Licensed Material automatically
171
+ receives an offer from the Licensor to exercise the
172
+ Licensed Rights under the terms and conditions of this
173
+ Public License.
174
+
175
+ b. No downstream restrictions. You may not offer or impose
176
+ any additional or different terms or conditions on, or
177
+ apply any Effective Technological Measures to, the
178
+ Licensed Material if doing so restricts exercise of the
179
+ Licensed Rights by any recipient of the Licensed
180
+ Material.
181
+
182
+ 6. No endorsement. Nothing in this Public License constitutes or
183
+ may be construed as permission to assert or imply that You
184
+ are, or that Your use of the Licensed Material is, connected
185
+ with, or sponsored, endorsed, or granted official status by,
186
+ the Licensor or others designated to receive attribution as
187
+ provided in Section 3(a)(1)(A)(i).
188
+
189
+ b. Other rights.
190
+
191
+ 1. Moral rights, such as the right of integrity, are not
192
+ licensed under this Public License, nor are publicity,
193
+ privacy, and/or other similar personality rights; however, to
194
+ the extent possible, the Licensor waives and/or agrees not to
195
+ assert any such rights held by the Licensor to the limited
196
+ extent necessary to allow You to exercise the Licensed
197
+ Rights, but not otherwise.
198
+
199
+ 2. Patent and trademark rights are not licensed under this
200
+ Public License.
201
+
202
+ 3. To the extent possible, the Licensor waives any right to
203
+ collect royalties from You for the exercise of the Licensed
204
+ Rights, whether directly or through a collecting society
205
+ under any voluntary or waivable statutory or compulsory
206
+ licensing scheme. In all other cases the Licensor expressly
207
+ reserves any right to collect such royalties.
208
+
209
+
210
+ Section 3 -- License Conditions.
211
+
212
+ Your exercise of the Licensed Rights is expressly made subject to the
213
+ following conditions.
214
+
215
+ a. Attribution.
216
+
217
+ 1. If You Share the Licensed Material (including in modified
218
+ form), You must:
219
+
220
+ a. retain the following if it is supplied by the Licensor
221
+ with the Licensed Material:
222
+
223
+ i. identification of the creator(s) of the Licensed
224
+ Material and any others designated to receive
225
+ attribution, in any reasonable manner requested by
226
+ the Licensor (including by pseudonym if
227
+ designated);
228
+
229
+ ii. a copyright notice;
230
+
231
+ iii. a notice that refers to this Public License;
232
+
233
+ iv. a notice that refers to the disclaimer of
234
+ warranties;
235
+
236
+ v. a URI or hyperlink to the Licensed Material to the
237
+ extent reasonably practicable;
238
+
239
+ b. indicate if You modified the Licensed Material and
240
+ retain an indication of any previous modifications; and
241
+
242
+ c. indicate the Licensed Material is licensed under this
243
+ Public License, and include the text of, or the URI or
244
+ hyperlink to, this Public License.
245
+
246
+ 2. You may satisfy the conditions in Section 3(a)(1) in any
247
+ reasonable manner based on the medium, means, and context in
248
+ which You Share the Licensed Material. For example, it may be
249
+ reasonable to satisfy the conditions by providing a URI or
250
+ hyperlink to a resource that includes the required
251
+ information.
252
+
253
+ 3. If requested by the Licensor, You must remove any of the
254
+ information required by Section 3(a)(1)(A) to the extent
255
+ reasonably practicable.
256
+
257
+ 4. If You Share Adapted Material You produce, the Adapter's
258
+ License You apply must not prevent recipients of the Adapted
259
+ Material from complying with this Public License.
260
+
261
+
262
+ Section 4 -- Sui Generis Database Rights.
263
+
264
+ Where the Licensed Rights include Sui Generis Database Rights that
265
+ apply to Your use of the Licensed Material:
266
+
267
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right
268
+ to extract, reuse, reproduce, and Share all or a substantial
269
+ portion of the contents of the database;
270
+
271
+ b. if You include all or a substantial portion of the database
272
+ contents in a database in which You have Sui Generis Database
273
+ Rights, then the database in which You have Sui Generis Database
274
+ Rights (but not its individual contents) is Adapted Material; and
275
+
276
+ c. You must comply with the conditions in Section 3(a) if You Share
277
+ all or a substantial portion of the contents of the database.
278
+
279
+ For the avoidance of doubt, this Section 4 supplements and does not
280
+ replace Your obligations under this Public License where the Licensed
281
+ Rights include other Copyright and Similar Rights.
282
+
283
+
284
+ Section 5 -- Disclaimer of Warranties and Limitation of Liability.
285
+
286
+ a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
287
+ EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
288
+ AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
289
+ ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
290
+ IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
291
+ WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
292
+ PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
293
+ ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
294
+ KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
295
+ ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
296
+
297
+ b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
298
+ TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
299
+ NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
300
+ INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
301
+ COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
302
+ USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
303
+ ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
304
+ DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
305
+ IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
306
+
307
+ c. The disclaimer of warranties and limitation of liability provided
308
+ above shall be interpreted in a manner that, to the extent
309
+ possible, most closely approximates an absolute disclaimer and
310
+ waiver of all liability.
311
+
312
+
313
+ Section 6 -- Term and Termination.
314
+
315
+ a. This Public License applies for the term of the Copyright and
316
+ Similar Rights licensed here. However, if You fail to comply with
317
+ this Public License, then Your rights under this Public License
318
+ terminate automatically.
319
+
320
+ b. Where Your right to use the Licensed Material has terminated under
321
+ Section 6(a), it reinstates:
322
+
323
+ 1. automatically as of the date the violation is cured, provided
324
+ it is cured within 30 days of Your discovery of the
325
+ violation; or
326
+
327
+ 2. upon express reinstatement by the Licensor.
328
+
329
+ For the avoidance of doubt, this Section 6(b) does not affect any
330
+ right the Licensor may have to seek remedies for Your violations
331
+ of this Public License.
332
+
333
+ c. For the avoidance of doubt, the Licensor may also offer the
334
+ Licensed Material under separate terms or conditions or stop
335
+ distributing the Licensed Material at any time; however, doing so
336
+ will not terminate this Public License.
337
+
338
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
339
+ License.
340
+
341
+
342
+ Section 7 -- Other Terms and Conditions.
343
+
344
+ a. The Licensor shall not be bound by any additional or different
345
+ terms or conditions communicated by You unless expressly agreed.
346
+
347
+ b. Any arrangements, understandings, or agreements regarding the
348
+ Licensed Material not stated herein are separate from and
349
+ independent of the terms and conditions of this Public License.
350
+
351
+
352
+ Section 8 -- Interpretation.
353
+
354
+ a. For the avoidance of doubt, this Public License does not, and
355
+ shall not be interpreted to, reduce, limit, restrict, or impose
356
+ conditions on any use of the Licensed Material that could lawfully
357
+ be made without permission under this Public License.
358
+
359
+ b. To the extent possible, if any provision of this Public License is
360
+ deemed unenforceable, it shall be automatically reformed to the
361
+ minimum extent necessary to make it enforceable. If the provision
362
+ cannot be reformed, it shall be severed from this Public License
363
+ without affecting the enforceability of the remaining terms and
364
+ conditions.
365
+
366
+ c. No term or condition of this Public License will be waived and no
367
+ failure to comply consented to unless expressly agreed to by the
368
+ Licensor.
369
+
370
+ d. Nothing in this Public License constitutes or may be interpreted
371
+ as a limitation upon, or waiver of, any privileges and immunities
372
+ that apply to the Licensor or You, including from the legal
373
+ processes of any jurisdiction or authority.
374
+
375
+
376
+ =======================================================================
377
+
378
+ Creative Commons is not a party to its public
379
+ licenses. Notwithstanding, Creative Commons may elect to apply one of
380
+ its public licenses to material it publishes and in those instances
381
+ will be considered the “Licensor.” The text of the Creative Commons
382
+ public licenses is dedicated to the public domain under the CC0 Public
383
+ Domain Dedication. Except for the limited purpose of indicating that
384
+ material is shared under a Creative Commons public license or as
385
+ otherwise permitted by the Creative Commons policies published at
386
+ creativecommons.org/policies, Creative Commons does not authorize the
387
+ use of the trademark "Creative Commons" or any other trademark or logo
388
+ of Creative Commons without its prior written consent including,
389
+ without limitation, in connection with any unauthorized modifications
390
+ to any of its public licenses or any other arrangements,
391
+ understandings, or agreements concerning use of licensed material. For
392
+ the avoidance of doubt, this paragraph does not form part of the
393
+ public licenses.
394
+
395
+ Creative Commons may be contacted at creativecommons.org.
Orient_Anything/README.md ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+ <h2>Orient Anything: Learning Robust Object Orientation Estimation from Rendering 3D Models</h2>
3
+
4
+ [**Zehan Wang**](https://scholar.google.com/citations?user=euXK0lkAAAAJ&hl=zh-CN)<sup>1*</sup> · [**Ziang Zhang**](https://scholar.google.com/citations?hl=zh-CN&user=DptGMnYAAAAJ)<sup>1*</sup> · [**Tianyu Pang**](https://scholar.google.com/citations?hl=zh-CN&user=wYDbtFsAAAAJ)<sup>2</sup> · [**Du Chao**](https://scholar.google.com/citations?hl=zh-CN&user=QOp7xW0AAAAJ)<sup>2</sup> · [**Hengshuang Zhao**](https://scholar.google.com/citations?user=4uE10I0AAAAJ&hl&oi=ao)<sup>3</sup> · [**Zhou Zhao**](https://scholar.google.com/citations?user=IIoFY90AAAAJ&hl&oi=ao)<sup>1</sup>
5
+
6
+ <sup>1</sup>Zhejiang University&emsp;&emsp;&emsp;&emsp;<sup>2</sup>SEA AI Lab&emsp;&emsp;&emsp;&emsp;<sup>3</sup>HKU
7
+
8
+ *Equal Contribution
9
+
10
+
11
+ <a href='https://arxiv.org/abs/2412.18605'><img src='https://img.shields.io/badge/arXiv-Orient Anything-red' alt='Paper PDF'></a>
12
+ <a href='https://orient-anything.github.io'><img src='https://img.shields.io/badge/Project_Page-Orient Anything-green' alt='Project Page'></a>
13
+ <a href='https://huggingface.co/spaces/Viglong/Orient-Anything'><img src='https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue'></a>
14
+ <a href='https://huggingface.co/papers/2412.18605'><img src='https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Paper-yellow'></a>
15
+ </div>
16
+
17
+ **Orient Anything**, a robust image-based object orientation estimation model. By training on 2M rendered labeled images, it achieves strong zero-shot generalization ability for images in the wild.
18
+
19
+ ![teaser](assets/demo.png)
20
+
21
+ ## News
22
+ * **2025-05-01:** Orient Anything is accepted by ICML 2025!
23
+ * **2024-12-24:** [Paper](https://arxiv.org/abs/2412.18605), [Project Page](https://orient-anything.github.io), [Code](https://github.com/SpatialVision/Orient-Anything), Models, and [Demo](https://huggingface.co/spaces/Viglong/Orient-Anything) are released.
24
+
25
+
26
+
27
+ ## Pre-trained models
28
+
29
+ We provide **three models** of varying scales for robust object orientation estimation in images:
30
+
31
+ | Model | Params | Checkpoint |
32
+ |:-|-:|:-:|
33
+ | Orient-Anything-Small | 23.3 M | [Download](https://huggingface.co/Viglong/OriNet/blob/main/cropsmallEx03/dino_weight.pt) |
34
+ | Orient-Anything-Base | 87.8 M | [Download](https://huggingface.co/Viglong/OriNet/blob/main/cropbaseEx032/dino_weight.pt) |
35
+ | Orient-Anything-Large | 305 M | [Download](https://huggingface.co/Viglong/OriNet/blob/main/croplargeEX2/dino_weight.pt) |
36
+
37
+ ## Usage
38
+
39
+ ### 1 Prepraration
40
+
41
+ ```bash
42
+ pip install -r requirements.txt
43
+ ```
44
+
45
+ ### 2 Use our models
46
+ #### 2.1 In Gradio app
47
+ Start gradio by executing the following script:
48
+
49
+ ```bash
50
+ python app.py
51
+ ```
52
+ then open GUI page(default is https://127.0.0.1:7860) in web browser.
53
+
54
+ or, you can try it in our [Huggingface-Space](https://huggingface.co/spaces/Viglong/Orient-Anything)
55
+
56
+ #### 2.2 In Python Scripts
57
+ ```python
58
+ from paths import *
59
+ from vision_tower import DINOv2_MLP
60
+ from transformers import AutoImageProcessor
61
+ import torch
62
+ from PIL import Image
63
+
64
+ import torch.nn.functional as F
65
+ from utils import *
66
+ from inference import *
67
+
68
+ from huggingface_hub import hf_hub_download
69
+ ckpt_path = hf_hub_download(repo_id="Viglong/Orient-Anything", filename="croplargeEX2/dino_weight.pt", repo_type="model", cache_dir='./', resume_download=True)
70
+ print(ckpt_path)
71
+
72
+ save_path = './'
73
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
74
+ dino = DINOv2_MLP(
75
+ dino_mode = 'large',
76
+ in_dim = 1024,
77
+ out_dim = 360+180+180+2,
78
+ evaluate = True,
79
+ mask_dino = False,
80
+ frozen_back = False
81
+ )
82
+
83
+ dino.eval()
84
+ print('model create')
85
+ dino.load_state_dict(torch.load(ckpt_path, map_location='cpu'))
86
+ dino = dino.to(device)
87
+ print('weight loaded')
88
+ val_preprocess = AutoImageProcessor.from_pretrained(DINO_LARGE, cache_dir='./')
89
+
90
+ image_path = '/path/to/image'
91
+ origin_image = Image.open(image_path).convert('RGB')
92
+ angles = get_3angle(origin_image, dino, val_preprocess, device)
93
+ azimuth = float(angles[0])
94
+ polar = float(angles[1])
95
+ rotation = float(angles[2])
96
+ confidence = float(angles[3])
97
+
98
+
99
+ ```
100
+
101
+
102
+ ### Best Practice
103
+ To avoid ambiguity, our model only supports inputs that contain images of a single object. For daily images that usually contain multiple objects, it is a good choice to isolate each object with DINO-grounding and predict the orientation separately.
104
+ ```python
105
+ [ToDo]
106
+ ```
107
+ ### Test-Time Augmentation
108
+ In order to further enhance the robustness of the model,We further propose the test-time ensemble strategy. The input images will be randomly cropped into different variants, and the predicted orientation of different variants will be voted as the final prediction result. We implement this strategy in functions `get_3angle_infer_aug()` and `get_crop_images()`.
109
+
110
+ ## Citation
111
+
112
+ If you find this project useful, please consider citing:
113
+
114
+ ```bibtex
115
+ @article{orient_anything,
116
+ title={Orient Anything: Learning Robust Object Orientation Estimation from Rendering 3D Models},
117
+ author={Wang, Zehan and Zhang, Ziang and Pang, Tianyu and Du, Chao and Zhao, Hengshuang and Zhao, Zhou},
118
+ journal={arXiv:2412.18605},
119
+ year={2024}
120
+ }
121
+ ```
122
+
123
+ ## Acknowledgement
124
+ Thanks to the open source of the following projects: [Grounded-Segment-Anything](https://github.com/IDEA-Research/Grounded-Segment-Anything), [render-py](https://github.com/tvytlx/render-py)
Orient_Anything/Rotation.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from osdsynth.Orient_Anything.paths import *
2
+ from osdsynth.Orient_Anything.vision_tower import DINOv2_MLP
3
+ from transformers import AutoImageProcessor
4
+ import torch
5
+ from PIL import Image
6
+
7
+ import torch.nn.functional as F
8
+ from osdsynth.Orient_Anything.utils import *
9
+ from osdsynth.Orient_Anything.inference import *
10
+ from osdsynth.utils.logger import SkipImageException
11
+
12
+
13
+ class Rotation:
14
+ def __init__(self, cfg, logger, device):
15
+ self.rotation_model = DINOv2_MLP(
16
+ dino_mode = 'large',
17
+ in_dim = 1024,
18
+ out_dim = 360+180+180+2,
19
+ evaluate = True,
20
+ mask_dino = False,
21
+ frozen_back = False
22
+ ).eval()
23
+ self.rotation_model.load_state_dict(torch.load(cfg.rotation_model_ckpt_path, map_location='cpu'))
24
+ self.rotation_model = self.rotation_model.to(device)
25
+ self.val_preprocess = AutoImageProcessor.from_pretrained(DINO_LARGE, cache_dir='./')
26
+ self.logger = logger
27
+ self.device = device
28
+
29
+ def get_R(self, phi, theta, gamma):
30
+ R = np.array([[-math.sin(phi), 0, -math.cos(phi)],
31
+ [math.cos(phi) * math.sin(theta), -math.cos(theta), -math.sin(phi) * math.sin(theta)],
32
+ [-math.cos(phi) * math.cos(theta), -math.sin(theta), math.sin(phi) * math.cos(theta)]
33
+ ]) # The position of the object as seen by the camera
34
+
35
+ # R rotates gamma around the z-axis of the world coordinate system
36
+ gamma = gamma * math.pi / 180
37
+ R = np.dot(R, np.array([[math.cos(gamma), -math.sin(gamma), 0],
38
+ [math.sin(gamma), math.cos(gamma), 0],
39
+ [0, 0, 1]
40
+ ]))
41
+
42
+
43
+
44
+ return R
45
+
46
+ def process_single(self, image_segment_wbg, do_rm_bkg=True, do_infer_aug=False):
47
+ origin_img_wbg = Image.fromarray(image_segment_wbg) if isinstance(image_segment_wbg, np.ndarray) else image_segment_wbg
48
+ if do_infer_aug:
49
+ rm_bkg_img = background_preprocess(origin_img_wbg, True)
50
+ angles = get_3angle_infer_aug(origin_img_wbg, rm_bkg_img, self.rotation_model, self.val_preprocess, self.device)
51
+ else:
52
+ rm_bkg_img = background_preprocess(origin_img_wbg, False)
53
+ angles = get_3angle(rm_bkg_img, self.rotation_model, self.val_preprocess, self.device)
54
+ confidence = float(angles[3])
55
+
56
+ if confidence < 0.5:
57
+ do_rm_bkg_img = background_preprocess(origin_img_wbg, True)
58
+ do_angles = get_3angle(do_rm_bkg_img, self.rotation_model, self.val_preprocess, self.device)
59
+ do_confidence = float(do_angles[3])
60
+ if do_confidence >0.5 :
61
+ rm_bkg_img = do_rm_bkg_img
62
+ angles = do_angles
63
+
64
+
65
+ phi = np.radians(angles[0])
66
+ theta = np.radians(angles[1])
67
+ gamma = angles[2]
68
+ confidence = float(angles[3])
69
+
70
+
71
+
72
+ render_axis = render_3D_axis(phi, theta, gamma)
73
+ res_img = overlay_images_with_scaling(render_axis, rm_bkg_img)
74
+ res_img.save("res_img.png")
75
+ rotation_matrix = self.get_R(phi=phi, theta=theta, gamma=gamma)
76
+ return rotation_matrix, confidence
77
+
78
+
79
+ def process(self, detection_list, do_rm_bkg=True, do_infer_aug=False):
80
+ skip_index = []
81
+ for i in range(len(detection_list)):
82
+ # image_segment_wobg = detection_list[i]['image_segment']
83
+ image_segment_wbg = detection_list[i]['image_crop']
84
+
85
+ # object-centered reference system, the camera's bit position
86
+ rotation_matrix, confidence = self.process_single(image_segment_wbg, do_rm_bkg=do_rm_bkg, do_infer_aug=do_infer_aug)
87
+
88
+ # For the camera, the position and rotation of the object
89
+ detection_list[i]['rotation_matrix'] = rotation_matrix
90
+ detection_list[i]['rotation_matrix_confidence'] = confidence
91
+
92
+ # 删除不符合条件的项
93
+ for i in skip_index[::-1]:
94
+ del detection_list[i]
95
+
96
+
97
+ return detection_list
Orient_Anything/app.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from paths import *
3
+
4
+ from vision_tower import DINOv2_MLP
5
+ from transformers import AutoImageProcessor
6
+ import torch
7
+ from inference import *
8
+ from utils import *
9
+
10
+ from huggingface_hub import hf_hub_download
11
+ ckpt_path = hf_hub_download(repo_id="Viglong/Orient-Anything", filename="ronormsigma1/dino_weight.pt", repo_type="model", cache_dir='./', resume_download=True)
12
+ print(ckpt_path)
13
+
14
+ save_path = './'
15
+ device = 'cpu'
16
+ dino = DINOv2_MLP(
17
+ dino_mode = 'large',
18
+ in_dim = 1024,
19
+ out_dim = 360+180+360+2,
20
+ evaluate = True,
21
+ mask_dino = False,
22
+ frozen_back = False
23
+ )
24
+
25
+ dino.eval()
26
+ print('model create')
27
+ dino.load_state_dict(torch.load(ckpt_path, map_location='cpu'))
28
+ dino = dino.to(device)
29
+ print('weight loaded')
30
+ val_preprocess = AutoImageProcessor.from_pretrained(DINO_LARGE, cache_dir='./')
31
+
32
+ def infer_func(img, do_rm_bkg, do_infer_aug):
33
+ origin_img = Image.fromarray(img)
34
+ if do_infer_aug:
35
+ rm_bkg_img = background_preprocess(origin_img, True)
36
+ angles = get_3angle_infer_aug(origin_img, rm_bkg_img, dino, val_preprocess, device)
37
+ else:
38
+ rm_bkg_img = background_preprocess(origin_img, do_rm_bkg)
39
+ angles = get_3angle(rm_bkg_img, dino, val_preprocess, device)
40
+
41
+ phi = np.radians(angles[0])
42
+ theta = np.radians(angles[1])
43
+ gamma = angles[2]
44
+ confidence = float(angles[3])
45
+ if confidence > 0.5:
46
+ render_axis = render_3D_axis(phi, theta, gamma)
47
+ res_img = overlay_images_with_scaling(render_axis, rm_bkg_img)
48
+ else:
49
+ res_img = img
50
+
51
+ # axis_model = "axis.obj"
52
+ return [res_img, round(float(angles[0]), 2), round(float(angles[1]), 2), round(float(angles[2]), 2), round(float(angles[3]), 2)]
53
+
54
+ server = gr.Interface(
55
+ flagging_mode='never',
56
+ fn=infer_func,
57
+ inputs=[
58
+ gr.Image(height=512, width=512, label="upload your image"),
59
+ gr.Checkbox(label="Remove Background", value=True),
60
+ gr.Checkbox(label="Inference time augmentation", value=False)
61
+ ],
62
+ outputs=[
63
+ gr.Image(height=512, width=512, label="result image"),
64
+ # gr.Model3D(clear_color=[0.0, 0.0, 0.0, 0.0], label="3D Model"),
65
+ gr.Textbox(lines=1, label='Azimuth(0~360°)'),
66
+ gr.Textbox(lines=1, label='Polar(-90~90°)'),
67
+ gr.Textbox(lines=1, label='Rotation(-90~90°)'),
68
+ gr.Textbox(lines=1, label='Confidence(0~1)')
69
+ ]
70
+ )
71
+
72
+ server.launch()
Orient_Anything/inference.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from PIL import Image
3
+ from osdsynth.Orient_Anything.utils import *
4
+ import torch.nn.functional as F
5
+ import numpy as np
6
+
7
+ def get_3angle(image, dino, val_preprocess, device):
8
+
9
+ # image = Image.open(image_path).convert('RGB')
10
+ image_inputs = val_preprocess(images = image)
11
+ image_inputs['pixel_values'] = torch.from_numpy(np.array(image_inputs['pixel_values'])).to(device)
12
+ with torch.no_grad():
13
+ dino_pred = dino(image_inputs)
14
+
15
+ gaus_ax_pred = torch.argmax(dino_pred[:, 0:360], dim=-1)
16
+ gaus_pl_pred = torch.argmax(dino_pred[:, 360:360+180], dim=-1)
17
+ gaus_ro_pred = torch.argmax(dino_pred[:, 360+180:360+180+180], dim=-1)
18
+ confidence = F.softmax(dino_pred[:, -2:], dim=-1)[0][0]
19
+ angles = torch.zeros(4)
20
+ angles[0] = gaus_ax_pred
21
+ angles[1] = gaus_pl_pred - 90
22
+ angles[2] = gaus_ro_pred - 90
23
+ angles[3] = confidence
24
+ return angles
25
+
26
+ def get_3angle_infer_aug(origin_img, rm_bkg_img, dino, val_preprocess, device):
27
+
28
+ # image = Image.open(image_path).convert('RGB')
29
+ image = get_crop_images(origin_img, num=3) + get_crop_images(rm_bkg_img, num=3)
30
+ image_inputs = val_preprocess(images = image)
31
+ image_inputs['pixel_values'] = torch.from_numpy(np.array(image_inputs['pixel_values'])).to(device)
32
+ with torch.no_grad():
33
+ dino_pred = dino(image_inputs)
34
+
35
+ gaus_ax_pred = torch.argmax(dino_pred[:, 0:360], dim=-1).to(torch.float32)
36
+ gaus_pl_pred = torch.argmax(dino_pred[:, 360:360+180], dim=-1).to(torch.float32)
37
+ gaus_ro_pred = torch.argmax(dino_pred[:, 360+180:360+180+180], dim=-1).to(torch.float32)
38
+
39
+ gaus_ax_pred = remove_outliers_and_average_circular(gaus_ax_pred)
40
+ gaus_pl_pred = remove_outliers_and_average(gaus_pl_pred)
41
+ gaus_ro_pred = remove_outliers_and_average(gaus_ro_pred)
42
+
43
+ confidence = torch.mean(F.softmax(dino_pred[:, -2:], dim=-1), dim=0)[0]
44
+ angles = torch.zeros(4)
45
+ angles[0] = gaus_ax_pred
46
+ angles[1] = gaus_pl_pred - 90
47
+ angles[2] = gaus_ro_pred - 90
48
+ angles[3] = confidence
49
+ return angles
Orient_Anything/paths.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ DINO_SMALL = "facebook/dinov2-small"
2
+ DINO_BASE = "facebook/dinov2-base"
3
+ DINO_LARGE = "/mnt/prev_nas/qhy/dinov2-large"
4
+ DINO_GIANT = "facebook/dinov2-giant"
Orient_Anything/requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ torch==2.2.1
2
+ transformers==4.38
3
+ matplotlib
4
+ pillow==10.2.0
5
+ huggingface-hub==0.26.5
6
+ gradio==5.9.0
7
+ numpy==1.26.4
8
+ onnxruntime
9
+ rembg
Orient_Anything/utils.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import rembg
2
+ import random
3
+ import torch
4
+ import numpy as np
5
+ from PIL import Image, ImageOps
6
+ import PIL
7
+ from typing import Any
8
+ import matplotlib.pyplot as plt
9
+ import io
10
+
11
+ def resize_foreground(
12
+ image: Image,
13
+ ratio: float,
14
+ ) -> Image:
15
+ image = np.array(image)
16
+ assert image.shape[-1] == 4
17
+ alpha = np.where(image[..., 3] > 0)
18
+ y1, y2, x1, x2 = (
19
+ alpha[0].min(),
20
+ alpha[0].max(),
21
+ alpha[1].min(),
22
+ alpha[1].max(),
23
+ )
24
+ # crop the foreground
25
+ fg = image[y1:y2, x1:x2]
26
+ # pad to square
27
+ size = max(fg.shape[0], fg.shape[1])
28
+ ph0, pw0 = (size - fg.shape[0]) // 2, (size - fg.shape[1]) // 2
29
+ ph1, pw1 = size - fg.shape[0] - ph0, size - fg.shape[1] - pw0
30
+ new_image = np.pad(
31
+ fg,
32
+ ((ph0, ph1), (pw0, pw1), (0, 0)),
33
+ mode="constant",
34
+ constant_values=((0, 0), (0, 0), (0, 0)),
35
+ )
36
+
37
+ # compute padding according to the ratio
38
+ new_size = int(new_image.shape[0] / ratio)
39
+ # pad to size, double side
40
+ ph0, pw0 = (new_size - size) // 2, (new_size - size) // 2
41
+ ph1, pw1 = new_size - size - ph0, new_size - size - pw0
42
+ new_image = np.pad(
43
+ new_image,
44
+ ((ph0, ph1), (pw0, pw1), (0, 0)),
45
+ mode="constant",
46
+ constant_values=((0, 0), (0, 0), (0, 0)),
47
+ )
48
+ new_image = Image.fromarray(new_image)
49
+ return new_image
50
+
51
+ def remove_background(image: Image,
52
+ rembg_session: Any = None,
53
+ force: bool = False,
54
+ **rembg_kwargs,
55
+ ) -> Image:
56
+ do_remove = True
57
+ if image.mode == "RGBA" and image.getextrema()[3][0] < 255:
58
+ do_remove = False
59
+ do_remove = do_remove or force
60
+ if do_remove:
61
+ image = rembg.remove(image, session=rembg_session, **rembg_kwargs)
62
+ return image
63
+
64
+ def random_crop(image, crop_scale=(0.8, 0.95)):
65
+ """
66
+ 随机裁切图片
67
+ image (numpy.ndarray): (H, W, C)。
68
+ crop_scale (tuple): (min_scale, max_scale)。
69
+ """
70
+ assert isinstance(image, Image.Image), "iput must be PIL.Image.Image"
71
+ assert len(crop_scale) == 2 and 0 < crop_scale[0] <= crop_scale[1] <= 1
72
+
73
+ width, height = image.size
74
+
75
+ # 计算裁切的高度和宽度
76
+ crop_width = random.randint(int(width * crop_scale[0]), int(width * crop_scale[1]))
77
+ crop_height = random.randint(int(height * crop_scale[0]), int(height * crop_scale[1]))
78
+
79
+ # 随机选择裁切的起始点
80
+ left = random.randint(0, width - crop_width)
81
+ top = random.randint(0, height - crop_height)
82
+
83
+ # 裁切图片
84
+ cropped_image = image.crop((left, top, left + crop_width, top + crop_height))
85
+
86
+ return cropped_image
87
+
88
+ def get_crop_images(img, num=3):
89
+ cropped_images = []
90
+ for i in range(num):
91
+ cropped_images.append(random_crop(img))
92
+ return cropped_images
93
+
94
+ def background_preprocess(input_image, do_remove_background):
95
+
96
+ rembg_session = rembg.new_session() if do_remove_background else None
97
+
98
+ if do_remove_background:
99
+ input_image = remove_background(input_image, rembg_session)
100
+ input_image = resize_foreground(input_image, 0.85)
101
+
102
+ return input_image
103
+
104
+ def remove_outliers_and_average(tensor, threshold=1.5):
105
+ assert tensor.dim() == 1, "dimension of input Tensor must equal to 1"
106
+
107
+ q1 = torch.quantile(tensor, 0.25)
108
+ q3 = torch.quantile(tensor, 0.75)
109
+ iqr = q3 - q1
110
+
111
+ lower_bound = q1 - threshold * iqr
112
+ upper_bound = q3 + threshold * iqr
113
+
114
+ non_outliers = tensor[(tensor >= lower_bound) & (tensor <= upper_bound)]
115
+
116
+ if len(non_outliers) == 0:
117
+ return tensor.mean().item()
118
+
119
+ return non_outliers.mean().item()
120
+
121
+
122
+ def remove_outliers_and_average_circular(tensor, threshold=1.5):
123
+ assert tensor.dim() == 1, "dimension of input Tensor must equal to 1"
124
+
125
+ # 将角度转换为二维平面上的点
126
+ radians = tensor * torch.pi / 180.0
127
+ x_coords = torch.cos(radians)
128
+ y_coords = torch.sin(radians)
129
+
130
+ # 计算平均向量
131
+ mean_x = torch.mean(x_coords)
132
+ mean_y = torch.mean(y_coords)
133
+
134
+ differences = torch.sqrt((x_coords - mean_x) * (x_coords - mean_x) + (y_coords - mean_y) * (y_coords - mean_y))
135
+
136
+ # 计算四分位数和 IQR
137
+ q1 = torch.quantile(differences, 0.25)
138
+ q3 = torch.quantile(differences, 0.75)
139
+ iqr = q3 - q1
140
+
141
+ # 计算上下限
142
+ lower_bound = q1 - threshold * iqr
143
+ upper_bound = q3 + threshold * iqr
144
+
145
+ # 筛选非离群点
146
+ non_outliers = tensor[(differences >= lower_bound) & (differences <= upper_bound)]
147
+
148
+ if len(non_outliers) == 0:
149
+ mean_angle = torch.atan2(mean_y, mean_x) * 180.0 / torch.pi
150
+ mean_angle = (mean_angle + 360) % 360
151
+ return mean_angle # 如果没有非离群点,返回 None
152
+
153
+ # 对非离群点再次计算平均向量
154
+ radians = non_outliers * torch.pi / 180.0
155
+ x_coords = torch.cos(radians)
156
+ y_coords = torch.sin(radians)
157
+
158
+ mean_x = torch.mean(x_coords)
159
+ mean_y = torch.mean(y_coords)
160
+
161
+ mean_angle = torch.atan2(mean_y, mean_x) * 180.0 / torch.pi
162
+ mean_angle = (mean_angle + 360) % 360
163
+
164
+ return mean_angle
165
+
166
+ def scale(x):
167
+ # print(x)
168
+ # if abs(x[0])<0.1 and abs(x[1])<0.1:
169
+
170
+ # return x*5
171
+ # else:
172
+ # return x
173
+ return x*3
174
+
175
+ def get_proj2D_XYZ(phi, theta, gamma):
176
+ x = np.array([-1*np.sin(phi)*np.cos(gamma) - np.cos(phi)*np.sin(theta)*np.sin(gamma), np.sin(phi)*np.sin(gamma) - np.cos(phi)*np.sin(theta)*np.cos(gamma)])
177
+ y = np.array([-1*np.cos(phi)*np.cos(gamma) + np.sin(phi)*np.sin(theta)*np.sin(gamma), np.cos(phi)*np.sin(gamma) + np.sin(phi)*np.sin(theta)*np.cos(gamma)])
178
+ z = np.array([np.cos(theta)*np.sin(gamma), np.cos(theta)*np.cos(gamma)])
179
+ x = scale(x)
180
+ y = scale(y)
181
+ z = scale(z)
182
+ return x, y, z
183
+
184
+ # 绘制3D坐标轴
185
+ def draw_axis(ax, origin, vector, color, label=None):
186
+ ax.quiver(origin[0], origin[1], vector[0], vector[1], angles='xy', scale_units='xy', scale=1, color=color)
187
+ if label!=None:
188
+ ax.text(origin[0] + vector[0] * 1.1, origin[1] + vector[1] * 1.1, label, color=color, fontsize=12)
189
+
190
+ def matplotlib_2D_arrow(angles, rm_bkg_img):
191
+ fig, ax = plt.subplots(figsize=(8, 8))
192
+
193
+ # 设置旋转角度
194
+ phi = np.radians(angles[0])
195
+ theta = np.radians(angles[1])
196
+ gamma = np.radians(-1*angles[2])
197
+
198
+ w, h = rm_bkg_img.size
199
+ if h>w:
200
+ extent = [-5*w/h, 5*w/h, -5, 5]
201
+ else:
202
+ extent = [-5, 5, -5*h/w, 5*h/w]
203
+ ax.imshow(rm_bkg_img, extent=extent, zorder=0, aspect ='auto') # extent 设置图片的显示范围
204
+
205
+ origin = np.array([0, 0])
206
+
207
+ # 旋转后的向量
208
+ rot_x, rot_y, rot_z = get_proj2D_XYZ(phi, theta, gamma)
209
+
210
+ # draw arrow
211
+ arrow_attr = [{'point':rot_x, 'color':'r', 'label':'front'},
212
+ {'point':rot_y, 'color':'g', 'label':'right'},
213
+ {'point':rot_z, 'color':'b', 'label':'top'}]
214
+
215
+ if phi> 45 and phi<=225:
216
+ order = [0,1,2]
217
+ elif phi > 225 and phi < 315:
218
+ order = [2,0,1]
219
+ else:
220
+ order = [2,1,0]
221
+
222
+ for i in range(3):
223
+ draw_axis(ax, origin, arrow_attr[order[i]]['point'], arrow_attr[order[i]]['color'], arrow_attr[order[i]]['label'])
224
+ # draw_axis(ax, origin, rot_y, 'g', label='right')
225
+ # draw_axis(ax, origin, rot_z, 'b', label='top')
226
+ # draw_axis(ax, origin, rot_x, 'r', label='front')
227
+
228
+ # 关闭坐标轴和网格
229
+ ax.set_axis_off()
230
+ ax.grid(False)
231
+
232
+ # 设置坐标范围
233
+ ax.set_xlim(-5, 5)
234
+ ax.set_ylim(-5, 5)
235
+
236
+ def figure_to_img(fig):
237
+ with io.BytesIO() as buf:
238
+ fig.savefig(buf, format='JPG', bbox_inches='tight')
239
+ buf.seek(0)
240
+ image = Image.open(buf).copy()
241
+ return image
242
+
243
+ from render import render, Model
244
+ import math
245
+ axis_model = Model("/mnt/prev_nas/qhy_1/GenSpace/osdsynth/Orient_Anything/assets/axis.obj", texture_filename="/mnt/prev_nas/qhy_1/GenSpace/osdsynth/Orient_Anything/assets/axis.png")
246
+ def render_3D_axis(phi, theta, gamma):
247
+ radius = 240
248
+ # camera_location = [radius * math.cos(phi), radius * math.sin(phi), radius * math.tan(theta)]
249
+ # print(camera_location)
250
+ camera_location = [-1*radius * math.cos(phi), -1*radius * math.tan(theta), radius * math.sin(phi)]
251
+ img = render(
252
+ # Model("res/jinx.obj", texture_filename="res/jinx.tga"),
253
+ axis_model,
254
+ height=512,
255
+ width=512,
256
+ filename="tmp_render.png",
257
+ cam_loc = camera_location
258
+ )
259
+ img = img.rotate(gamma)
260
+ return img
261
+
262
+ def overlay_images_with_scaling(center_image: Image.Image, background_image, target_size=(512, 512)):
263
+ """
264
+ 调整前景图像大小为 512x512,将背景图像缩放以适配,并中心对齐叠加
265
+ :param center_image: 前景图像
266
+ :param background_image: 背景图像
267
+ :param target_size: 前景图像的目标大小,默认 (512, 512)
268
+ :return: 叠加后的图像
269
+ """
270
+ # 确保输入图像为 RGBA 模式
271
+ if center_image.mode != "RGBA":
272
+ center_image = center_image.convert("RGBA")
273
+ if background_image.mode != "RGBA":
274
+ background_image = background_image.convert("RGBA")
275
+
276
+ # 调整前景图像大小
277
+ center_image = center_image.resize(target_size)
278
+
279
+ # 缩放背景图像,确保其适合前景图像的尺寸
280
+ bg_width, bg_height = background_image.size
281
+
282
+ # 按宽度或高度等比例缩放背景
283
+ scale = target_size[0] / max(bg_width, bg_height)
284
+ new_width = int(bg_width * scale)
285
+ new_height = int(bg_height * scale)
286
+ resized_background = background_image.resize((new_width, new_height))
287
+ # 计算需要的填充量
288
+ pad_width = target_size[0] - new_width
289
+ pad_height = target_size[0] - new_height
290
+
291
+ # 计算上下左右的 padding
292
+ left = pad_width // 2
293
+ right = pad_width - left
294
+ top = pad_height // 2
295
+ bottom = pad_height - top
296
+
297
+ # 添加 padding
298
+ resized_background = ImageOps.expand(resized_background, border=(left, top, right, bottom), fill=(255,255,255,255))
299
+
300
+ # 将前景图像叠加到背景图像上
301
+ result = resized_background.copy()
302
+ result.paste(center_image, (0, 0), mask=center_image)
303
+
304
+ return result
Orient_Anything/vision_tower.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ sys.path.append("/mnt/prev_nas/qhy_1/GenSpace/osdsynth/Orient_Anything")
3
+
4
+ import torch
5
+ from torch import nn
6
+ import torch.nn.init as init
7
+ import torch.nn.functional as F
8
+
9
+ from paths import *
10
+
11
+ from typing import Dict, List, Optional, Set, Tuple, Union
12
+ from transformers import AutoImageProcessor, AutoModel, Dinov2Model
13
+ from transformers.models.dinov2.modeling_dinov2 import Dinov2Embeddings
14
+ from transformers.models.dinov2.configuration_dinov2 import Dinov2Config
15
+ import numpy as np
16
+ from contextlib import nullcontext
17
+
18
+ def get_activation(activation):
19
+ if activation.lower() == 'gelu':
20
+ return nn.GELU()
21
+ elif activation.lower() == 'rrelu':
22
+ return nn.RReLU(inplace=True)
23
+ elif activation.lower() == 'selu':
24
+ return nn.SELU(inplace=True)
25
+ elif activation.lower() == 'silu':
26
+ return nn.SiLU(inplace=True)
27
+ elif activation.lower() == 'hardswish':
28
+ return nn.Hardswish(inplace=True)
29
+ elif activation.lower() == 'leakyrelu':
30
+ return nn.LeakyReLU(inplace=True)
31
+ elif activation.lower() == 'sigmoid':
32
+ return nn.Sigmoid()
33
+ elif activation.lower() == 'tanh':
34
+ return nn.Tanh()
35
+ else:
36
+ return nn.ReLU(inplace=True)
37
+
38
+
39
+
40
+ class MLP_dim(nn.Module):
41
+ def __init__(
42
+ self, in_dim=512, out_dim=1024, bias=True, activation='relu'):
43
+ super().__init__()
44
+ self.act = get_activation(activation)
45
+ self.net1 = nn.Sequential(
46
+ nn.Linear(in_dim, int(out_dim), bias=bias),
47
+ nn.BatchNorm1d(int(out_dim)),
48
+ self.act
49
+ )
50
+ self.net2 = nn.Sequential(
51
+ nn.Linear(int(out_dim), out_dim, bias=bias),
52
+ nn.BatchNorm1d(out_dim)
53
+ )
54
+
55
+ def forward(self, x):
56
+ return self.net2(self.net1(x))
57
+
58
+ class FLIP_Dinov2Embeddings(Dinov2Embeddings):
59
+ """
60
+ Construct the CLS token, mask token, position and patch embeddings.
61
+ """
62
+
63
+ def __init__(self, config: Dinov2Config) -> None:
64
+ super().__init__(config)
65
+
66
+ def forward(self, pixel_values: torch.Tensor, bool_masked_pos: Optional[torch.Tensor] = None) -> torch.Tensor:
67
+ batch_size, _, height, width = pixel_values.shape
68
+ target_dtype = self.patch_embeddings.projection.weight.dtype
69
+ embeddings = self.patch_embeddings(pixel_values.to(dtype=target_dtype))
70
+
71
+ # add the [CLS] token to the embedded patch tokens
72
+ cls_tokens = self.cls_token.expand(batch_size, -1, -1)
73
+ embeddings = torch.cat((cls_tokens, embeddings), dim=1)
74
+
75
+ # add positional encoding to each token
76
+ embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
77
+
78
+ if bool_masked_pos is not None:
79
+ # embeddings = torch.where(
80
+ # bool_masked_pos.unsqueeze(-1), self.mask_token.to(embeddings.dtype).unsqueeze(0), embeddings
81
+ # )
82
+ B,S,D = embeddings.shape
83
+ batch_indices = torch.arange(B).unsqueeze(1)
84
+ embeddings = embeddings[batch_indices, bool_masked_pos]
85
+
86
+ embeddings = self.dropout(embeddings)
87
+
88
+ return embeddings
89
+
90
+ class FLIP_DINOv2(Dinov2Model):
91
+ def __init__(self, config):
92
+ super().__init__(config)
93
+
94
+ self.embeddings = FLIP_Dinov2Embeddings(config)
95
+
96
+ class DINOv2_MLP(nn.Module):
97
+ def __init__(self,
98
+ dino_mode,
99
+ in_dim,
100
+ out_dim,
101
+ evaluate,
102
+ mask_dino,
103
+ frozen_back
104
+ ) -> None:
105
+ super().__init__()
106
+ # self.dinov2 = AutoModel.from_pretrained(DINO_BASE)
107
+ if dino_mode == 'base':
108
+ self.dinov2 = FLIP_DINOv2.from_pretrained(DINO_BASE, cache_dir='./')
109
+ elif dino_mode == 'large':
110
+ self.dinov2 = FLIP_DINOv2.from_pretrained(DINO_LARGE, cache_dir='./')
111
+ elif dino_mode == 'small':
112
+ self.dinov2 = FLIP_DINOv2.from_pretrained(DINO_SMALL, cache_dir='./')
113
+ elif dino_mode == 'giant':
114
+ self.dinov2 = FLIP_DINOv2.from_pretrained(DINO_GIANT, cache_dir='./')
115
+
116
+ self.down_sampler = MLP_dim(in_dim=in_dim, out_dim=out_dim)
117
+ self.random_mask = False
118
+ if not evaluate:
119
+ self.init_weights(self.down_sampler)
120
+ self.random_mask = mask_dino
121
+ if frozen_back:
122
+ self.forward_mode = torch.no_grad()
123
+ else:
124
+ self.forward_mode = nullcontext()
125
+
126
+ def forward(self, img_inputs):
127
+ device = self.get_device()
128
+ # print(img_inputs['pixel_values'].shape)
129
+
130
+ with self.forward_mode:
131
+ if self.random_mask:
132
+ B = len(img_inputs['pixel_values'])
133
+ S = 256
134
+ indices = []
135
+ for i in range(B):
136
+ tmp = torch.randperm(S)[:S//2]
137
+ tmp = tmp.sort().values + 1
138
+ indices.append(tmp)
139
+ indices = torch.stack(indices, dim=0)
140
+ indices = torch.cat([torch.zeros(B, 1, dtype=torch.long, device='cpu'), indices], dim=1)
141
+ # print(indices.shape)
142
+ img_inputs['bool_masked_pos'] = indices.to(device)
143
+
144
+ dino_outputs = self.dinov2(**img_inputs)
145
+ dino_seq = dino_outputs.last_hidden_state
146
+ # B,S,_ = dino_seq.shape
147
+ # dino_seq = dino_seq.view(B*S,-1)
148
+ dino_seq = dino_seq[:,0,:]
149
+
150
+ down_sample_out = self.down_sampler(dino_seq)
151
+ # down_sample_out = down_sample_out.view(B,S,-1)
152
+ # down_sample_out = down_sample_out[:,0,:]
153
+
154
+ return down_sample_out
155
+
156
+ def get_device(self):
157
+ return next(self.parameters()).device
158
+
159
+ def init_weights(self, m):
160
+ if isinstance(m, nn.Linear):
161
+ init.xavier_uniform_(m.weight)
162
+ if m.bias is not None:
163
+ init.constant_(m.bias, 0)
164
+
external/Grounded-Segment-Anything/.gitmodules ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+
2
+ [submodule "grounded-sam-osx"]
3
+ path = grounded-sam-osx
4
+ url = https://github.com/linjing7/grounded-sam-osx.git
5
+ [submodule "VISAM"]
6
+ path = VISAM
7
+ url = https://github.com/BingfengYan/VISAM
external/Grounded-Segment-Anything/CITATION.cff ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ cff-version: 1.2.0
2
+ message: "If you use this software, please cite it as below."
3
+ authors:
4
+ - name: "Grounded-SAM Contributors"
5
+ title: "Grounded-Segment-Anything"
6
+ date-released: 2023-04-06
7
+ url: "https://github.com/IDEA-Research/Grounded-Segment-Anything"
8
+ license: Apache-2.0
external/Grounded-Segment-Anything/Dockerfile ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM pytorch/pytorch:1.13.1-cuda11.6-cudnn8-devel
2
+
3
+ # Arguments to build Docker Image using CUDA
4
+ ARG USE_CUDA=0
5
+ ARG TORCH_ARCH=
6
+
7
+ ENV AM_I_DOCKER True
8
+ ENV BUILD_WITH_CUDA "${USE_CUDA}"
9
+ ENV TORCH_CUDA_ARCH_LIST "${TORCH_ARCH}"
10
+ ENV CUDA_HOME /usr/local/cuda-11.6/
11
+
12
+ RUN mkdir -p /home/appuser/Grounded-Segment-Anything
13
+ COPY . /home/appuser/Grounded-Segment-Anything/
14
+
15
+ RUN apt-get update && apt-get install --no-install-recommends wget ffmpeg=7:* \
16
+ libsm6=2:* libxext6=2:* git=1:* nano=2.* \
17
+ vim=2:* -y \
18
+ && apt-get clean && apt-get autoremove && rm -rf /var/lib/apt/lists/*
19
+
20
+ WORKDIR /home/appuser/Grounded-Segment-Anything
21
+ RUN python -m pip install --no-cache-dir -e segment_anything
22
+
23
+ # When using build isolation, PyTorch with newer CUDA is installed and can't compile GroundingDINO
24
+ RUN python -m pip install --no-cache-dir wheel
25
+ RUN python -m pip install --no-cache-dir --no-build-isolation -e GroundingDINO
26
+
27
+ WORKDIR /home/appuser
28
+ RUN pip install --no-cache-dir diffusers[torch]==0.15.1 opencv-python==4.7.0.72 \
29
+ pycocotools==2.0.6 matplotlib==3.5.3 \
30
+ onnxruntime==1.14.1 onnx==1.13.1 ipykernel==6.16.2 scipy gradio openai
external/Grounded-Segment-Anything/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2020 - present, IDEA, Inc
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
external/Grounded-Segment-Anything/Makefile ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Get version of CUDA and enable it for compilation if CUDA > 11.0
2
+ # This solves https://github.com/IDEA-Research/Grounded-Segment-Anything/issues/53
3
+ # and https://github.com/IDEA-Research/Grounded-Segment-Anything/issues/84
4
+ # when running in Docker
5
+ # Check if nvcc is installed
6
+ NVCC := $(shell which nvcc)
7
+ ifeq ($(NVCC),)
8
+ # NVCC not found
9
+ USE_CUDA := 0
10
+ NVCC_VERSION := "not installed"
11
+ else
12
+ NVCC_VERSION := $(shell nvcc --version | grep -oP 'release \K[0-9.]+')
13
+ USE_CUDA := $(shell echo "$(NVCC_VERSION) > 11" | bc -l)
14
+ endif
15
+
16
+ # Add the list of supported ARCHs
17
+ ifeq ($(USE_CUDA), 1)
18
+ TORCH_CUDA_ARCH_LIST := "3.5;5.0;6.0;6.1;7.0;7.5;8.0;8.6+PTX"
19
+ BUILD_MESSAGE := "I will try to build the image with CUDA support"
20
+ else
21
+ TORCH_CUDA_ARCH_LIST :=
22
+ BUILD_MESSAGE := "CUDA $(NVCC_VERSION) is not supported"
23
+ endif
24
+
25
+
26
+ build-image:
27
+ @echo $(BUILD_MESSAGE)
28
+ docker build --build-arg USE_CUDA=$(USE_CUDA) \
29
+ --build-arg TORCH_ARCH=$(TORCH_CUDA_ARCH_LIST) \
30
+ -t gsa:v0 .
31
+ run:
32
+ ifeq (,$(wildcard ./sam_vit_h_4b8939.pth))
33
+ wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth
34
+ endif
35
+ ifeq (,$(wildcard ./groundingdino_swint_ogc.pth))
36
+ wget https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth
37
+ endif
38
+ docker run --gpus all -it --rm --net=host --privileged \
39
+ -v /tmp/.X11-unix:/tmp/.X11-unix \
40
+ -v "${PWD}":/home/appuser/Grounded-Segment-Anything \
41
+ -e DISPLAY=$DISPLAY \
42
+ --name=gsa \
43
+ --ipc=host -it gsa:v0
external/Grounded-Segment-Anything/README.md ADDED
@@ -0,0 +1,808 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ![](./assets/Grounded-SAM_logo.png)
2
+
3
+ # Grounded-Segment-Anything
4
+ [![YouTube](https://badges.aleen42.com/src/youtube.svg)](https://youtu.be/oEQYStnF2l8) [![Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/roboflow-ai/notebooks/blob/main/notebooks/automated-dataset-annotation-and-evaluation-with-grounding-dino-and-sam.ipynb) [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://github.com/camenduru/grounded-segment-anything-colab) [![HuggingFace Space](https://img.shields.io/badge/🤗-HuggingFace%20Space-cyan.svg)](https://huggingface.co/spaces/IDEA-Research/Grounded-SAM) [![Replicate](https://replicate.com/cjwbw/grounded-recognize-anything/badge)](https://replicate.com/cjwbw/grounded-recognize-anything) [![ModelScope Official Demo](https://img.shields.io/badge/ModelScope-Official%20Demo-important)](https://modelscope.cn/studios/tuofeilunhifi/Grounded-Segment-Anything/summary) [![Huggingface Demo by Community](https://img.shields.io/badge/Huggingface-Demo%20by%20Community-red)](https://huggingface.co/spaces/yizhangliu/Grounded-Segment-Anything) [![Stable-Diffusion WebUI](https://img.shields.io/badge/Stable--Diffusion-WebUI%20by%20Community-critical)](https://github.com/continue-revolution/sd-webui-segment-anything) [![Jupyter Notebook Demo](https://img.shields.io/badge/Demo-Jupyter%20Notebook-informational)](./grounded_sam.ipynb) [![Static Badge](https://img.shields.io/badge/GroundingDINO-arXiv-blue)](https://arxiv.org/abs/2303.05499) [![Static Badge](https://img.shields.io/badge/Segment_Anything-arXiv-blue)](https://arxiv.org/abs/2304.02643) [![Static Badge](https://img.shields.io/badge/Grounded_SAM-arXiv-blue)](https://arxiv.org/abs/2401.14159)
5
+
6
+
7
+ We plan to create a very interesting demo by combining [Grounding DINO](https://github.com/IDEA-Research/GroundingDINO) and [Segment Anything](https://github.com/facebookresearch/segment-anything) which aims to detect and segment anything with text inputs! And we will continue to improve it and create more interesting demos based on this foundation. And we have already released an overall technical report about our project on arXiv, please check [Grounded SAM: Assembling Open-World Models for Diverse Visual Tasks](https://arxiv.org/abs/2401.14159) for more details.
8
+
9
+ - 🔥 **[Grounded SAM 2](https://github.com/IDEA-Research/Grounded-SAM-2)** is released now, which combines Grounding DINO with [SAM 2](https://github.com/facebookresearch/segment-anything-2) for any object tracking in open-world scenarios.
10
+ - 🔥 **[Grounding DINO 1.5](https://github.com/IDEA-Research/Grounding-DINO-1.5-API)** is released now, which is IDEA Research's **Most Capable** Open-World Object Detection Model!
11
+ - 🔥 **[Grounding DINO](https://arxiv.org/abs/2303.05499)** and **[Grounded SAM](https://arxiv.org/abs/2401.14159)** are now supported in Huggingface. For more convenient use, you can refer to [this documentation](https://huggingface.co/docs/transformers/model_doc/grounding-dino)
12
+
13
+ We are very willing to **help everyone share and promote new projects** based on Segment-Anything, Please check out here for more amazing demos and works in the community: [Highlight Extension Projects](#highlighted-projects). You can submit a new issue (with `project` tag) or a new pull request to add new project's links.
14
+
15
+ ![](./assets/grounded_sam_new_demo_image.png)
16
+
17
+ ![](./assets/ram_grounded_sam_new.png)
18
+
19
+ **🍄 Why Building this Project?**
20
+
21
+ The **core idea** behind this project is to **combine the strengths of different models in order to build a very powerful pipeline for solving complex problems**. And it's worth mentioning that this is a workflow for combining strong expert models, where **all parts can be used separately or in combination, and can be replaced with any similar but different models (like replacing Grounding DINO with GLIP or other detectors / replacing Stable-Diffusion with ControlNet or GLIGEN/ Combining with ChatGPT)**.
22
+
23
+ **🍇 Updates**
24
+ - **`2024/01/26`** We have released a comprehensive technical report about our project on arXiv, please check [Grounded SAM: Assembling Open-World Models for Diverse Visual Tasks](https://arxiv.org/abs/2401.14159) for more details. And we are profoundly grateful for the contributions of all the contributors in this project.
25
+ - **`2023/12/17`** Support [Grounded-RepViT-SAM](https://github.com/IDEA-Research/Grounded-Segment-Anything/tree/main/EfficientSAM#run-grounded-repvit-sam-demo) demo, thanks a lot for their great work!
26
+ - **`2023/12/16`** Support [Grounded-Edge-SAM](https://github.com/IDEA-Research/Grounded-Segment-Anything/tree/main/EfficientSAM#run-grounded-edge-sam-demo) demo, thanks a lot for their great work!
27
+ - **`2023/12/10`** Support [Grounded-Efficient-SAM](https://github.com/IDEA-Research/Grounded-Segment-Anything/tree/main/EfficientSAM#run-grounded-efficient-sam-demo) demo, thanks a lot for their great work!
28
+ - **`2023/11/24`** Release [RAM++](https://arxiv.org/abs/2310.15200), which is the next generation of RAM. RAM++ can recognize any category with high accuracy, including both predefined common categories and diverse open-set categories.
29
+ - **`2023/11/23`** Release our newly proposed visual prompt counting model [T-Rex](https://github.com/IDEA-Research/T-Rex). The introduction [Video](https://www.youtube.com/watch?v=engIEhZogAQ) and [Demo](https://deepdataspace.com/playground/ivp) is available in [DDS](https://github.com/IDEA-Research/deepdataspace) now.
30
+ - **`2023/07/25`** Support [Light-HQ-SAM](https://github.com/SysCV/sam-hq) in [EfficientSAM](./EfficientSAM/), credits to [Mingqiao Ye](https://github.com/ymq2017) and [Lei Ke](https://github.com/lkeab), thanks a lot for their great work!
31
+ - **`2023/07/14`** Combining **Grounding-DINO-B** with [SAM-HQ](https://github.com/SysCV/sam-hq) achieves **49.6 mean AP** in [Segmentation in the Wild](https://eval.ai/web/challenges/challenge-page/1931/overview) competition zero-shot track, surpassing Grounded-SAM by **3.6 mean AP**, thanks for their great work!
32
+ - **`2023/06/28`** Combining Grounding-DINO with Efficient SAM variants including [FastSAM](https://github.com/CASIA-IVA-Lab/FastSAM) and [MobileSAM](https://github.com/ChaoningZhang/MobileSAM) in [EfficientSAM](./EfficientSAM/) for faster annotating, thanks a lot for their great work!
33
+ - **`2023/06/20`** By combining **Grounding-DINO-L** with **SAM-ViT-H**, Grounded-SAM achieves 46.0 mean AP in [Segmentation in the Wild](https://eval.ai/web/challenges/challenge-page/1931/overview) competition zero-shot track on [CVPR 2023 workshop](https://computer-vision-in-the-wild.github.io/cvpr-2023/), surpassing [UNINEXT (CVPR 2023)](https://github.com/MasterBin-IIAU/UNINEXT) by about **4 mean AP**.
34
+ - **`2023/06/16`** Release [RAM-Grounded-SAM Replicate Online Demo](https://replicate.com/cjwbw/ram-grounded-sam). Thanks a lot to [Chenxi](https://chenxwh.github.io/) for providing this nice demo 🌹.
35
+ - **`2023/06/14`** Support [RAM-Grounded-SAM & SAM-HQ](./automatic_label_ram_demo.py) and update [Simple Automatic Label Demo](./automatic_label_ram_demo.py) to support [RAM](https://github.com/OPPOMKLab/recognize-anything), setting up a strong automatic annotation pipeline.
36
+ - **`2023/06/13`** Checkout the [Autodistill: Train YOLOv8 with ZERO Annotations](https://youtu.be/gKTYMfwPo4M) tutorial to learn how to use Grounded-SAM + [Autodistill](https://github.com/autodistill/autodistill) for automated data labeling and real-time model training.
37
+ - **`2023/06/13`** Support [SAM-HQ](https://github.com/SysCV/sam-hq) in [Grounded-SAM Demo](#running_man-grounded-sam-detect-and-segment-everything-with-text-prompt) for higher quality prediction.
38
+ - **`2023/06/12`** Support [RAM-Grounded-SAM](#label-grounded-sam-with-ram-or-tag2text-for-automatic-labeling) for strong automatic labeling pipeline! Thanks for [Recognize-Anything](https://github.com/OPPOMKLab/recognize-anything).
39
+ - **`2023/06/01`** Our Grounded-SAM has been accepted to present a **demo** at [ICCV 2023](https://iccv2023.thecvf.com/)! See you in Paris!
40
+ - **`2023/05/23`**: Support `Image-Referring-Segment`, `Audio-Referring-Segment` and `Text-Referring-Segment` in [ImageBind-SAM](./playground/ImageBind_SAM/).
41
+ - **`2023/05/03`**: Checkout the [Automated Dataset Annotation and Evaluation with GroundingDINO and SAM](https://colab.research.google.com/github/roboflow-ai/notebooks/blob/main/notebooks/automated-dataset-annotation-and-evaluation-with-grounding-dino-and-sam.ipynb) which is an amazing tutorial on automatic labeling! Thanks a lot for [Piotr Skalski](https://github.com/SkalskiP) and [Roboflow](https://github.com/roboflow/notebooks)!
42
+
43
+
44
+ ## Table of Contents
45
+ - [Grounded-Segment-Anything](#grounded-segment-anything)
46
+ - [Preliminary Works](#preliminary-works)
47
+ - [Highlighted Projects](#highlighted-projects)
48
+ - [Installation](#installation)
49
+ - [Install with Docker](#install-with-docker)
50
+ - [Install locally](#install-without-docker)
51
+ - [Grounded-SAM Playground](#grounded-sam-playground)
52
+ - [Step-by-Step Notebook Demo](#open_book-step-by-step-notebook-demo)
53
+ - [GroundingDINO: Detect Everything with Text Prompt](#running_man-groundingdino-detect-everything-with-text-prompt)
54
+ - [Grounded-SAM: Detect and Segment Everything with Text Prompt](#running_man-grounded-sam-detect-and-segment-everything-with-text-prompt)
55
+ - [Grounded-SAM with Inpainting: Detect, Segment and Generate Everything with Text Prompt](#skier-grounded-sam-with-inpainting-detect-segment-and-generate-everything-with-text-prompt)
56
+ - [Grounded-SAM and Inpaint Gradio APP](#golfing-grounded-sam-and-inpaint-gradio-app)
57
+ - [Grounded-SAM with RAM or Tag2Text for Automatic Labeling](#label-grounded-sam-with-ram-or-tag2text-for-automatic-labeling)
58
+ - [Grounded-SAM with BLIP & ChatGPT for Automatic Labeling](#robot-grounded-sam-with-blip-for-automatic-labeling)
59
+ - [Grounded-SAM with Whisper: Detect and Segment Anything with Audio](#open_mouth-grounded-sam-with-whisper-detect-and-segment-anything-with-audio)
60
+ - [Grounded-SAM ChatBot with Visual ChatGPT](#speech_balloon-grounded-sam-chatbot-demo)
61
+ - [Grounded-SAM with OSX for 3D Whole-Body Mesh Recovery](#man_dancing-run-grounded-segment-anything--osx-demo)
62
+ - [Grounded-SAM with VISAM for Tracking and Segment Anything](#man_dancing-run-grounded-segment-anything--visam-demo)
63
+ - [Interactive Fashion-Edit Playground: Click for Segmentation And Editing](#dancers-interactive-editing)
64
+ - [Interactive Human-face Editing Playground: Click And Editing Human Face](#dancers-interactive-editing)
65
+ - [3D Box Via Segment Anything](#camera-3d-box-via-segment-anything)
66
+ - [Playground: More Interesting and Imaginative Demos with Grounded-SAM](./playground/)
67
+ - [DeepFloyd: Image Generation with Text Prompt](./playground/DeepFloyd/)
68
+ - [PaintByExample: Exemplar-based Image Editing with Diffusion Models](./playground/PaintByExample/)
69
+ - [LaMa: Resolution-robust Large Mask Inpainting with Fourier Convolutions](./playground/LaMa/)
70
+ - [RePaint: Inpainting using Denoising Diffusion Probabilistic Models](./playground/RePaint/)
71
+ - [ImageBind with SAM: Segment with Different Modalities](./playground/ImageBind_SAM/)
72
+ - [Efficient SAM Series for Faster Annotation](./EfficientSAM/)
73
+ - [Grounded-FastSAM Demo](https://github.com/IDEA-Research/Grounded-Segment-Anything/tree/main/EfficientSAM#run-grounded-fastsam-demo)
74
+ - [Grounded-MobileSAM Demo](https://github.com/IDEA-Research/Grounded-Segment-Anything/tree/main/EfficientSAM#run-grounded-mobilesam-demo)
75
+ - [Grounded-Light-HQSAM Demo](https://github.com/IDEA-Research/Grounded-Segment-Anything/tree/main/EfficientSAM#run-grounded-light-hqsam-demo)
76
+ - [Grounded-Efficient-SAM Demo](https://github.com/IDEA-Research/Grounded-Segment-Anything/tree/main/EfficientSAM#run-grounded-efficient-sam-demo)
77
+ - [Grounded-Edge-SAM Demo](https://github.com/IDEA-Research/Grounded-Segment-Anything/tree/main/EfficientSAM#run-grounded-edge-sam-demo)
78
+ - [Grounded-RepViT-SAM Demo](https://github.com/IDEA-Research/Grounded-Segment-Anything/tree/main/EfficientSAM#run-grounded-repvit-sam-demo)
79
+ - [Citation](#citation)
80
+
81
+ ## Preliminary Works
82
+
83
+ Here we provide some background knowledge that you may need to know before trying the demos.
84
+
85
+ <div align="center">
86
+
87
+ | Title | Intro | Description | Links |
88
+ |:----:|:----:|:----:|:----:|
89
+ | [Segment-Anything](https://arxiv.org/abs/2304.02643) | ![](https://github.com/facebookresearch/segment-anything/blob/main/assets/model_diagram.png?raw=true) | A strong foundation model aims to segment everything in an image, which needs prompts (as boxes/points/text) to generate masks | [[Github](https://github.com/facebookresearch/segment-anything)] <br> [[Page](https://segment-anything.com/)] <br> [[Demo](https://segment-anything.com/demo)] |
90
+ | [Grounding DINO](https://arxiv.org/abs/2303.05499) | ![](https://github.com/IDEA-Research/GroundingDINO/blob/main/.asset/hero_figure.png?raw=True) | A strong zero-shot detector which is capable of to generate high quality boxes and labels with free-form text. | [[Github](https://github.com/IDEA-Research/GroundingDINO)] <br> [[Demo](https://huggingface.co/spaces/ShilongLiu/Grounding_DINO_demo)] |
91
+ | [OSX](http://arxiv.org/abs/2303.16160) | ![](https://github.com/IDEA-Research/OSX/blob/main/assets/demo_video.gif?raw=True) | A strong and efficient one-stage motion capture method to generate high quality 3D human mesh from monucular image. OSX also releases a large-scale upper-body dataset UBody for a more accurate reconstrution in the upper-body scene. | [[Github](https://github.com/IDEA-Research/OSX)] <br> [[Page](https://osx-ubody.github.io/)] <br> [[Video](https://osx-ubody.github.io/)] <br> [[Data](https://docs.google.com/forms/d/e/1FAIpQLSehgBP7wdn_XznGAM2AiJPiPLTqXXHw5uX9l7qeQ1Dh9HoO_A/viewform)] |
92
+ | [Stable-Diffusion](https://arxiv.org/abs/2112.10752) | ![](https://github.com/CompVis/stable-diffusion/blob/main/assets/stable-samples/txt2img/merged-0006.png?raw=True) | A super powerful open-source latent text-to-image diffusion model | [[Github](https://github.com/CompVis/stable-diffusion)] <br> [[Page](https://ommer-lab.com/research/latent-diffusion-models/)] |
93
+ | [RAM++](https://arxiv.org/abs/2310.15200) | ![](https://github.com/xinyu1205/recognize-anything/blob/main/images/ram_plus_compare.jpg) | RAM++ is the next generation of RAM, which can recognize any category with high accuracy. | [[Github](https://github.com/OPPOMKLab/recognize-anything)] |
94
+ | [RAM](https://recognize-anything.github.io/) | ![](https://github.com/xinyu1205/Tag2Text/raw/main/images/localization_and_recognition.jpg) | RAM is an image tagging model, which can recognize any common category with high accuracy. | [[Github](https://github.com/OPPOMKLab/recognize-anything)] <br> [[Demo](https://huggingface.co/spaces/xinyu1205/Recognize_Anything-Tag2Text)] |
95
+ | [BLIP](https://arxiv.org/abs/2201.12086) | ![](https://github.com/salesforce/LAVIS/raw/main/docs/_static/logo_final.png) | A wonderful language-vision model for image understanding. | [[GitHub](https://github.com/salesforce/LAVIS)] |
96
+ | [Visual ChatGPT](https://arxiv.org/abs/2303.04671) | ![](https://github.com/microsoft/TaskMatrix/raw/main/assets/figure.jpg) | A wonderful tool that connects ChatGPT and a series of Visual Foundation Models to enable sending and receiving images during chatting. | [[Github](https://github.com/microsoft/TaskMatrix)] <br> [[Demo](https://huggingface.co/spaces/microsoft/visual_chatgpt)] |
97
+ | [Tag2Text](https://tag2text.github.io/) | ![](https://github.com/xinyu1205/Tag2Text/raw/main/images/tag2text_framework.png) | An efficient and controllable vision-language model which can simultaneously output superior image captioning and image tagging. | [[Github](https://github.com/OPPOMKLab/recognize-anything)] <br> [[Demo](https://huggingface.co/spaces/xinyu1205/Tag2Text)] |
98
+ | [VoxelNeXt](https://arxiv.org/abs/2303.11301) | ![](https://github.com/dvlab-research/VoxelNeXt/raw/master/docs/sequence-v2.gif) | A clean, simple, and fully-sparse 3D object detector, which predicts objects directly upon sparse voxel features. | [[Github](https://github.com/dvlab-research/VoxelNeXt)]
99
+
100
+ </div>
101
+
102
+ ## Highlighted Projects
103
+
104
+ Here we provide some impressive works you may find interesting:
105
+
106
+ <div align="center">
107
+
108
+ | Title | Description | Links |
109
+ |:---:|:---:|:---:|
110
+ | [Semantic-SAM](https://github.com/UX-Decoder/Semantic-SAM) | A universal image segmentation model to enable segment and recognize anything at any desired granularity | [[Github](https://github.com/UX-Decoder/Semantic-SAM)] <br> [[Demo](https://github.com/UX-Decoder/Semantic-SAM)] |
111
+ | [SEEM: Segment Everything Everywhere All at Once](https://arxiv.org/pdf/2304.06718.pdf) | A powerful promptable segmentation model supports segmenting with various types of prompts (text, point, scribble, referring image, etc.) and any combination of prompts. | [[Github](https://github.com/UX-Decoder/Segment-Everything-Everywhere-All-At-Once)] <br> [[Demo](https://huggingface.co/spaces/xdecoder/SEEM)] |
112
+ | [OpenSeeD](https://arxiv.org/pdf/2303.08131.pdf) | A simple framework for open-vocabulary segmentation and detection which supports interactive segmentation with box input to generate mask | [[Github](https://github.com/IDEA-Research/OpenSeeD)] |
113
+ | [LLaVA](https://arxiv.org/abs/2304.08485) | Visual instruction tuning with GPT-4 | [[Github](https://github.com/haotian-liu/LLaVA)] <br> [[Page](https://llava-vl.github.io/)] <br> [[Demo](https://llava.hliu.cc/)] <br> [[Data](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K)] <br> [[Model](https://huggingface.co/liuhaotian/LLaVA-13b-delta-v0)] |
114
+ | [GenSAM](https://arxiv.org/abs/2312.07374) | Relaxing the instance-specific manual prompt requirement in SAM through training-free test-time adaptation | [[Github](https://github.com/jyLin8100/GenSAM)] <br> [[Page](https://lwpyh.github.io/GenSAM/)] |
115
+
116
+ </div>
117
+
118
+ We also list some awesome segment-anything extension projects here you may find interesting:
119
+ - [Computer Vision in the Wild (CVinW) Readings](https://github.com/Computer-Vision-in-the-Wild/CVinW_Readings) for those who are interested in open-set tasks in computer vision.
120
+ - [Zero-Shot Anomaly Detection](https://github.com/caoyunkang/GroundedSAM-zero-shot-anomaly-detection) by Yunkang Cao
121
+ - [EditAnything: ControlNet + StableDiffusion based on the SAM segmentation mask](https://github.com/sail-sg/EditAnything) by Shanghua Gao and Pan Zhou
122
+ - [IEA: Image Editing Anything](https://github.com/feizc/IEA) by Zhengcong Fei
123
+ - [SAM-MMRorate: Combining Rotated Object Detector and SAM](https://github.com/Li-Qingyun/sam-mmrotate) by Qingyun Li and Xue Yang
124
+ - [Awesome-Anything](https://github.com/VainF/Awesome-Anything) by Gongfan Fang
125
+ - [Prompt-Segment-Anything](https://github.com/RockeyCoss/Prompt-Segment-Anything) by Rockey
126
+ - [WebUI for Segment-Anything and Grounded-SAM](https://github.com/continue-revolution/sd-webui-segment-anything) by Chengsong Zhang
127
+ - [Inpainting Anything: Inpaint Anything with SAM + Inpainting models](https://github.com/geekyutao/Inpaint-Anything) by Tao Yu
128
+ - [Grounded Segment Anything From Objects to Parts: Combining Segment-Anything with VLPart & GLIP & Visual ChatGPT](https://github.com/Cheems-Seminar/segment-anything-and-name-it) by Peize Sun and Shoufa Chen
129
+ - [Narapi-SAM: Integration of Segment Anything into Narapi (A nice viewer for SAM)](https://github.com/MIC-DKFZ/napari-sam) by MIC-DKFZ
130
+ - [Grounded Segment Anything Colab](https://github.com/camenduru/grounded-segment-anything-colab) by camenduru
131
+ - [Optical Character Recognition with Segment Anything](https://github.com/yeungchenwa/OCR-SAM) by Zhenhua Yang
132
+ - [Transform Image into Unique Paragraph with ChatGPT, BLIP2, OFA, GRIT, Segment Anything, ControlNet](https://github.com/showlab/Image2Paragraph) by showlab
133
+ - [Lang-Segment-Anything: Another awesome demo for combining GroundingDINO with Segment-Anything](https://github.com/luca-medeiros/lang-segment-anything) by Luca Medeiros
134
+ - [🥳 🚀 **Playground: Integrate SAM and OpenMMLab!**](https://github.com/open-mmlab/playground)
135
+ - [3D-object via Segment Anything](https://github.com/dvlab-research/3D-Box-Segment-Anything) by Yukang Chen
136
+ - [Image2Paragraph: Transform Image Into Unique Paragraph](https://github.com/showlab/Image2Paragraph) by Show Lab
137
+ - [Zero-shot Scene Graph Generate with Grounded-SAM](https://github.com/showlab/Image2Paragraph) by JackWhite-rwx
138
+ - [CLIP Surgery for Better Explainability with Enhancement in Open-Vocabulary Tasks](https://github.com/xmed-lab/CLIP_Surgery) by Eli-YiLi
139
+ - [Panoptic-Segment-Anything: Zero-shot panoptic segmentation using SAM](https://github.com/segments-ai/panoptic-segment-anything) by segments-ai
140
+ - [Caption-Anything: Generates Descriptive Captions for Any Object within an Image](https://github.com/ttengwang/Caption-Anything) by Teng Wang
141
+ - [Segment-Anything-3D: Transferring Segmentation Information of 2D Images to 3D Space](https://github.com/Pointcept/SegmentAnything3D) by Yunhan Yang
142
+ - [Expediting SAM without Fine-tuning](https://github.com/Expedit-LargeScale-Vision-Transformer/Expedit-SAM) by Weicong Liang and Yuhui Yuan
143
+ - [Semantic Segment Anything: Providing Rich Semantic Category Annotations for SAM](https://github.com/fudan-zvg/Semantic-Segment-Anything) by Jiaqi Chen and Zeyu Yang and Li Zhang
144
+ - [Enhance Everything: Combining SAM with Image Restoration and Enhancement Tasks](https://github.com/lixinustc/Enhance-Anything) by Xin Li
145
+ - [DragGAN](https://github.com/Zeqiang-Lai/DragGAN) by Shanghai AI Lab.
146
+ - [Tabletop HandyBot: Robotic arm assistant that performs tabletop tasks using Grounded-SAM](https://github.com/ycheng517/tabletop-handybot) by Yifei Cheng
147
+
148
+ ## Installation
149
+ The code requires `python>=3.8`, as well as `pytorch>=1.7` and `torchvision>=0.8`. Please follow the instructions [here](https://pytorch.org/get-started/locally/) to install both PyTorch and TorchVision dependencies. Installing both PyTorch and TorchVision with CUDA support is strongly recommended.
150
+
151
+ ### Install with Docker
152
+
153
+ Open one terminal:
154
+
155
+ ```
156
+ make build-image
157
+ ```
158
+
159
+ ```
160
+ make run
161
+ ```
162
+
163
+ That's it.
164
+
165
+ If you would like to allow visualization across docker container, open another terminal and type:
166
+
167
+ ```
168
+ xhost +
169
+ ```
170
+
171
+
172
+ ### Install without Docker
173
+ You should set the environment variable manually as follows if you want to build a local GPU environment for Grounded-SAM:
174
+ ```bash
175
+ export AM_I_DOCKER=False
176
+ export BUILD_WITH_CUDA=True
177
+ export CUDA_HOME=/path/to/cuda-11.3/
178
+ ```
179
+
180
+ Install Segment Anything:
181
+
182
+ ```bash
183
+ python -m pip install -e segment_anything
184
+ ```
185
+
186
+ Install Grounding DINO:
187
+
188
+ ```bash
189
+ pip install --no-build-isolation -e GroundingDINO
190
+ ```
191
+
192
+
193
+ Install diffusers:
194
+
195
+ ```bash
196
+ pip install --upgrade diffusers[torch]
197
+ ```
198
+
199
+ Install osx:
200
+
201
+ ```bash
202
+ git submodule update --init --recursive
203
+ cd grounded-sam-osx && bash install.sh
204
+ ```
205
+
206
+ Install RAM & Tag2Text:
207
+
208
+ ```bash
209
+ git clone https://github.com/xinyu1205/recognize-anything.git
210
+ pip install -r ./recognize-anything/requirements.txt
211
+ pip install -e ./recognize-anything/
212
+ ```
213
+
214
+ The following optional dependencies are necessary for mask post-processing, saving masks in COCO format, the example notebooks, and exporting the model in ONNX format. `jupyter` is also required to run the example notebooks.
215
+
216
+ ```
217
+ pip install opencv-python pycocotools matplotlib onnxruntime onnx ipykernel
218
+ ```
219
+
220
+ More details can be found in [install segment anything](https://github.com/facebookresearch/segment-anything#installation) and [install GroundingDINO](https://github.com/IDEA-Research/GroundingDINO#install) and [install OSX](https://github.com/IDEA-Research/OSX)
221
+
222
+
223
+ ## Grounded-SAM Playground
224
+ Let's start exploring our Grounding-SAM Playground and we will release more interesting demos in the future, stay tuned!
225
+
226
+ ## :open_book: Step-by-Step Notebook Demo
227
+ Here we list some notebook demo provided in this project:
228
+ - [grounded_sam.ipynb](grounded_sam.ipynb)
229
+ - [grounded_sam_colab_demo.ipynb](grounded_sam_colab_demo.ipynb)
230
+ - [grounded_sam_3d_box.ipynb](grounded_sam_3d_box)
231
+
232
+
233
+ ### :running_man: GroundingDINO: Detect Everything with Text Prompt
234
+
235
+ :grapes: [[arXiv Paper](https://arxiv.org/abs/2303.05499)] &nbsp; :rose:[[Try the Colab Demo](https://colab.research.google.com/github/roboflow-ai/notebooks/blob/main/notebooks/zero-shot-object-detection-with-grounding-dino.ipynb)] &nbsp; :sunflower: [[Try Huggingface Demo](https://huggingface.co/spaces/ShilongLiu/Grounding_DINO_demo)] &nbsp; :mushroom: [[Automated Dataset Annotation and Evaluation](https://youtu.be/C4NqaRBz_Kw)]
236
+
237
+ Here's the step-by-step tutorial on running `GroundingDINO` demo:
238
+
239
+ **Step 1: Download the pretrained weights**
240
+
241
+ ```bash
242
+ cd Grounded-Segment-Anything
243
+
244
+ # download the pretrained groundingdino-swin-tiny model
245
+ wget https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth
246
+ ```
247
+
248
+ **Step 2: Running the demo**
249
+
250
+ ```bash
251
+ python grounding_dino_demo.py
252
+ ```
253
+
254
+ <details>
255
+ <summary> <b> Running with Python (same as demo but you can run it anywhere after installing GroundingDINO) </b> </summary>
256
+
257
+ ```python
258
+ from groundingdino.util.inference import load_model, load_image, predict, annotate
259
+ import cv2
260
+
261
+ model = load_model("GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py", "./groundingdino_swint_ogc.pth")
262
+ IMAGE_PATH = "assets/demo1.jpg"
263
+ TEXT_PROMPT = "bear."
264
+ BOX_THRESHOLD = 0.35
265
+ TEXT_THRESHOLD = 0.25
266
+
267
+ image_source, image = load_image(IMAGE_PATH)
268
+
269
+ boxes, logits, phrases = predict(
270
+ model=model,
271
+ image=image,
272
+ caption=TEXT_PROMPT,
273
+ box_threshold=BOX_THRESHOLD,
274
+ text_threshold=TEXT_THRESHOLD
275
+ )
276
+
277
+ annotated_frame = annotate(image_source=image_source, boxes=boxes, logits=logits, phrases=phrases)
278
+ cv2.imwrite("annotated_image.jpg", annotated_frame)
279
+ ```
280
+
281
+ </details>
282
+ <br>
283
+
284
+ **Tips**
285
+ - If you want to detect multiple objects in one sentence with [Grounding DINO](https://github.com/IDEA-Research/GroundingDINO), we suggest separating each name with `.` . An example: `cat . dog . chair .`
286
+
287
+ **Step 3: Check the annotated image**
288
+
289
+ The annotated image will be saved as `./annotated_image.jpg`.
290
+
291
+ <div align="center">
292
+
293
+ | Text Prompt | Demo Image | Annotated Image |
294
+ |:----:|:----:|:----:|
295
+ | `Bear.` | ![](./assets/demo1.jpg) | ![](./assets/annotated_image.jpg) |
296
+ | `Horse. Clouds. Grasses. Sky. Hill` | ![](./assets/demo7.jpg) | ![](https://github.com/IDEA-Research/detrex-storage/blob/main/assets/grounded_sam/grounding_dino/groundingdino_demo7.jpg?raw=true)
297
+
298
+ </div>
299
+
300
+
301
+ ### :running_man: Grounded-SAM: Detect and Segment Everything with Text Prompt
302
+
303
+ Here's the step-by-step tutorial on running `Grounded-SAM` demo:
304
+
305
+ **Step 1: Download the pretrained weights**
306
+
307
+ ```bash
308
+ cd Grounded-Segment-Anything
309
+
310
+ wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth
311
+ wget https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth
312
+ ```
313
+
314
+ We provide two versions of Grounded-SAM demo here:
315
+ - [grounded_sam_demo.py](./grounded_sam_demo.py): our original implementation for Grounded-SAM.
316
+ - [grounded_sam_simple_demo.py](./grounded_sam_simple_demo.py) our updated more elegant version for Grounded-SAM.
317
+
318
+ **Step 2: Running original grounded-sam demo**
319
+ ```bash
320
+ # depends on your device
321
+ export CUDA_VISIBLE_DEVICES=0
322
+ ```
323
+
324
+ ```python
325
+
326
+ python grounded_sam_demo.py \
327
+ --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
328
+ --grounded_checkpoint groundingdino_swint_ogc.pth \
329
+ --sam_checkpoint sam_vit_h_4b8939.pth \
330
+ --input_image assets/demo1.jpg \
331
+ --output_dir "outputs" \
332
+ --box_threshold 0.3 \
333
+ --text_threshold 0.25 \
334
+ --text_prompt "bear" \
335
+ --device "cuda"
336
+ ```
337
+
338
+ The annotated results will be saved in `./outputs` as follows
339
+
340
+ <div align="center">
341
+
342
+ | Input Image | Annotated Image | Generated Mask |
343
+ |:----:|:----:|:----:|
344
+ | ![](./assets/demo1.jpg) | ![](https://github.com/IDEA-Research/detrex-storage/blob/main/assets/grounded_sam/grounded_sam/original_grounded_sam_demo1.jpg?raw=true) | ![](https://github.com/IDEA-Research/detrex-storage/blob/main/assets/grounded_sam/grounded_sam/mask.jpg?raw=true) |
345
+
346
+ </div>
347
+
348
+ **Step 3: Running grounded-sam demo with sam-hq**
349
+ - Download the demo image
350
+ ```bash
351
+ wget https://github.com/IDEA-Research/detrex-storage/releases/download/grounded-sam-storage/sam_hq_demo_image.png
352
+ ```
353
+
354
+ - Download SAM-HQ checkpoint [here](https://github.com/SysCV/sam-hq#model-checkpoints)
355
+
356
+ - Running grounded-sam-hq demo as follows:
357
+ ```python
358
+ export CUDA_VISIBLE_DEVICES=0
359
+ python grounded_sam_demo.py \
360
+ --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
361
+ --grounded_checkpoint groundingdino_swint_ogc.pth \
362
+ --sam_hq_checkpoint ./sam_hq_vit_h.pth \ # path to sam-hq checkpoint
363
+ --use_sam_hq \ # set to use sam-hq model
364
+ --input_image sam_hq_demo_image.png \
365
+ --output_dir "outputs" \
366
+ --box_threshold 0.3 \
367
+ --text_threshold 0.25 \
368
+ --text_prompt "chair." \
369
+ --device "cuda"
370
+ ```
371
+
372
+ The annotated results will be saved in `./outputs` as follows
373
+
374
+ <div align="center">
375
+
376
+ | Input Image | SAM Output | SAM-HQ Output |
377
+ |:----:|:----:|:----:|
378
+ | ![](https://github.com/IDEA-Research/detrex-storage/blob/main/assets/grounded_sam/sam_hq/sam_hq_demo.png?raw=true) | ![](https://github.com/IDEA-Research/detrex-storage/blob/main/assets/grounded_sam/sam_hq/sam_output.jpg?raw=true) | ![](https://github.com/IDEA-Research/detrex-storage/blob/main/assets/grounded_sam/sam_hq/sam_hq_output.jpg?raw=true) |
379
+
380
+ </div>
381
+
382
+ **Step 4: Running the updated grounded-sam demo (optional)**
383
+
384
+ Note that this demo is almost same as the original demo, but **with more elegant code**.
385
+
386
+ ```python
387
+ python grounded_sam_simple_demo.py
388
+ ```
389
+
390
+ The annotated results will be saved as `./groundingdino_annotated_image.jpg` and `./grounded_sam_annotated_image.jpg`
391
+
392
+ <div align="center">
393
+
394
+ | Text Prompt | Input Image | GroundingDINO Annotated Image | Grounded-SAM Annotated Image |
395
+ |:----:|:----:|:----:|:----:|
396
+ | `The running dog` | ![](./assets/demo2.jpg) | ![](https://github.com/IDEA-Research/detrex-storage/blob/main/assets/grounded_sam/grounded_sam/groundingdino_annotated_image_demo2.jpg?raw=true) | ![](https://github.com/IDEA-Research/detrex-storage/blob/main/assets/grounded_sam/grounded_sam/grounded_sam_annotated_image_demo2.jpg?raw=true) |
397
+ | `Horse. Clouds. Grasses. Sky. Hill` | ![](./assets/demo7.jpg) | ![](assets/groundingdino_annotated_image.jpg) | ![](assets/grounded_sam_annotated_image.jpg) |
398
+
399
+ </div>
400
+
401
+ **Step 5: Running the Sam model with multi-gpu**
402
+ ```bash
403
+ export CUDA_VISIBLE_DEVICES=0,1
404
+ ```
405
+ ```python
406
+
407
+ python grounded_sam_multi_gpu_demo.py \
408
+ --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
409
+ --grounded_checkpoint groundingdino_swint_ogc.pth \
410
+ --sam_checkpoint sam_vit_h_4b8939.pth \
411
+ --input_path assets/car \
412
+ --output_dir "outputs" \
413
+ --box_threshold 0.3 \
414
+ --text_threshold 0.25 \
415
+ --text_prompt "car" \
416
+ --device "cuda"
417
+ ```
418
+ You will see that the model is loaded once per GPU ![](assets/multi-gpu.png)
419
+
420
+ ### :skier: Grounded-SAM with Inpainting: Detect, Segment and Generate Everything with Text Prompt
421
+
422
+ **Step 1: Download the pretrained weights**
423
+
424
+ ```bash
425
+ cd Grounded-Segment-Anything
426
+
427
+ wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth
428
+ wget https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth
429
+ ```
430
+
431
+ **Step 2: Running grounded-sam inpainting demo**
432
+
433
+ ```bash
434
+ CUDA_VISIBLE_DEVICES=0
435
+ python grounded_sam_inpainting_demo.py \
436
+ --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
437
+ --grounded_checkpoint groundingdino_swint_ogc.pth \
438
+ --sam_checkpoint sam_vit_h_4b8939.pth \
439
+ --input_image assets/inpaint_demo.jpg \
440
+ --output_dir "outputs" \
441
+ --box_threshold 0.3 \
442
+ --text_threshold 0.25 \
443
+ --det_prompt "bench" \
444
+ --inpaint_prompt "A sofa, high quality, detailed" \
445
+ --device "cuda"
446
+ ```
447
+
448
+ The annotated and inpaint image will be saved in `./outputs`
449
+
450
+ **Step 3: Check the results**
451
+
452
+
453
+ <div align="center">
454
+
455
+ | Input Image | Det Prompt | Annotated Image | Inpaint Prompt | Inpaint Image |
456
+ |:---:|:---:|:---:|:---:|:---:|
457
+ |![](./assets/inpaint_demo.jpg) | `Bench` | ![](https://github.com/IDEA-Research/detrex-storage/blob/main/assets/grounded_sam/grounded_sam_inpaint/grounded_sam_output.jpg?raw=true) | `A sofa, high quality, detailed` | ![](https://github.com/IDEA-Research/detrex-storage/blob/main/assets/grounded_sam/grounded_sam_inpaint/grounded_sam_inpainting_output.jpg?raw=true) |
458
+
459
+ </div>
460
+
461
+ ### :golfing: Grounded-SAM and Inpaint Gradio APP
462
+
463
+ We support 6 tasks in the local Gradio APP:
464
+
465
+ 1. **scribble**: Segmentation is achieved through Segment Anything and mouse click interaction (you need to click on the object with the mouse, no need to specify the prompt).
466
+ 2. **automask**: Segment the entire image at once through Segment Anything (no need to specify a prompt).
467
+ 3. **det**: Realize detection through Grounding DINO and text interaction (text prompt needs to be specified).
468
+ 4. **seg**: Realize text interaction by combining Grounding DINO and Segment Anything to realize detection + segmentation (need to specify text prompt).
469
+ 5. **inpainting**: By combining Grounding DINO + Segment Anything + Stable Diffusion to achieve text exchange and replace the target object (need to specify text prompt and inpaint prompt) .
470
+ 6. **automatic**: By combining BLIP + Grounding DINO + Segment Anything to achieve non-interactive detection + segmentation (no need to specify prompt).
471
+
472
+ ```bash
473
+ python gradio_app.py
474
+ ```
475
+
476
+ - The gradio_app visualization as follows:
477
+
478
+ ![](./assets/gradio_demo.png)
479
+
480
+
481
+ ### :label: Grounded-SAM with RAM or Tag2Text for Automatic Labeling
482
+ [**The Recognize Anything Models**](https://github.com/OPPOMKLab/recognize-anything) are a series of open-source and strong fundamental image recognition models, including [RAM++](https://arxiv.org/abs/2310.15200), [RAM](https://arxiv.org/abs/2306.03514) and [Tag2text](https://arxiv.org/abs/2303.05657).
483
+
484
+
485
+ It is seamlessly linked to generate pseudo labels automatically as follows:
486
+ 1. Use RAM/Tag2Text to generate tags.
487
+ 2. Use Grounded-Segment-Anything to generate the boxes and masks.
488
+
489
+
490
+ **Step 1: Init submodule and download the pretrained checkpoint**
491
+
492
+ - Init submodule:
493
+
494
+ ```bash
495
+ cd Grounded-Segment-Anything
496
+ git submodule init
497
+ git submodule update
498
+ ```
499
+
500
+ - Download pretrained weights for `GroundingDINO`, `SAM` and `RAM/Tag2Text`:
501
+
502
+ ```bash
503
+ wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth
504
+ wget https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth
505
+
506
+
507
+ wget https://huggingface.co/spaces/xinyu1205/Tag2Text/resolve/main/ram_swin_large_14m.pth
508
+ wget https://huggingface.co/spaces/xinyu1205/Tag2Text/resolve/main/tag2text_swin_14m.pth
509
+ ```
510
+
511
+ **Step 2: Running the demo with RAM**
512
+ ```bash
513
+ export CUDA_VISIBLE_DEVICES=0
514
+ python automatic_label_ram_demo.py \
515
+ --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
516
+ --ram_checkpoint ram_swin_large_14m.pth \
517
+ --grounded_checkpoint groundingdino_swint_ogc.pth \
518
+ --sam_checkpoint sam_vit_h_4b8939.pth \
519
+ --input_image assets/demo9.jpg \
520
+ --output_dir "outputs" \
521
+ --box_threshold 0.25 \
522
+ --text_threshold 0.2 \
523
+ --iou_threshold 0.5 \
524
+ --device "cuda"
525
+ ```
526
+
527
+
528
+ **Step 2: Or Running the demo with Tag2Text**
529
+ ```bash
530
+ export CUDA_VISIBLE_DEVICES=0
531
+ python automatic_label_tag2text_demo.py \
532
+ --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
533
+ --tag2text_checkpoint tag2text_swin_14m.pth \
534
+ --grounded_checkpoint groundingdino_swint_ogc.pth \
535
+ --sam_checkpoint sam_vit_h_4b8939.pth \
536
+ --input_image assets/demo9.jpg \
537
+ --output_dir "outputs" \
538
+ --box_threshold 0.25 \
539
+ --text_threshold 0.2 \
540
+ --iou_threshold 0.5 \
541
+ --device "cuda"
542
+ ```
543
+
544
+ - RAM++ significantly improves the open-set capability of RAM, for [RAM++ inference on unseen categoreis](https://github.com/xinyu1205/recognize-anything#ram-inference-on-unseen-categories-open-set).
545
+ - Tag2Text also provides powerful captioning capabilities, and the process with captions can refer to [BLIP](#robot-run-grounded-segment-anything--blip-demo).
546
+ - The pseudo labels and model prediction visualization will be saved in `output_dir` as follows (right figure):
547
+
548
+ ![](./assets/automatic_label_output/demo9_tag2text_ram.jpg)
549
+
550
+
551
+ ### :robot: Grounded-SAM with BLIP for Automatic Labeling
552
+ It is easy to generate pseudo labels automatically as follows:
553
+ 1. Use BLIP (or other caption models) to generate a caption.
554
+ 2. Extract tags from the caption. We use ChatGPT to handle the potential complicated sentences.
555
+ 3. Use Grounded-Segment-Anything to generate the boxes and masks.
556
+
557
+ - Run Demo
558
+ ```bash
559
+ export OPENAI_API_KEY=your_openai_key
560
+ export OPENAI_API_BASE=https://closeai.deno.dev/v1
561
+ export CUDA_VISIBLE_DEVICES=0
562
+ python automatic_label_demo.py \
563
+ --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
564
+ --grounded_checkpoint groundingdino_swint_ogc.pth \
565
+ --sam_checkpoint sam_vit_h_4b8939.pth \
566
+ --input_image assets/demo3.jpg \
567
+ --output_dir "outputs" \
568
+ --openai_key $OPENAI_API_KEY \
569
+ --box_threshold 0.25 \
570
+ --text_threshold 0.2 \
571
+ --iou_threshold 0.5 \
572
+ --device "cuda"
573
+ ```
574
+
575
+ - When you don't have a paid Account for ChatGPT is also possible to use NLTK instead. Just don't include the ```openai_key``` Parameter when starting the Demo.
576
+ - The Script will automatically download the necessary NLTK Data.
577
+ - The pseudo labels and model prediction visualization will be saved in `output_dir` as follows:
578
+
579
+ ![](./assets/automatic_label_output_demo3.jpg)
580
+
581
+
582
+ ### :open_mouth: Grounded-SAM with Whisper: Detect and Segment Anything with Audio
583
+ Detect and segment anything with speech!
584
+
585
+ ![](assets/acoustics/gsam_whisper_inpainting_demo.png)
586
+
587
+ **Install Whisper**
588
+ ```bash
589
+ pip install -U openai-whisper
590
+ ```
591
+ See the [whisper official page](https://github.com/openai/whisper#setup) if you have other questions for the installation.
592
+
593
+ **Run Voice-to-Label Demo**
594
+
595
+ Optional: Download the demo audio file
596
+
597
+ ```bash
598
+ wget https://huggingface.co/ShilongLiu/GroundingDINO/resolve/main/demo_audio.mp3
599
+ ```
600
+
601
+
602
+ ```bash
603
+ export CUDA_VISIBLE_DEVICES=0
604
+ python grounded_sam_whisper_demo.py \
605
+ --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
606
+ --grounded_checkpoint groundingdino_swint_ogc.pth \
607
+ --sam_checkpoint sam_vit_h_4b8939.pth \
608
+ --input_image assets/demo4.jpg \
609
+ --output_dir "outputs" \
610
+ --box_threshold 0.3 \
611
+ --text_threshold 0.25 \
612
+ --speech_file "demo_audio.mp3" \
613
+ --device "cuda"
614
+ ```
615
+
616
+ ![](./assets/grounded_sam_whisper_output.jpg)
617
+
618
+ **Run Voice-to-inpaint Demo**
619
+
620
+ You can enable chatgpt to help you automatically detect the object and inpainting order with `--enable_chatgpt`.
621
+
622
+ Or you can specify the object you want to inpaint [stored in `args.det_speech_file`] and the text you want to inpaint with [stored in `args.inpaint_speech_file`].
623
+
624
+ ```bash
625
+ export OPENAI_API_KEY=your_openai_key
626
+ export OPENAI_API_BASE=https://closeai.deno.dev/v1
627
+ # Example: enable chatgpt
628
+ export CUDA_VISIBLE_DEVICES=0
629
+ python grounded_sam_whisper_inpainting_demo.py \
630
+ --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
631
+ --grounded_checkpoint groundingdino_swint_ogc.pth \
632
+ --sam_checkpoint sam_vit_h_4b8939.pth \
633
+ --input_image assets/inpaint_demo.jpg \
634
+ --output_dir "outputs" \
635
+ --box_threshold 0.3 \
636
+ --text_threshold 0.25 \
637
+ --prompt_speech_file assets/acoustics/prompt_speech_file.mp3 \
638
+ --enable_chatgpt \
639
+ --openai_key $OPENAI_API_KEY\
640
+ --device "cuda"
641
+ ```
642
+
643
+ ```bash
644
+ # Example: without chatgpt
645
+ export CUDA_VISIBLE_DEVICES=0
646
+ python grounded_sam_whisper_inpainting_demo.py \
647
+ --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
648
+ --grounded_checkpoint groundingdino_swint_ogc.pth \
649
+ --sam_checkpoint sam_vit_h_4b8939.pth \
650
+ --input_image assets/inpaint_demo.jpg \
651
+ --output_dir "outputs" \
652
+ --box_threshold 0.3 \
653
+ --text_threshold 0.25 \
654
+ --det_speech_file "assets/acoustics/det_voice.mp3" \
655
+ --inpaint_speech_file "assets/acoustics/inpaint_voice.mp3" \
656
+ --device "cuda"
657
+ ```
658
+
659
+ ![](./assets/acoustics/gsam_whisper_inpainting_pipeline.png)
660
+
661
+ ### :speech_balloon: Grounded-SAM ChatBot Demo
662
+
663
+ https://user-images.githubusercontent.com/24236723/231955561-2ae4ec1a-c75f-4cc5-9b7b-517aa1432123.mp4
664
+
665
+ Following [Visual ChatGPT](https://github.com/microsoft/visual-chatgpt), we add a ChatBot for our project. Currently, it supports:
666
+ 1. "Describe the image."
667
+ 2. "Detect the dog (and the cat) in the image."
668
+ 3. "Segment anything in the image."
669
+ 4. "Segment the dog (and the cat) in the image."
670
+ 5. "Help me label the image."
671
+ 6. "Replace the dog with a cat in the image."
672
+
673
+ To use the ChatBot:
674
+ - Install whisper if you want to use audio as input.
675
+ - Set the default model setting in the tool `Grounded_dino_sam_inpainting`.
676
+ - Run Demo
677
+ ```bash
678
+ export OPENAI_API_KEY=your_openai_key
679
+ export OPENAI_API_BASE=https://closeai.deno.dev/v1
680
+ export CUDA_VISIBLE_DEVICES=0
681
+ python chatbot.py
682
+ ```
683
+
684
+ ### :man_dancing: Run Grounded-Segment-Anything + OSX Demo
685
+
686
+ <p align="middle">
687
+ <img src="assets/osx/grouned_sam_osx_demo.gif">
688
+ <br>
689
+ </p>
690
+
691
+
692
+ - Download the checkpoint `osx_l_wo_decoder.pth.tar` from [here](https://drive.google.com/drive/folders/1x7MZbB6eAlrq5PKC9MaeIm4GqkBpokow?usp=share_link) for OSX:
693
+ - Download the human model files and place it into `grounded-sam-osx/utils/human_model_files` following the instruction of [OSX](https://github.com/IDEA-Research/OSX).
694
+
695
+ - Run Demo
696
+
697
+ ```shell
698
+ export CUDA_VISIBLE_DEVICES=0
699
+ python grounded_sam_osx_demo.py \
700
+ --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
701
+ --grounded_checkpoint groundingdino_swint_ogc.pth \
702
+ --sam_checkpoint sam_vit_h_4b8939.pth \
703
+ --osx_checkpoint osx_l_wo_decoder.pth.tar \
704
+ --input_image assets/osx/grounded_sam_osx_demo.png \
705
+ --output_dir "outputs" \
706
+ --box_threshold 0.3 \
707
+ --text_threshold 0.25 \
708
+ --text_prompt "humans, chairs" \
709
+ --device "cuda"
710
+ ```
711
+
712
+ - The model prediction visualization will be saved in `output_dir` as follows:
713
+
714
+ <img src="assets/osx/grounded_sam_osx_output.jpg" style="zoom: 49%;" />
715
+
716
+ - We also support promptable 3D whole-body mesh recovery. For example, you can track someone with a text prompt and estimate his 3D pose and shape :
717
+
718
+ | ![space-1.jpg](assets/osx/grounded_sam_osx_output1.jpg) |
719
+ | :---------------------------------------------------: |
720
+ | *A person with pink clothes* |
721
+
722
+ | ![space-1.jpg](assets/osx/grounded_sam_osx_output2.jpg) |
723
+ | :---------------------------------------------------: |
724
+ | *A man with a sunglasses* |
725
+
726
+
727
+ ## :man_dancing: Run Grounded-Segment-Anything + VISAM Demo
728
+
729
+ - Download the checkpoint `motrv2_dancetrack.pth` from [here](https://drive.google.com/file/d/1EA4lndu2yQcVgBKR09KfMe5efbf631Th/view?usp=share_link) for MOTRv2:
730
+ - See the more thing if you have other questions for the installation.
731
+
732
+ - Run Demo
733
+
734
+ ```shell
735
+ export CUDA_VISIBLE_DEVICES=0
736
+ python grounded_sam_visam.py \
737
+ --meta_arch motr \
738
+ --dataset_file e2e_dance \
739
+ --with_box_refine \
740
+ --query_interaction_layer QIMv2 \
741
+ --num_queries 10 \
742
+ --det_db det_db_motrv2.json \
743
+ --use_checkpoint \
744
+ --mot_path your_data_path \
745
+ --resume motrv2_dancetrack.pth \
746
+ --sam_checkpoint sam_vit_h_4b8939.pth \
747
+ --video_path DanceTrack/test/dancetrack0003
748
+ ```
749
+ |![](https://raw.githubusercontent.com/BingfengYan/MOTSAM/main/visam.gif)|
750
+
751
+
752
+ ### :dancers: Interactive Editing
753
+ - Release the interactive fashion-edit playground in [here](https://github.com/IDEA-Research/Grounded-Segment-Anything/tree/humanFace). Run in the notebook, just click for annotating points for further segmentation. Enjoy it!
754
+
755
+
756
+ - Release human-face-edit branch [here](https://github.com/IDEA-Research/Grounded-Segment-Anything/tree/humanFace). We'll keep updating this branch with more interesting features. Here are some examples:
757
+
758
+ ![](https://github.com/IDEA-Research/Grounded-Segment-Anything/blob/humanFace/assets/231-hair-edit.png)
759
+
760
+ ## :camera: 3D-Box via Segment Anything
761
+ We extend the scope to 3D world by combining Segment Anything and [VoxelNeXt](https://github.com/dvlab-research/VoxelNeXt). When we provide a prompt (e.g., a point / box), the result is not only 2D segmentation mask, but also 3D boxes. Please check [voxelnext_3d_box](./voxelnext_3d_box/) for more details.
762
+ ![](https://github.com/IDEA-Research/Grounded-Segment-Anything/blob/main/voxelnext_3d_box/images/sam-voxelnext.png)
763
+ ![](https://github.com/IDEA-Research/Grounded-Segment-Anything/blob/main/voxelnext_3d_box/images/image_boxes2.png)
764
+
765
+
766
+
767
+
768
+ ## :cupid: Acknowledgements
769
+
770
+ - [Segment Anything](https://github.com/facebookresearch/segment-anything)
771
+ - [Grounding DINO](https://github.com/IDEA-Research/GroundingDINO)
772
+
773
+
774
+ ## Contributors
775
+
776
+ Our project wouldn't be possible without the contributions of these amazing people! Thank you all for making this project better.
777
+
778
+ <a href="https://github.com/IDEA-Research/Grounded-Segment-Anything/graphs/contributors">
779
+ <img src="https://contrib.rocks/image?repo=IDEA-Research/Grounded-Segment-Anything" />
780
+ </a>
781
+
782
+
783
+ ## Citation
784
+ If you find this project helpful for your research, please consider citing the following BibTeX entry.
785
+ ```BibTex
786
+ @article{kirillov2023segany,
787
+ title={Segment Anything},
788
+ author={Kirillov, Alexander and Mintun, Eric and Ravi, Nikhila and Mao, Hanzi and Rolland, Chloe and Gustafson, Laura and Xiao, Tete and Whitehead, Spencer and Berg, Alexander C. and Lo, Wan-Yen and Doll{\'a}r, Piotr and Girshick, Ross},
789
+ journal={arXiv:2304.02643},
790
+ year={2023}
791
+ }
792
+
793
+ @article{liu2023grounding,
794
+ title={Grounding dino: Marrying dino with grounded pre-training for open-set object detection},
795
+ author={Liu, Shilong and Zeng, Zhaoyang and Ren, Tianhe and Li, Feng and Zhang, Hao and Yang, Jie and Li, Chunyuan and Yang, Jianwei and Su, Hang and Zhu, Jun and others},
796
+ journal={arXiv preprint arXiv:2303.05499},
797
+ year={2023}
798
+ }
799
+
800
+ @misc{ren2024grounded,
801
+ title={Grounded SAM: Assembling Open-World Models for Diverse Visual Tasks},
802
+ author={Tianhe Ren and Shilong Liu and Ailing Zeng and Jing Lin and Kunchang Li and He Cao and Jiayu Chen and Xinyu Huang and Yukang Chen and Feng Yan and Zhaoyang Zeng and Hao Zhang and Feng Li and Jie Yang and Hongyang Li and Qing Jiang and Lei Zhang},
803
+ year={2024},
804
+ eprint={2401.14159},
805
+ archivePrefix={arXiv},
806
+ primaryClass={cs.CV}
807
+ }
808
+ ```
external/Grounded-Segment-Anything/automatic_label_simple_demo.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import supervision as sv
4
+ from typing import List
5
+ from PIL import Image
6
+
7
+ import torch
8
+
9
+ from groundingdino.util.inference import Model
10
+ from segment_anything import sam_model_registry, SamPredictor
11
+
12
+ # Tag2Text
13
+ # from ram.models import tag2text_caption
14
+ from ram.models import ram
15
+ # from ram import inference_tag2text
16
+ from ram import inference_ram
17
+ import torchvision
18
+ import torchvision.transforms as TS
19
+
20
+
21
+ # Hyper-Params
22
+ SOURCE_IMAGE_PATH = "./assets/demo9.jpg"
23
+ DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
24
+
25
+ GROUNDING_DINO_CONFIG_PATH = "GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py"
26
+ GROUNDING_DINO_CHECKPOINT_PATH = "./groundingdino_swint_ogc.pth"
27
+
28
+ SAM_ENCODER_VERSION = "vit_h"
29
+ SAM_CHECKPOINT_PATH = "./sam_vit_h_4b8939.pth"
30
+
31
+ TAG2TEXT_CHECKPOINT_PATH = "./tag2text_swin_14m.pth"
32
+ RAM_CHECKPOINT_PATH = "./ram_swin_large_14m.pth"
33
+
34
+ TAG2TEXT_THRESHOLD = 0.64
35
+ BOX_THRESHOLD = 0.2
36
+ TEXT_THRESHOLD = 0.2
37
+ IOU_THRESHOLD = 0.5
38
+
39
+ # Building GroundingDINO inference model
40
+ grounding_dino_model = Model(model_config_path=GROUNDING_DINO_CONFIG_PATH, model_checkpoint_path=GROUNDING_DINO_CHECKPOINT_PATH)
41
+
42
+
43
+ # Building SAM Model and SAM Predictor
44
+ sam = sam_model_registry[SAM_ENCODER_VERSION](checkpoint=SAM_CHECKPOINT_PATH)
45
+ sam_predictor = SamPredictor(sam)
46
+
47
+ # Tag2Text
48
+ # initialize Tag2Text
49
+ normalize = TS.Normalize(
50
+ mean=[0.485, 0.456, 0.406],
51
+ std=[0.229, 0.224, 0.225]
52
+ )
53
+ transform = TS.Compose(
54
+ [
55
+ TS.Resize((384, 384)),
56
+ TS.ToTensor(),
57
+ normalize
58
+ ]
59
+ )
60
+
61
+ DELETE_TAG_INDEX = [] # filter out attributes and action which are difficult to be grounded
62
+ for idx in range(3012, 3429):
63
+ DELETE_TAG_INDEX.append(idx)
64
+
65
+ # tag2text_model = tag2text_caption(
66
+ # pretrained=TAG2TEXT_CHECKPOINT_PATH,
67
+ # image_size=384,
68
+ # vit='swin_b',
69
+ # delete_tag_index=DELETE_TAG_INDEX
70
+ # )
71
+ # # threshold for tagging
72
+ # # we reduce the threshold to obtain more tags
73
+ # tag2text_model.threshold = TAG2TEXT_THRESHOLD
74
+ # tag2text_model.eval()
75
+ # tag2text_model = tag2text_model.to(DEVICE)
76
+
77
+ ram_model = ram(pretrained=RAM_CHECKPOINT_PATH,
78
+ image_size=384,
79
+ vit='swin_l')
80
+ ram_model.eval()
81
+ ram_model = ram_model.to(DEVICE)
82
+
83
+ # load image
84
+ image = cv2.imread(SOURCE_IMAGE_PATH) # bgr
85
+ image_pillow = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) # rgb
86
+
87
+ image_pillow = image_pillow.resize((384, 384))
88
+ image_pillow = transform(image_pillow).unsqueeze(0).to(DEVICE)
89
+
90
+ specified_tags='None'
91
+ # res = inference_tag2text(image_pillow , tag2text_model, specified_tags)
92
+ res = inference_ram(image_pillow , ram_model)
93
+
94
+ # Currently ", " is better for detecting single tags
95
+ # while ". " is a little worse in some case
96
+ AUTOMATIC_CLASSES=res[0].split(" | ")
97
+
98
+ print(f"Tags: {res[0].replace(' |', ',')}")
99
+
100
+
101
+ # detect objects
102
+ detections = grounding_dino_model.predict_with_classes(
103
+ image=image,
104
+ classes=AUTOMATIC_CLASSES,
105
+ box_threshold=BOX_THRESHOLD,
106
+ text_threshold=BOX_THRESHOLD
107
+ )
108
+
109
+ # NMS post process
110
+ print(f"Before NMS: {len(detections.xyxy)} boxes")
111
+ nms_idx = torchvision.ops.nms(
112
+ torch.from_numpy(detections.xyxy),
113
+ torch.from_numpy(detections.confidence),
114
+ IOU_THRESHOLD
115
+ ).numpy().tolist()
116
+
117
+ detections.xyxy = detections.xyxy[nms_idx]
118
+ detections.confidence = detections.confidence[nms_idx]
119
+ detections.class_id = detections.class_id[nms_idx]
120
+
121
+ print(f"After NMS: {len(detections.xyxy)} boxes")
122
+
123
+ # annotate image with detections
124
+ box_annotator = sv.BoxAnnotator()
125
+ labels = [
126
+ f"{AUTOMATIC_CLASSES[class_id]} {confidence:0.2f}"
127
+ for _, _, confidence, class_id, _, _
128
+ in detections]
129
+ annotated_frame = box_annotator.annotate(scene=image.copy(), detections=detections, labels=labels)
130
+
131
+ # save the annotated grounding dino image
132
+ cv2.imwrite("groundingdino_auto_annotated_image.jpg", annotated_frame)
133
+
134
+ # Prompting SAM with detected boxes
135
+ def segment(sam_predictor: SamPredictor, image: np.ndarray, xyxy: np.ndarray) -> np.ndarray:
136
+ sam_predictor.set_image(image)
137
+ result_masks = []
138
+ for box in xyxy:
139
+ masks, scores, logits = sam_predictor.predict(
140
+ box=box,
141
+ multimask_output=True
142
+ )
143
+ index = np.argmax(scores)
144
+ result_masks.append(masks[index])
145
+ return np.array(result_masks)
146
+
147
+
148
+ # convert detections to masks
149
+ detections.mask = segment(
150
+ sam_predictor=sam_predictor,
151
+ image=cv2.cvtColor(image, cv2.COLOR_BGR2RGB),
152
+ xyxy=detections.xyxy
153
+ )
154
+
155
+ # annotate image with detections
156
+ box_annotator = sv.BoxAnnotator()
157
+ mask_annotator = sv.MaskAnnotator()
158
+ labels = [
159
+ f"{AUTOMATIC_CLASSES[class_id]} {confidence:0.2f}"
160
+ for _, _, confidence, class_id, _, _
161
+ in detections]
162
+ annotated_image = mask_annotator.annotate(scene=image.copy(), detections=detections)
163
+ annotated_image = box_annotator.annotate(scene=annotated_image, detections=detections, labels=labels)
164
+
165
+ # save the annotated grounded-sam image
166
+ cv2.imwrite("ram_grounded_sam_auto_annotated_image.jpg", annotated_image)
external/Grounded-Segment-Anything/grounded_sam_3d_box.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
external/Grounded-Segment-Anything/grounded_sam_colab_demo.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
external/Grounded-Segment-Anything/grounded_sam_demo.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import sys
4
+
5
+ import numpy as np
6
+ import json
7
+ import torch
8
+ from PIL import Image
9
+
10
+ sys.path.append(os.path.join(os.getcwd(), "GroundingDINO"))
11
+ sys.path.append(os.path.join(os.getcwd(), "segment_anything"))
12
+
13
+
14
+ # Grounding DINO
15
+ import GroundingDINO.groundingdino.datasets.transforms as T
16
+ from GroundingDINO.groundingdino.models import build_model
17
+ from GroundingDINO.groundingdino.util.slconfig import SLConfig
18
+ from GroundingDINO.groundingdino.util.utils import clean_state_dict, get_phrases_from_posmap
19
+
20
+
21
+ # segment anything
22
+ from segment_anything import (
23
+ sam_model_registry,
24
+ sam_hq_model_registry,
25
+ SamPredictor
26
+ )
27
+ import cv2
28
+ import numpy as np
29
+ import matplotlib.pyplot as plt
30
+
31
+
32
+ def load_image(image_path):
33
+ # load image
34
+ image_pil = Image.open(image_path).convert("RGB") # load image
35
+
36
+ transform = T.Compose(
37
+ [
38
+ T.RandomResize([800], max_size=1333),
39
+ T.ToTensor(),
40
+ T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
41
+ ]
42
+ )
43
+ image, _ = transform(image_pil, None) # 3, h, w
44
+ return image_pil, image
45
+
46
+
47
+ def load_model(model_config_path, model_checkpoint_path, bert_base_uncased_path, device):
48
+ args = SLConfig.fromfile(model_config_path)
49
+ args.device = device
50
+ args.bert_base_uncased_path = bert_base_uncased_path
51
+ model = build_model(args)
52
+ checkpoint = torch.load(model_checkpoint_path, map_location="cpu")
53
+ load_res = model.load_state_dict(clean_state_dict(checkpoint["model"]), strict=False)
54
+ print(load_res)
55
+ _ = model.eval()
56
+ return model
57
+
58
+
59
+ def get_grounding_output(model, image, caption, box_threshold, text_threshold, with_logits=True, device="cpu"):
60
+ caption = caption.lower()
61
+ caption = caption.strip()
62
+ if not caption.endswith("."):
63
+ caption = caption + "."
64
+ model = model.to(device)
65
+ image = image.to(device)
66
+ with torch.no_grad():
67
+ outputs = model(image[None], captions=[caption])
68
+ logits = outputs["pred_logits"].cpu().sigmoid()[0] # (nq, 256)
69
+ boxes = outputs["pred_boxes"].cpu()[0] # (nq, 4)
70
+ logits.shape[0]
71
+
72
+ # filter output
73
+ logits_filt = logits.clone()
74
+ boxes_filt = boxes.clone()
75
+ filt_mask = logits_filt.max(dim=1)[0] > box_threshold
76
+ logits_filt = logits_filt[filt_mask] # num_filt, 256
77
+ boxes_filt = boxes_filt[filt_mask] # num_filt, 4
78
+ logits_filt.shape[0]
79
+
80
+ # get phrase
81
+ tokenlizer = model.tokenizer
82
+ tokenized = tokenlizer(caption)
83
+ # build pred
84
+ pred_phrases = []
85
+ for logit, box in zip(logits_filt, boxes_filt):
86
+ pred_phrase = get_phrases_from_posmap(logit > text_threshold, tokenized, tokenlizer)
87
+ if with_logits:
88
+ pred_phrases.append(pred_phrase + f"({str(logit.max().item())[:4]})")
89
+ else:
90
+ pred_phrases.append(pred_phrase)
91
+
92
+ return boxes_filt, pred_phrases
93
+
94
+ def show_mask(mask, ax, random_color=False):
95
+ if random_color:
96
+ color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)
97
+ else:
98
+ color = np.array([30/255, 144/255, 255/255, 0.6])
99
+ h, w = mask.shape[-2:]
100
+ mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
101
+ ax.imshow(mask_image)
102
+
103
+
104
+ def show_box(box, ax, label):
105
+ x0, y0 = box[0], box[1]
106
+ w, h = box[2] - box[0], box[3] - box[1]
107
+ ax.add_patch(plt.Rectangle((x0, y0), w, h, edgecolor='green', facecolor=(0,0,0,0), lw=2))
108
+ ax.text(x0, y0, label)
109
+
110
+
111
+ def save_mask_data(output_dir, mask_list, box_list, label_list):
112
+ value = 0 # 0 for background
113
+
114
+ mask_img = torch.zeros(mask_list.shape[-2:])
115
+ for idx, mask in enumerate(mask_list):
116
+ mask_img[mask.cpu().numpy()[0] == True] = value + idx + 1
117
+ plt.figure(figsize=(10, 10))
118
+ plt.imshow(mask_img.numpy())
119
+ plt.axis('off')
120
+ plt.savefig(os.path.join(output_dir, 'mask.jpg'), bbox_inches="tight", dpi=300, pad_inches=0.0)
121
+
122
+ json_data = [{
123
+ 'value': value,
124
+ 'label': 'background'
125
+ }]
126
+ for label, box in zip(label_list, box_list):
127
+ value += 1
128
+ name, logit = label.split('(')
129
+ logit = logit[:-1] # the last is ')'
130
+ json_data.append({
131
+ 'value': value,
132
+ 'label': name,
133
+ 'logit': float(logit),
134
+ 'box': box.numpy().tolist(),
135
+ })
136
+ with open(os.path.join(output_dir, 'mask.json'), 'w') as f:
137
+ json.dump(json_data, f)
138
+
139
+
140
+ if __name__ == "__main__":
141
+
142
+ parser = argparse.ArgumentParser("Grounded-Segment-Anything Demo", add_help=True)
143
+ parser.add_argument("--config", type=str, required=True, help="path to config file")
144
+ parser.add_argument(
145
+ "--grounded_checkpoint", type=str, required=True, help="path to checkpoint file"
146
+ )
147
+ parser.add_argument(
148
+ "--sam_version", type=str, default="vit_h", required=False, help="SAM ViT version: vit_b / vit_l / vit_h"
149
+ )
150
+ parser.add_argument(
151
+ "--sam_checkpoint", type=str, required=False, help="path to sam checkpoint file"
152
+ )
153
+ parser.add_argument(
154
+ "--sam_hq_checkpoint", type=str, default=None, help="path to sam-hq checkpoint file"
155
+ )
156
+ parser.add_argument(
157
+ "--use_sam_hq", action="store_true", help="using sam-hq for prediction"
158
+ )
159
+ parser.add_argument("--input_image", type=str, required=True, help="path to image file")
160
+ parser.add_argument("--text_prompt", type=str, required=True, help="text prompt")
161
+ parser.add_argument(
162
+ "--output_dir", "-o", type=str, default="outputs", required=True, help="output directory"
163
+ )
164
+
165
+ parser.add_argument("--box_threshold", type=float, default=0.3, help="box threshold")
166
+ parser.add_argument("--text_threshold", type=float, default=0.25, help="text threshold")
167
+
168
+ parser.add_argument("--device", type=str, default="cpu", help="running on cpu only!, default=False")
169
+ parser.add_argument("--bert_base_uncased_path", type=str, required=False, help="bert_base_uncased model path, default=False")
170
+ args = parser.parse_args()
171
+
172
+ # cfg
173
+ config_file = args.config # change the path of the model config file
174
+ grounded_checkpoint = args.grounded_checkpoint # change the path of the model
175
+ sam_version = args.sam_version
176
+ sam_checkpoint = args.sam_checkpoint
177
+ sam_hq_checkpoint = args.sam_hq_checkpoint
178
+ use_sam_hq = args.use_sam_hq
179
+ image_path = args.input_image
180
+ text_prompt = args.text_prompt
181
+ output_dir = args.output_dir
182
+ box_threshold = args.box_threshold
183
+ text_threshold = args.text_threshold
184
+ device = args.device
185
+ bert_base_uncased_path = args.bert_base_uncased_path
186
+
187
+ # make dir
188
+ os.makedirs(output_dir, exist_ok=True)
189
+ # load image
190
+ image_pil, image = load_image(image_path)
191
+ # load model
192
+ model = load_model(config_file, grounded_checkpoint, bert_base_uncased_path, device=device)
193
+
194
+ # visualize raw image
195
+ image_pil.save(os.path.join(output_dir, "raw_image.jpg"))
196
+
197
+ # run grounding dino model
198
+ boxes_filt, pred_phrases = get_grounding_output(
199
+ model, image, text_prompt, box_threshold, text_threshold, device=device
200
+ )
201
+
202
+ # initialize SAM
203
+ if use_sam_hq:
204
+ predictor = SamPredictor(sam_hq_model_registry[sam_version](checkpoint=sam_hq_checkpoint).to(device))
205
+ else:
206
+ predictor = SamPredictor(sam_model_registry[sam_version](checkpoint=sam_checkpoint).to(device))
207
+ image = cv2.imread(image_path)
208
+ image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
209
+ predictor.set_image(image)
210
+
211
+ size = image_pil.size
212
+ H, W = size[1], size[0]
213
+ for i in range(boxes_filt.size(0)):
214
+ boxes_filt[i] = boxes_filt[i] * torch.Tensor([W, H, W, H])
215
+ boxes_filt[i][:2] -= boxes_filt[i][2:] / 2
216
+ boxes_filt[i][2:] += boxes_filt[i][:2]
217
+
218
+ boxes_filt = boxes_filt.cpu()
219
+ transformed_boxes = predictor.transform.apply_boxes_torch(boxes_filt, image.shape[:2]).to(device)
220
+
221
+ masks, _, _ = predictor.predict_torch(
222
+ point_coords = None,
223
+ point_labels = None,
224
+ boxes = transformed_boxes.to(device),
225
+ multimask_output = False,
226
+ )
227
+
228
+ # draw output image
229
+ plt.figure(figsize=(10, 10))
230
+ plt.imshow(image)
231
+ for mask in masks:
232
+ show_mask(mask.cpu().numpy(), plt.gca(), random_color=True)
233
+ for box, label in zip(boxes_filt, pred_phrases):
234
+ show_box(box.numpy(), plt.gca(), label)
235
+
236
+ plt.axis('off')
237
+ plt.savefig(
238
+ os.path.join(output_dir, "grounded_sam_output.jpg"),
239
+ bbox_inches="tight", dpi=300, pad_inches=0.0
240
+ )
241
+
242
+ save_mask_data(output_dir, masks, boxes_filt, pred_phrases)
external/Grounded-Segment-Anything/grounded_sam_osx_demo.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torchvision.transforms as transforms
2
+ from torch.nn.parallel.data_parallel import DataParallel
3
+ import torch.backends.cudnn as cudnn
4
+ import argparse
5
+ import json
6
+ import torch
7
+ from PIL import Image
8
+ import matplotlib.pyplot as plt
9
+ import os
10
+ import cv2
11
+ import numpy as np
12
+
13
+ # Grounding DINO
14
+ import GroundingDINO.groundingdino.datasets.transforms as T
15
+ from GroundingDINO.groundingdino.models import build_model
16
+ from GroundingDINO.groundingdino.util.slconfig import SLConfig
17
+ from GroundingDINO.groundingdino.util.utils import clean_state_dict, get_phrases_from_posmap
18
+
19
+ # segment anything
20
+ from segment_anything import build_sam, SamPredictor
21
+
22
+
23
+ # OSX
24
+ import sys
25
+ sys.path.insert(0, 'grounded-sam-osx')
26
+ from osx import get_model
27
+ from config import cfg
28
+ from utils.preprocessing import load_img, process_bbox, generate_patch_image
29
+ from utils.human_models import smpl_x
30
+
31
+ os.environ["PYOPENGL_PLATFORM"] = "egl"
32
+ from utils.vis import render_mesh, save_obj
33
+ cudnn.benchmark = True
34
+
35
+ def load_image(image_path):
36
+ # load image
37
+ image_pil = Image.open(image_path).convert("RGB") # load image
38
+
39
+ transform = T.Compose(
40
+ [
41
+ T.RandomResize([800], max_size=1333),
42
+ T.ToTensor(),
43
+ T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
44
+ ]
45
+ )
46
+ image, _ = transform(image_pil, None) # 3, h, w
47
+ return image_pil, image
48
+
49
+
50
+ def load_model(model_config_path, model_checkpoint_path, device):
51
+ args = SLConfig.fromfile(model_config_path)
52
+ args.device = device
53
+ model = build_model(args)
54
+ checkpoint = torch.load(model_checkpoint_path, map_location="cpu")
55
+ load_res = model.load_state_dict(clean_state_dict(checkpoint["model"]), strict=False)
56
+ print(load_res)
57
+ _ = model.eval()
58
+ return model
59
+
60
+
61
+ def get_grounding_output(model, image, caption, box_threshold, text_threshold, with_logits=True, device="cpu"):
62
+ caption = caption.lower()
63
+ caption = caption.strip()
64
+ if not caption.endswith("."):
65
+ caption = caption + "."
66
+ model = model.to(device)
67
+ image = image.to(device)
68
+ with torch.no_grad():
69
+ outputs = model(image[None], captions=[caption])
70
+ logits = outputs["pred_logits"].cpu().sigmoid()[0] # (nq, 256)
71
+ boxes = outputs["pred_boxes"].cpu()[0] # (nq, 4)
72
+ logits.shape[0]
73
+
74
+ # filter output
75
+ logits_filt = logits.clone()
76
+ boxes_filt = boxes.clone()
77
+ filt_mask = logits_filt.max(dim=1)[0] > box_threshold
78
+ logits_filt = logits_filt[filt_mask] # num_filt, 256
79
+ boxes_filt = boxes_filt[filt_mask] # num_filt, 4
80
+ logits_filt.shape[0]
81
+
82
+ # get phrase
83
+ tokenlizer = model.tokenizer
84
+ tokenized = tokenlizer(caption)
85
+ # build pred
86
+ pred_phrases = []
87
+ for logit, box in zip(logits_filt, boxes_filt):
88
+ pred_phrase = get_phrases_from_posmap(logit > text_threshold, tokenized, tokenlizer)
89
+ if with_logits:
90
+ pred_phrases.append(pred_phrase + f"({str(logit.max().item())[:4]})")
91
+ else:
92
+ pred_phrases.append(pred_phrase)
93
+
94
+ return boxes_filt, pred_phrases
95
+
96
+
97
+ def show_mask(mask, ax, random_color=False):
98
+ if random_color:
99
+ color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)
100
+ else:
101
+ color = np.array([30 / 255, 144 / 255, 255 / 255, 0.6])
102
+ h, w = mask.shape[-2:]
103
+ mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
104
+ ax.imshow(mask_image)
105
+
106
+ def show_box(box, ax, label):
107
+ x0, y0 = box[0], box[1]
108
+ w, h = box[2] - box[0], box[3] - box[1]
109
+ if 'person' in label.lower() or 'human' in label.lower():
110
+ color = 'green'
111
+ else:
112
+ color = 'blue'
113
+ ax.add_patch(plt.Rectangle((x0, y0), w, h, edgecolor=color, facecolor=(0, 0, 0, 0), lw=2))
114
+ ax.text(x0, y0-5, label, fontsize=5, color='white',bbox={'facecolor': color, 'alpha': 0.7, 'pad': 1, 'edgecolor': 'none'})
115
+
116
+ def save_mask_data(output_dir, mask_list, box_list, label_list):
117
+ value = 0 # 0 for background
118
+
119
+ mask_img = torch.zeros(mask_list.shape[-2:])
120
+ for idx, mask in enumerate(mask_list):
121
+ mask_img[mask.cpu().numpy()[0] == True] = value + idx + 1
122
+ plt.figure(figsize=(10, 10))
123
+ plt.imshow(mask_img.numpy())
124
+ plt.axis('off')
125
+ plt.savefig(os.path.join(output_dir, 'mask.jpg'), bbox_inches="tight", dpi=300, pad_inches=0.0)
126
+
127
+ json_data = [{
128
+ 'value': value,
129
+ 'label': 'background'
130
+ }]
131
+ for label, box in zip(label_list, box_list):
132
+ value += 1
133
+ name, logit = label.split('(')
134
+ logit = logit[:-1] # the last is ')'
135
+ json_data.append({
136
+ 'value': value,
137
+ 'label': name,
138
+ 'logit': float(logit),
139
+ 'box': box.numpy().tolist(),
140
+ })
141
+ with open(os.path.join(output_dir, 'mask.json'), 'w') as f:
142
+ json.dump(json_data, f)
143
+
144
+ def bbox_resize(bbox, scale=1.0):
145
+ center = (bbox[2:] + bbox[:2]) / 2
146
+ new_size = (bbox[2:] - bbox[:2]) * scale
147
+ new_bbox = torch.cat((center - new_size / 2, center + new_size / 2))
148
+ return new_bbox
149
+
150
+ def mesh_recovery(original_img, bboxes):
151
+ transform = transforms.ToTensor()
152
+ original_img_height, original_img_width = original_img.shape[:2]
153
+
154
+ vis_img = original_img.copy()
155
+ for bbox in bboxes: # [x1, y1, x2, y2]
156
+ bbox = [bbox[0], bbox[1], bbox[2] - bbox[0], bbox[3] - bbox[1]] # xyxy -> xyhw
157
+ bbox = process_bbox(bbox, original_img_width, original_img_height)
158
+ img, img2bb_trans, bb2img_trans = generate_patch_image(original_img, bbox, 1.0, 0.0, False, cfg.input_img_shape)
159
+ img = transform(img.astype(np.float32)) / 255
160
+ img = img.cuda()[None, :, :, :]
161
+
162
+ # forward
163
+ inputs = {'img': img}
164
+ with torch.no_grad():
165
+ out = model(inputs, 'test')
166
+ mesh = out['smplx_mesh_cam'].detach().cpu().numpy()[0]
167
+
168
+ # # save mesh
169
+ # save_obj(mesh, smpl_x.face, 'output.obj')
170
+
171
+ focal = [cfg.focal[0] / cfg.input_body_shape[1] * bbox[2], cfg.focal[1] / cfg.input_body_shape[0] * bbox[3]]
172
+ princpt = [cfg.princpt[0] / cfg.input_body_shape[1] * bbox[2] + bbox[0],
173
+ cfg.princpt[1] / cfg.input_body_shape[0] * bbox[3] + bbox[1]]
174
+ rendered_img, _ = render_mesh(vis_img[:, :, ::-1], mesh, smpl_x.face, {'focal': focal, 'princpt': princpt})
175
+ vis_img = rendered_img.copy()
176
+
177
+ return rendered_img
178
+
179
+
180
+ if __name__ == "__main__":
181
+
182
+ parser = argparse.ArgumentParser("Grounded-Segment-Anything Demo", add_help=True)
183
+ parser.add_argument("--config", type=str, required=True, help="path to config file")
184
+ parser.add_argument(
185
+ "--grounded_checkpoint", type=str, required=True, help="path to checkpoint file"
186
+ )
187
+ parser.add_argument(
188
+ "--sam_checkpoint", type=str, required=True, help="path to checkpoint file"
189
+ )
190
+ parser.add_argument(
191
+ "--osx_checkpoint", type=str, required=True, help="path to checkpoint file"
192
+ )
193
+ parser.add_argument("--input_image", type=str, required=True, help="path to image file")
194
+ parser.add_argument("--text_prompt", type=str, required=True, help="text prompt")
195
+ parser.add_argument(
196
+ "--output_dir", "-o", type=str, default="outputs", required=True, help="output directory"
197
+ )
198
+
199
+ parser.add_argument("--box_threshold", type=float, default=0.3, help="box threshold")
200
+ parser.add_argument("--text_threshold", type=float, default=0.25, help="text threshold")
201
+
202
+ parser.add_argument("--device", type=str, default="cpu", help="running on cpu only!, default=False")
203
+ args = parser.parse_args()
204
+
205
+ # cfg
206
+ config_file = args.config # change the path of the model config file
207
+ grounded_checkpoint = args.grounded_checkpoint # change the path of the model
208
+ sam_checkpoint = args.sam_checkpoint
209
+ osx_checkpoint = args.osx_checkpoint
210
+ image_path = args.input_image
211
+ text_prompt = args.text_prompt
212
+ output_dir = args.output_dir
213
+ box_threshold = args.box_threshold
214
+ text_threshold = args.text_threshold
215
+ device = args.device
216
+
217
+ # make dir
218
+ os.makedirs(output_dir, exist_ok=True)
219
+ # load image
220
+ image_pil, image = load_image(image_path)
221
+ # load model
222
+ model = load_model(config_file, grounded_checkpoint, device=device)
223
+
224
+ # visualize raw image
225
+ image_pil.save(os.path.join(output_dir, "raw_image.jpg"))
226
+
227
+ # run grounding dino model
228
+ boxes_filt, pred_phrases = get_grounding_output(
229
+ model, image, text_prompt, box_threshold, text_threshold, device=device
230
+ )
231
+
232
+ # initialize SAM
233
+ sam = build_sam(checkpoint=sam_checkpoint)
234
+ sam.to(device=device)
235
+ predictor = SamPredictor(sam)
236
+ image = cv2.imread(image_path)
237
+ image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
238
+ predictor.set_image(image)
239
+
240
+ # initialize OSX
241
+ model = get_model()
242
+ model = DataParallel(model).cuda()
243
+ ckpt = torch.load(osx_checkpoint)
244
+ model.load_state_dict(ckpt['network'], strict=False)
245
+ model.eval()
246
+
247
+ size = image_pil.size
248
+ H, W = size[1], size[0]
249
+ for i in range(boxes_filt.size(0)):
250
+ boxes_filt[i] = boxes_filt[i] * torch.Tensor([W, H, W, H])
251
+ boxes_filt[i][:2] -= boxes_filt[i][2:] / 2
252
+ boxes_filt[i][2:] += boxes_filt[i][:2]
253
+
254
+ boxes_filt = boxes_filt.cpu()
255
+ transformed_boxes = predictor.transform.apply_boxes_torch(boxes_filt, image.shape[:2]).to(device)
256
+
257
+ masks, _, _ = predictor.predict_torch(
258
+ point_coords=None,
259
+ point_labels=None,
260
+ boxes=transformed_boxes,
261
+ multimask_output=False,
262
+ )
263
+
264
+ # scale up the human bboxes
265
+ boxes_human = []
266
+ for i, label in enumerate(pred_phrases):
267
+ if 'person' in label.lower() or 'human' in label.lower():
268
+ boxes_filt[i] = bbox_resize(boxes_filt[i], scale=1.1)
269
+ boxes_human.append(boxes_filt[i])
270
+
271
+ # predict and visualize 3d human mesh
272
+ for i, label in enumerate(pred_phrases):
273
+ if 'person' in label.lower() or 'man' in label.lower():
274
+ boxes_human.append(boxes_filt[i])
275
+ rendered_img = mesh_recovery(image, boxes_human)
276
+ cv2.imwrite(os.path.join(output_dir, "grounded_sam_osx_output.jpg"), rendered_img)
277
+
278
+ # draw output image
279
+ fig, (plt1, plt2) = plt.subplots(ncols=2, figsize=(10, 20), gridspec_kw={'wspace':0, 'hspace':0})
280
+
281
+ plt1.imshow(image)
282
+ for mask in masks:
283
+ show_mask(mask.cpu().numpy(), plt1, random_color=True)
284
+ for box, label in zip(boxes_filt, pred_phrases):
285
+ show_box(box.numpy(), plt1, label)
286
+ rendered_img = cv2.imread(os.path.join(output_dir, "grounded_sam_osx_output.jpg"))
287
+ plt2.imshow(rendered_img)
288
+ for box, label in zip(boxes_filt, pred_phrases):
289
+ show_box(box.numpy(), plt2, label)
290
+ plt1.axis('off')
291
+ plt2.axis('off')
292
+ plt.savefig(
293
+ os.path.join(output_dir, "grounded_sam_osx_output.jpg"),
294
+ bbox_inches="tight", dpi=300, pad_inches=0.0
295
+ )
296
+
297
+ save_mask_data(output_dir, masks, boxes_filt, pred_phrases)
298
+
299
+
external/Grounded-Segment-Anything/grounding_dino_demo.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from groundingdino.util.inference import load_model, load_image, predict, annotate, Model
2
+ import cv2
3
+
4
+
5
+ CONFIG_PATH = "GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py"
6
+ CHECKPOINT_PATH = "./groundingdino_swint_ogc.pth"
7
+ DEVICE = "cuda"
8
+ IMAGE_PATH = "assets/demo7.jpg"
9
+ TEXT_PROMPT = "Horse. Clouds. Grasses. Sky. Hill."
10
+ BOX_TRESHOLD = 0.35
11
+ TEXT_TRESHOLD = 0.25
12
+ FP16_INFERENCE = True
13
+
14
+ image_source, image = load_image(IMAGE_PATH)
15
+ model = load_model(CONFIG_PATH, CHECKPOINT_PATH)
16
+
17
+ if FP16_INFERENCE:
18
+ image = image.half()
19
+ model = model.half()
20
+
21
+ boxes, logits, phrases = predict(
22
+ model=model,
23
+ image=image,
24
+ caption=TEXT_PROMPT,
25
+ box_threshold=BOX_TRESHOLD,
26
+ text_threshold=TEXT_TRESHOLD,
27
+ device=DEVICE,
28
+ )
29
+
30
+ annotated_frame = annotate(image_source=image_source, boxes=boxes, logits=logits, phrases=phrases)
31
+ cv2.imwrite("annotated_image.jpg", annotated_frame)
external/Grounded-Segment-Anything/predict.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Prediction interface for Cog ⚙️
2
+ # https://github.com/replicate/cog/blob/main/docs/python.md
3
+
4
+ import os
5
+ import json
6
+ from typing import Any
7
+ import numpy as np
8
+ import random
9
+ import torch
10
+ import torchvision
11
+ import torchvision.transforms as transforms
12
+ from PIL import Image
13
+ import cv2
14
+ import matplotlib.pyplot as plt
15
+ from cog import BasePredictor, Input, Path, BaseModel
16
+
17
+ from subprocess import call
18
+
19
+ HOME = os.getcwd()
20
+ os.chdir("GroundingDINO")
21
+ call("pip install -q .", shell=True)
22
+ os.chdir(HOME)
23
+ os.chdir("segment_anything")
24
+ call("pip install -q .", shell=True)
25
+ os.chdir(HOME)
26
+
27
+ # Grounding DINO
28
+ import GroundingDINO.groundingdino.datasets.transforms as T
29
+ from GroundingDINO.groundingdino.models import build_model
30
+ from GroundingDINO.groundingdino.util.slconfig import SLConfig
31
+ from GroundingDINO.groundingdino.util.utils import (
32
+ clean_state_dict,
33
+ get_phrases_from_posmap,
34
+ )
35
+
36
+ # segment anything
37
+ from segment_anything import build_sam, build_sam_hq, SamPredictor
38
+
39
+ from ram.models import ram
40
+
41
+
42
+ class ModelOutput(BaseModel):
43
+ tags: str
44
+ rounding_box_img: Path
45
+ masked_img: Path
46
+ json_data: Any
47
+
48
+
49
+ class Predictor(BasePredictor):
50
+ def setup(self):
51
+ """Load the model into memory to make running multiple predictions efficient"""
52
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
53
+ normalize = transforms.Normalize(
54
+ mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
55
+ )
56
+ self.image_size = 384
57
+ self.transform = transforms.Compose(
58
+ [
59
+ transforms.Resize((self.image_size, self.image_size)),
60
+ transforms.ToTensor(),
61
+ normalize,
62
+ ]
63
+ )
64
+
65
+ # load model
66
+ self.ram_model = ram(
67
+ pretrained="pretrained/ram_swin_large_14m.pth",
68
+ image_size=self.image_size,
69
+ vit="swin_l",
70
+ )
71
+ self.ram_model.eval()
72
+ self.ram_model = self.ram_model.to(self.device)
73
+
74
+ self.model = load_model(
75
+ "GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py",
76
+ "pretrained/groundingdino_swint_ogc.pth",
77
+ device=self.device,
78
+ )
79
+
80
+ self.sam = SamPredictor(
81
+ build_sam(checkpoint="pretrained/sam_vit_h_4b8939.pth").to(self.device)
82
+ )
83
+ self.sam_hq = SamPredictor(
84
+ build_sam_hq(checkpoint="pretrained/sam_hq_vit_h.pth").to(self.device)
85
+ )
86
+
87
+ def predict(
88
+ self,
89
+ input_image: Path = Input(description="Input image"),
90
+ use_sam_hq: bool = Input(
91
+ description="Use sam_hq instead of SAM for prediction", default=False
92
+ ),
93
+ ) -> ModelOutput:
94
+ """Run a single prediction on the model"""
95
+
96
+ # default settings
97
+ box_threshold = 0.25
98
+ text_threshold = 0.2
99
+ iou_threshold = 0.5
100
+
101
+ image_pil, image = load_image(str(input_image))
102
+
103
+ raw_image = image_pil.resize((self.image_size, self.image_size))
104
+ raw_image = self.transform(raw_image).unsqueeze(0).to(self.device)
105
+
106
+ with torch.no_grad():
107
+ tags, tags_chinese = self.ram_model.generate_tag(raw_image)
108
+
109
+ tags = tags[0].replace(" |", ",")
110
+
111
+ # run grounding dino model
112
+ boxes_filt, scores, pred_phrases = get_grounding_output(
113
+ self.model, image, tags, box_threshold, text_threshold, device=self.device
114
+ )
115
+
116
+ predictor = self.sam_hq if use_sam_hq else self.sam
117
+
118
+ image = cv2.imread(str(input_image))
119
+ image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
120
+ predictor.set_image(image)
121
+
122
+ size = image_pil.size
123
+ H, W = size[1], size[0]
124
+ for i in range(boxes_filt.size(0)):
125
+ boxes_filt[i] = boxes_filt[i] * torch.Tensor([W, H, W, H])
126
+ boxes_filt[i][:2] -= boxes_filt[i][2:] / 2
127
+ boxes_filt[i][2:] += boxes_filt[i][:2]
128
+
129
+ boxes_filt = boxes_filt.cpu()
130
+ # use NMS to handle overlapped boxes
131
+ print(f"Before NMS: {boxes_filt.shape[0]} boxes")
132
+ nms_idx = (
133
+ torchvision.ops.nms(boxes_filt, scores, iou_threshold).numpy().tolist()
134
+ )
135
+ boxes_filt = boxes_filt[nms_idx]
136
+ pred_phrases = [pred_phrases[idx] for idx in nms_idx]
137
+ print(f"After NMS: {boxes_filt.shape[0]} boxes")
138
+
139
+ transformed_boxes = predictor.transform.apply_boxes_torch(
140
+ boxes_filt, image.shape[:2]
141
+ ).to(self.device)
142
+
143
+ masks, _, _ = predictor.predict_torch(
144
+ point_coords=None,
145
+ point_labels=None,
146
+ boxes=transformed_boxes.to(self.device),
147
+ multimask_output=False,
148
+ )
149
+
150
+ # draw output image
151
+ plt.figure(figsize=(10, 10))
152
+ for mask in masks:
153
+ show_mask(mask.cpu().numpy(), plt.gca(), random_color=True)
154
+ for box, label in zip(boxes_filt, pred_phrases):
155
+ show_box(box.numpy(), plt.gca(), label)
156
+
157
+ rounding_box_path = "/tmp/automatic_label_output.png"
158
+ plt.axis("off")
159
+ plt.savefig(
160
+ Path(rounding_box_path), bbox_inches="tight", dpi=300, pad_inches=0.0
161
+ )
162
+ plt.close()
163
+
164
+ # save masks and json data
165
+ value = 0 # 0 for background
166
+ mask_img = torch.zeros(masks.shape[-2:])
167
+ for idx, mask in enumerate(masks):
168
+ mask_img[mask.cpu().numpy()[0] == True] = value + idx + 1
169
+ plt.figure(figsize=(10, 10))
170
+ plt.imshow(mask_img.numpy())
171
+ plt.axis("off")
172
+ masks_path = "/tmp/mask.png"
173
+ plt.savefig(masks_path, bbox_inches="tight", dpi=300, pad_inches=0.0)
174
+ plt.close()
175
+
176
+ json_data = {
177
+ "tags": tags,
178
+ "mask": [{"value": value, "label": "background"}],
179
+ }
180
+ for label, box in zip(pred_phrases, boxes_filt):
181
+ value += 1
182
+ name, logit = label.split("(")
183
+ logit = logit[:-1] # the last is ')'
184
+ json_data["mask"].append(
185
+ {
186
+ "value": value,
187
+ "label": name,
188
+ "logit": float(logit),
189
+ "box": box.numpy().tolist(),
190
+ }
191
+ )
192
+
193
+ json_path = "/tmp/label.json"
194
+ with open(json_path, "w") as f:
195
+ json.dump(json_data, f)
196
+
197
+ return ModelOutput(
198
+ tags=tags,
199
+ masked_img=Path(masks_path),
200
+ rounding_box_img=Path(rounding_box_path),
201
+ json_data=Path(json_path),
202
+ )
203
+
204
+
205
+ def get_grounding_output(
206
+ model, image, caption, box_threshold, text_threshold, device="cpu"
207
+ ):
208
+ caption = caption.lower()
209
+ caption = caption.strip()
210
+ if not caption.endswith("."):
211
+ caption = caption + "."
212
+ model = model.to(device)
213
+ image = image.to(device)
214
+ with torch.no_grad():
215
+ outputs = model(image[None], captions=[caption])
216
+ logits = outputs["pred_logits"].cpu().sigmoid()[0] # (nq, 256)
217
+ boxes = outputs["pred_boxes"].cpu()[0] # (nq, 4)
218
+ logits.shape[0]
219
+
220
+ # filter output
221
+ logits_filt = logits.clone()
222
+ boxes_filt = boxes.clone()
223
+ filt_mask = logits_filt.max(dim=1)[0] > box_threshold
224
+ logits_filt = logits_filt[filt_mask] # num_filt, 256
225
+ boxes_filt = boxes_filt[filt_mask] # num_filt, 4
226
+ logits_filt.shape[0]
227
+
228
+ # get phrase
229
+ tokenlizer = model.tokenizer
230
+ tokenized = tokenlizer(caption)
231
+ # build pred
232
+ pred_phrases = []
233
+ scores = []
234
+ for logit, box in zip(logits_filt, boxes_filt):
235
+ pred_phrase = get_phrases_from_posmap(
236
+ logit > text_threshold, tokenized, tokenlizer
237
+ )
238
+ pred_phrases.append(pred_phrase + f"({str(logit.max().item())[:4]})")
239
+ scores.append(logit.max().item())
240
+
241
+ return boxes_filt, torch.Tensor(scores), pred_phrases
242
+
243
+
244
+ def load_image(image_path):
245
+ # load image
246
+ image_pil = Image.open(image_path).convert("RGB") # load image
247
+
248
+ transform = T.Compose(
249
+ [
250
+ T.RandomResize([800], max_size=1333),
251
+ T.ToTensor(),
252
+ T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
253
+ ]
254
+ )
255
+ image, _ = transform(image_pil, None) # 3, h, w
256
+ return image_pil, image
257
+
258
+
259
+ def load_model(model_config_path, model_checkpoint_path, device):
260
+ args = SLConfig.fromfile(model_config_path)
261
+ args.device = device
262
+ model = build_model(args)
263
+ checkpoint = torch.load(model_checkpoint_path, map_location="cpu")
264
+ load_res = model.load_state_dict(
265
+ clean_state_dict(checkpoint["model"]), strict=False
266
+ )
267
+ print(load_res)
268
+ _ = model.eval()
269
+ return model
270
+
271
+
272
+ def show_mask(mask, ax, random_color=False):
273
+ if random_color:
274
+ color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)
275
+ else:
276
+ color = np.array([30 / 255, 144 / 255, 255 / 255, 0.6])
277
+ h, w = mask.shape[-2:]
278
+ mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
279
+ ax.imshow(mask_image)
280
+
281
+
282
+ def show_box(box, ax, label):
283
+ x0, y0 = box[0], box[1]
284
+ w, h = box[2] - box[0], box[3] - box[1]
285
+ ax.add_patch(
286
+ plt.Rectangle((x0, y0), w, h, edgecolor="green", facecolor=(0, 0, 0, 0), lw=1.5)
287
+ )
288
+ ax.text(x0, y0, label)
external/Grounded-Segment-Anything/requirements.txt ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ addict
2
+ diffusers
3
+ gradio
4
+ huggingface_hub
5
+ matplotlib
6
+ numpy
7
+ onnxruntime
8
+ opencv_python
9
+ Pillow
10
+ pycocotools
11
+ PyYAML
12
+ requests
13
+ setuptools
14
+ supervision
15
+ termcolor
16
+ timm
17
+ torch
18
+ torchvision
19
+ transformers
20
+ yapf
21
+ nltk
22
+ fairscale
23
+ litellm
external/Metric3D/.gitignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ work_dirs
2
+ show_dirs
3
+ *__pycache__*
4
+ test_dataloader_*
5
+ *.onnx
external/Metric3D/LICENSE ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BSD 2-Clause License
2
+
3
+ Copyright (c) 2024, Wei Yin and Mu Hu
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
19
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
21
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
22
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
23
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
external/Metric3D/README.md ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚀 Metric3D Project 🚀
2
+
3
+ **Official PyTorch implementation of Metric3Dv1 and Metric3Dv2:**
4
+
5
+ [1] [Metric3D: Towards Zero-shot Metric 3D Prediction from A Single Image](https://arxiv.org/abs/2307.10984)
6
+
7
+ [2] [Metric3Dv2: A Versatile Monocular Geometric Foundation Model for Zero-shot Metric Depth and Surface Normal Estimation](https://arxiv.org/abs/2404.15506)
8
+
9
+ <a href='https://jugghm.github.io/Metric3Dv2'><img src='https://img.shields.io/badge/project%20page-@Metric3D-yellow.svg'></a>
10
+ <a href='https://arxiv.org/abs/2307.10984'><img src='https://img.shields.io/badge/arxiv-@Metric3Dv1-green'></a>
11
+ <a href='https://arxiv.org/abs/2404.15506'><img src='https://img.shields.io/badge/arxiv-@Metric3Dv2-red'></a>
12
+ <a href='https://huggingface.co/spaces/JUGGHM/Metric3D'><img src='https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue'></a>
13
+
14
+ [//]: # (### [Project Page]&#40;https://arxiv.org/abs/2307.08695&#41; | [v2 Paper]&#40;https://arxiv.org/abs/2307.10984&#41; | [v1 Arxiv]&#40;https://arxiv.org/abs/2307.10984&#41; | [Video]&#40;https://www.youtube.com/playlist?list=PLEuyXJsWqUNd04nwfm9gFBw5FVbcaQPl3&#41; | [Hugging Face 🤗]&#40;https://huggingface.co/spaces/JUGGHM/Metric3D&#41; )
15
+
16
+ [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/metric3d-v2-a-versatile-monocular-geometric-1/monocular-depth-estimation-on-nyu-depth-v2)](https://paperswithcode.com/sota/monocular-depth-estimation-on-nyu-depth-v2?p=metric3d-v2-a-versatile-monocular-geometric-1)
17
+
18
+ [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/metric3d-v2-a-versatile-monocular-geometric-1/monocular-depth-estimation-on-kitti-eigen)](https://paperswithcode.com/sota/monocular-depth-estimation-on-kitti-eigen?p=metric3d-v2-a-versatile-monocular-geometric-1)
19
+
20
+ [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/metric3d-v2-a-versatile-monocular-geometric-1/surface-normals-estimation-on-nyu-depth-v2-1)](https://paperswithcode.com/sota/surface-normals-estimation-on-nyu-depth-v2-1?p=metric3d-v2-a-versatile-monocular-geometric-1)
21
+
22
+ [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/metric3d-v2-a-versatile-monocular-geometric-1/surface-normals-estimation-on-ibims-1)](https://paperswithcode.com/sota/surface-normals-estimation-on-ibims-1?p=metric3d-v2-a-versatile-monocular-geometric-1)
23
+
24
+ [![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/metric3d-v2-a-versatile-monocular-geometric-1/surface-normals-estimation-on-scannetv2)](https://paperswithcode.com/sota/surface-normals-estimation-on-scannetv2?p=metric3d-v2-a-versatile-monocular-geometric-1)
25
+
26
+ 🏆 **Champion in [CVPR2023 Monocular Depth Estimation Challenge](https://jspenmar.github.io/MDEC)**
27
+
28
+ ## News
29
+ - `[2024/8]` Metric3Dv2 is accepted by TPAMI!
30
+ - `[2024/7/5]` Our stable-diffusion alternative GeoWizard has now been accepted by ECCV 2024! Check NOW the [repository](https://github.com/fuxiao0719/GeoWizard) and [paper](https://arxiv.org/abs/2403.12013) for the finest-grained geometry ever! 🎉🎉🎉
31
+ - `[2024/6/25]` Json files for KITTI datasets now available! Refer to [Training](./training/README.md) for more details
32
+ - `[2024/6/3]` ONNX is supported! We appreciate [@xenova](https://github.com/xenova) for their remarkable efforts!
33
+ - `[2024/4/25]` Weights for ViT-giant2 model released!
34
+ - `[2024/4/11]` Training codes are released!
35
+ - `[2024/3/18]` [HuggingFace 🤗](https://huggingface.co/spaces/JUGGHM/Metric3D) GPU version updated!
36
+ - `[2024/3/18]` [Project page](https://jugghm.github.io/Metric3Dv2/) released!
37
+ - `[2024/3/18]` Metric3D V2 models released, supporting metric depth and surface normal now!
38
+ - `[2023/8/10]` Inference codes, pre-trained weights, and demo released.
39
+ - `[2023/7]` Metric3D accepted by ICCV 2023!
40
+ - `[2023/4]` The Champion of [2nd Monocular Depth Estimation Challenge](https://jspenmar.github.io/MDEC) in CVPR 2023
41
+
42
+ ## 🌼 Abstract
43
+ Metric3D is a strong and robust geometry foundation model for high-quality and zero-shot **metric depth** and **surface normal** estimation from a single image. It excels at solving in-the-wild scene reconstruction. It can directly help you measure the size of structures from a single image. Now it achieves SOTA performance on over 10 depth and normal benchmarks.
44
+
45
+ ![depth_normal](media/screenshots/depth_normal.jpg)
46
+
47
+ ![metrology](media/screenshots/metrology.jpg)
48
+
49
+
50
+ ## 📝 Benchmarks
51
+
52
+ ### Metric Depth
53
+
54
+ [//]: # (#### Zero-shot Testing)
55
+
56
+ [//]: # (Our models work well on both indoor and outdoor scenarios, compared with other zero-shot metric depth estimation methods.)
57
+
58
+ [//]: # ()
59
+ [//]: # (| | Backbone | KITTI $\delta 1$ ↑ | KITTI $\delta 2$ ↑ | KITTI $\delta 3$ ↑ | KITTI AbsRel ↓ | KITTI RMSE ↓ | KITTI RMS_log ↓ | NYU $\delta 1$ ↑ | NYU $\delta 2$ ↑ | NYU $\delta 3$ ↑ | NYU AbsRel ↓ | NYU RMSE ↓ | NYU log10 ↓ |)
60
+
61
+ [//]: # (|-----------------|------------|--------------------|---------------------|--------------------|-----------------|---------------|------------------|------------------|------------------|------------------|---------------|-------------|--------------|)
62
+
63
+ [//]: # (| ZeroDepth | ResNet-18 | 0.910 | 0.980 | 0.996 | 0.057 | 4.044 | 0.083 | 0.901 | 0.961 | - | 0.100 | 0.380 | - |)
64
+
65
+ [//]: # (| PolyMax | ConvNeXt-L | - | - | - | - | - | - | 0.969 | 0.996 | 0.999 | 0.067 | 0.250 | 0.033 |)
66
+
67
+ [//]: # (| Ours | ViT-L | 0.985 | 0.995 | 0.999 | 0.052 | 2.511 | 0.074 | 0.975 | 0.994 | 0.998 | 0.063 | 0.251 | 0.028 |)
68
+
69
+ [//]: # (| Ours | ViT-g2 | 0.989 | 0.996 | 0.999 | 0.051 | 2.403 | 0.080 | 0.980 | 0.997 | 0.999 | 0.067 | 0.260 | 0.030 |)
70
+
71
+ [//]: # ()
72
+ [//]: # ([//]: # &#40;| Adabins | Efficient-B5 | 0.964 | 0.995 | 0.999 | 0.058 | 2.360 | 0.088 | 0.903 | 0.984 | 0.997 | 0.103 | 0.0444 | 0.364 |&#41;)
73
+ [//]: # ([//]: # &#40;| NewCRFs | SwinT-L | 0.974 | 0.997 | 0.999 | 0.052 | 2.129 | 0.079 | 0.922 | 0.983 | 0.994 | 0.095 | 0.041 | 0.334 |&#41;)
74
+ [//]: # ([//]: # &#40;| Ours &#40;CSTM_label&#41; | ConvNeXt-L | 0.964 | 0.993 | 0.998 | 0.058 | 2.770 | 0.092 | 0.944 | 0.986 | 0.995 | 0.083 | 0.035 | 0.310 |&#41;)
75
+
76
+ [//]: # (#### Finetuned)
77
+ Our models rank 1st on the routing KITTI and NYU benchmarks.
78
+
79
+ | | Backbone | KITTI δ1 ↑ | KITTI δ2 ↑ | KITTI AbsRel ↓ | KITTI RMSE ↓ | KITTI RMS_log ↓ | NYU δ1 ↑ | NYU δ2 ↑ | NYU AbsRel ↓ | NYU RMSE ↓ | NYU log10 ↓ |
80
+ |---------------|-------------|------------|-------------|-----------------|---------------|------------------|----------|----------|---------------|-------------|--------------|
81
+ | ZoeDepth | ViT-Large | 0.971 | 0.995 | 0.053 | 2.281 | 0.082 | 0.953 | 0.995 | 0.077 | 0.277 | 0.033 |
82
+ | ZeroDepth | ResNet-18 | 0.968 | 0.996 | 0.057 | 2.087 | 0.083 | 0.954 | 0.995 | 0.074 | 0.269 | 0.103 |
83
+ | IEBins | SwinT-Large | 0.978 | 0.998 | 0.050 | 2.011 | 0.075 | 0.936 | 0.992 | 0.087 | 0.314 | 0.031 |
84
+ | DepthAnything | ViT-Large | 0.982 | 0.998 | 0.046 | 1.985 | 0.069 | 0.984 | 0.998 | 0.056 | 0.206 | 0.024 |
85
+ | Ours | ViT-Large | 0.985 | 0.998 | 0.044 | 1.985 | 0.064 | 0.989 | 0.998 | 0.047 | 0.183 | 0.020 |
86
+ | Ours | ViT-giant2 | 0.989 | 0.998 | 0.039 | 1.766 | 0.060 | 0.987 | 0.997 | 0.045 | 0.187 | 0.015 |
87
+
88
+ ### Affine-invariant Depth
89
+ Even compared to recent affine-invariant depth methods (Marigold and Depth Anything), our metric-depth (and normal) models still show superior performance.
90
+
91
+ | | #Data for Pretrain and Train | KITTI Absrel ↓ | KITTI δ1 ↑ | NYUv2 AbsRel ↓ | NYUv2 δ1 ↑ | DIODE-Full AbsRel ↓ | DIODE-Full δ1 ↑ | Eth3d AbsRel ↓ | Eth3d δ1 ↑ |
92
+ |-----------------------|----------------------------------------------|----------------|------------|-----------------|------------|---------------------|-----------------|----------------------|------------|
93
+ | OmniData (v2, ViT-L) | 1.3M + 12.2M | 0.069 | 0.948 | 0.074 | 0.945 | 0.149 | 0.835 | 0.166 | 0.778 |
94
+ | MariGold (LDMv2) | 5B + 74K | 0.099 | 0.916 | 0.055 | 0.961 | 0.308 | 0.773 | 0.127 | 0.960 |
95
+ | DepthAnything (ViT-L) | 142M + 63M | 0.076 | 0.947 | 0.043 | 0.981 | 0.277 | 0.759 | 0.065 | 0.882 |
96
+ | Ours (ViT-L) | 142M + 16M | 0.042 | 0.979 | 0.042 | 0.980 | 0.141 | 0.882 | 0.042 | 0.987 |
97
+ | Ours (ViT-g) | 142M + 16M | 0.043 | 0.982 | 0.043 | 0.981 | 0.136 | 0.895 | 0.042 | 0.983 |
98
+
99
+
100
+ ### Surface Normal
101
+ Our models also show powerful performance on normal benchmarks.
102
+
103
+ | | NYU 11.25° ↑ | NYU Mean ↓ | NYU RMS ↓ | ScanNet 11.25° ↑ | ScanNet Mean ↓ | ScanNet RMS ↓ | iBims 11.25° ↑ | iBims Mean ↓ | iBims RMS ↓ |
104
+ |--------------|----------|----------|-----------|-----------------|----------------|--------------|---------------|--------------|-------------|
105
+ | EESNU | 0.597 | 16.0 | 24.7 | 0.711 | 11.8 | 20.3 | 0.585 | 20.0 | - |
106
+ | IronDepth | - | - | - | - | - | - | 0.431 | 25.3 | 37.4 |
107
+ | PolyMax | 0.656 | 13.1 | 20.4 | - | - | - | - | - | - |
108
+ | Ours (ViT-L) | 0.688 | 12.0 | 19.2 | 0.760 | 9.9 | 16.4 | 0.694 | 19.4 | 34.9 |
109
+ | Ours (ViT-g) | 0.662 | 13.2 | 20.2 | 0.778 | 9.2 | 15.3 | 0.697 | 19.6 | 35.2 |
110
+
111
+
112
+
113
+ ## 🌈 DEMOs
114
+
115
+ ### Zero-shot monocular metric depth & surface normal
116
+ <img src="media/gifs/demo_1.gif" width="600" height="337">
117
+ <img src="media/gifs/demo_12.gif" width="600" height="337">
118
+
119
+ ### Zero-shot metric 3D recovery
120
+ <img src="media/gifs/demo_2.gif" width="600" height="337">
121
+
122
+ ### Improving monocular SLAM
123
+ <img src="media/gifs/demo_22.gif" width="600" height="337">
124
+
125
+ [//]: # (https://github.com/YvanYin/Metric3D/assets/35299633/f95815ef-2506-4193-a6d9-1163ea821268)
126
+
127
+ [//]: # (https://github.com/YvanYin/Metric3D/assets/35299633/ed00706c-41cc-49ea-accb-ad0532633cc2)
128
+
129
+ [//]: # (### Zero-shot metric 3D recovery)
130
+
131
+ [//]: # (https://github.com/YvanYin/Metric3D/assets/35299633/26cd7ae1-dd5a-4446-b275-54c5ca7ef945)
132
+
133
+ [//]: # (https://github.com/YvanYin/Metric3D/assets/35299633/21e5484b-c304-4fe3-b1d3-8eebc4e26e42)
134
+ [//]: # (### Monocular reconstruction for a Sequence)
135
+
136
+ [//]: # ()
137
+ [//]: # (### In-the-wild 3D reconstruction)
138
+
139
+ [//]: # ()
140
+ [//]: # (| | Image | Reconstruction | Pointcloud File |)
141
+
142
+ [//]: # (|:---------:|:------------------:|:------------------:|:--------:|)
143
+
144
+ [//]: # (| room | <img src="data/wild_demo/jonathan-borba-CnthDZXCdoY-unsplash.jpg" width="300" height="335"> | <img src="media/gifs/room.gif" width="300" height="335"> | [Download]&#40;https://drive.google.com/file/d/1P1izSegH2c4LUrXGiUksw037PVb0hjZr/view?usp=drive_link&#41; |)
145
+
146
+ [//]: # (| Colosseum | <img src="data/wild_demo/david-kohler-VFRTXGw1VjU-unsplash.jpg" width="300" height="169"> | <img src="media/gifs/colo.gif" width="300" height="169"> | [Download]&#40;https://drive.google.com/file/d/1jJCXe5IpxBhHDr0TZtNZhjxKTRUz56Hg/view?usp=drive_link&#41; |)
147
+
148
+ [//]: # (| chess | <img src="data/wild_demo/randy-fath-G1yhU1Ej-9A-unsplash.jpg" width="300" height="169" align=center> | <img src="media/gifs/chess.gif" width="300" height="169"> | [Download]&#40;https://drive.google.com/file/d/1oV_Foq25_p-tTDRTcyO2AzXEdFJQz-Wm/view?usp=drive_link&#41; |)
149
+
150
+ [//]: # ()
151
+ [//]: # (All three images are downloaded from [unplash]&#40;https://unsplash.com/&#41; and put in the data/wild_demo directory.)
152
+
153
+ [//]: # ()
154
+ [//]: # (### 3D metric reconstruction, Metric3D × DroidSLAM)
155
+
156
+ [//]: # (Metric3D can also provide scale information for DroidSLAM, help to solve the scale drift problem for better trajectories. )
157
+
158
+ [//]: # ()
159
+ [//]: # (#### Bird Eyes' View &#40;Left: Droid-SLAM &#40;mono&#41;. Right: Droid-SLAM with Metric-3D&#41;)
160
+
161
+ [//]: # ()
162
+ [//]: # (<div align=center>)
163
+
164
+ [//]: # (<img src="media/gifs/0028.gif"> )
165
+
166
+ [//]: # (</div>)
167
+
168
+ [//]: # ()
169
+ [//]: # (### Front View)
170
+
171
+ [//]: # ()
172
+ [//]: # (<div align=center>)
173
+
174
+ [//]: # (<img src="media/gifs/0028_fv.gif"> )
175
+
176
+ [//]: # (</div>)
177
+
178
+ [//]: # ()
179
+ [//]: # (#### KITTI odemetry evaluation &#40;Translational RMS drift &#40;t_rel, ↓&#41; / Rotational RMS drift &#40;r_rel, ↓&#41;&#41;)
180
+
181
+ [//]: # (| | Modality | seq 00 | seq 02 | seq 05 | seq 06 | seq 08 | seq 09 | seq 10 |)
182
+
183
+ [//]: # (|:----------:|:--------:|:----------:|:----------:|:---------:|:----------:|:----------:|:---------:|:---------:|)
184
+
185
+ [//]: # (| ORB-SLAM2 | Mono | 11.43/0.58 | 10.34/0.26 | 9.04/0.26 | 14.56/0.26 | 11.46/0.28 | 9.3/0.26 | 2.57/0.32 |)
186
+
187
+ [//]: # (| Droid-SLAM | Mono | 33.9/0.29 | 34.88/0.27 | 23.4/0.27 | 17.2/0.26 | 39.6/0.31 | 21.7/0.23 | 7/0.25 |)
188
+
189
+ [//]: # (| Droid+Ours | Mono | 1.44/0.37 | 2.64/0.29 | 1.44/0.25 | 0.6/0.2 | 2.2/0.3 | 1.63/0.22 | 2.73/0.23 |)
190
+
191
+ [//]: # (| ORB-SLAM2 | Stereo | 0.88/0.31 | 0.77/0.28 | 0.62/0.26 | 0.89/0.27 | 1.03/0.31 | 0.86/0.25 | 0.62/0.29 |)
192
+
193
+ [//]: # ()
194
+ [//]: # (Metric3D makes the mono-SLAM scale-aware, like stereo systems.)
195
+
196
+ [//]: # ()
197
+ [//]: # (#### KITTI sequence videos - Youtube)
198
+
199
+ [//]: # ([2011_09_30_drive_0028]&#40;https://youtu.be/gcTB4MgVCLQ&#41; /)
200
+
201
+ [//]: # ([2011_09_30_drive_0033]&#40;https://youtu.be/He581fmoPP4&#41; /)
202
+
203
+ [//]: # ([2011_09_30_drive_0034]&#40;https://youtu.be/I3PkukQ3_F8&#41;)
204
+
205
+ [//]: # ()
206
+ [//]: # (#### Estimated pose)
207
+
208
+ [//]: # ([2011_09_30_drive_0033]&#40;https://drive.google.com/file/d/1SMXWzLYrEdmBe6uYMR9ShtDXeFDewChv/view?usp=drive_link&#41; / )
209
+
210
+ [//]: # ([2011_09_30_drive_0034]&#40;https://drive.google.com/file/d/1ONU4GxpvTlgW0TjReF1R2i-WFxbbjQPG/view?usp=drive_link&#41; /)
211
+
212
+ [//]: # ([2011_10_03_drive_0042]&#40;https://drive.google.com/file/d/19fweg6p1Q6TjJD2KlD7EMA_aV4FIeQUD/view?usp=drive_link&#41;)
213
+
214
+ [//]: # ()
215
+ [//]: # (#### Pointcloud files)
216
+
217
+ [//]: # ([2011_09_30_drive_0033]&#40;https://drive.google.com/file/d/1K0o8DpUmLf-f_rue0OX1VaHlldpHBAfw/view?usp=drive_link&#41; /)
218
+
219
+ [//]: # ([2011_09_30_drive_0034]&#40;https://drive.google.com/file/d/1bvZ6JwMRyvi07H7Z2VD_0NX1Im8qraZo/view?usp=drive_link&#41; /)
220
+
221
+ [//]: # ([2011_10_03_drive_0042]&#40;https://drive.google.com/file/d/1Vw59F8nN5ApWdLeGKXvYgyS9SNKHKy4x/view?usp=drive_link&#41;)
222
+
223
+ ## 🔨 Installation
224
+ ### One-line Installation
225
+ For the ViT models, use the following environment:
226
+ ```bash
227
+ pip install -r requirements_v2.txt
228
+ ```
229
+
230
+ For ConvNeXt-L, it is
231
+ ```bash
232
+ pip install -r requirements_v1.txt
233
+ ```
234
+
235
+ ### dataset annotation components
236
+ With off-the-shelf depth datasets, we need to generate json annotaions in compatible with this dataset, which is organized by:
237
+ ```
238
+ dict(
239
+ 'files':list(
240
+ dict(
241
+ 'rgb': 'data/kitti_demo/rgb/xxx.png',
242
+ 'depth': 'data/kitti_demo/depth/xxx.png',
243
+ 'depth_scale': 1000.0 # the depth scale of gt depth img.
244
+ 'cam_in': [fx, fy, cx, cy],
245
+ ),
246
+
247
+ dict(
248
+ ...
249
+ ),
250
+
251
+ ...
252
+ )
253
+ )
254
+ ```
255
+ To generate such annotations, please refer to the "Inference" section.
256
+
257
+ ### configs
258
+ In ```mono/configs``` we provide different config setups.
259
+
260
+ Intrinsics of the canonical camera is set bellow:
261
+ ```
262
+ canonical_space = dict(
263
+ img_size=(512, 960),
264
+ focal_length=1000.0,
265
+ ),
266
+ ```
267
+ where cx and cy is set to be half of the image size.
268
+
269
+ Inference settings are defined as
270
+ ```
271
+ depth_range=(0, 1),
272
+ depth_normalize=(0.3, 150),
273
+ crop_size = (512, 1088),
274
+ ```
275
+ where the images will be first resized as the ```crop_size``` and then fed into the model.
276
+
277
+ ## ✈️ Training
278
+ Please refer to [training/README.md](./training/README.md).
279
+ Now we provide complete json files for KITTI fine-tuning.
280
+
281
+ ## ✈️ Inference
282
+ ### News: Improved ONNX support with dynamic shapes (Feature owned by [@xenova](https://github.com/xenova). Appreciate for this outstanding contribution 🚩🚩🚩)
283
+
284
+ Now the onnx supports are availble for all three models with varying shapes. Refer to [issue117](https://github.com/YvanYin/Metric3D/issues/117) for more details.
285
+
286
+ ### Improved ONNX Checkpoints Available now
287
+ | | Encoder | Decoder | Link |
288
+ |:----:|:-------------------:|:-----------------:|:-------------------------------------------------------------------------------------------------:|
289
+ | v2-S-ONNX | DINO2reg-ViT-Small | RAFT-4iter | [Download 🤗](https://huggingface.co/onnx-community/metric3d-vit-small) |
290
+ | v2-L-ONNX | DINO2reg-ViT-Large | RAFT-8iter | [Download 🤗](https://huggingface.co/onnx-community/metric3d-vit-large) |
291
+ | v2-g-ONNX | DINO2reg-ViT-giant2 | RAFT-8iter | [Download 🤗](https://huggingface.co/onnx-community/metric3d-vit-giant2) |
292
+
293
+ One additional [reminder](https://github.com/YvanYin/Metric3D/issues/143#issue-2444506808) for using these onnx models is reported by @norbertlink.
294
+
295
+ ### News: Pytorch Hub is supported
296
+ Now you can use Metric3D via Pytorch Hub with just few lines of code:
297
+ ```python
298
+ import torch
299
+ model = torch.hub.load('yvanyin/metric3d', 'metric3d_vit_small', pretrain=True)
300
+ pred_depth, confidence, output_dict = model.inference({'input': rgb})
301
+ pred_normal = output_dict['prediction_normal'][:, :3, :, :] # only available for Metric3Dv2 i.e., ViT models
302
+ normal_confidence = output_dict['prediction_normal'][:, 3, :, :] # see https://arxiv.org/abs/2109.09881 for details
303
+ ```
304
+ Supported models: `metric3d_convnext_tiny`, `metric3d_convnext_large`, `metric3d_vit_small`, `metric3d_vit_large`, `metric3d_vit_giant2`.
305
+
306
+ We also provided a minimal working example in [hubconf.py](https://github.com/YvanYin/Metric3D/blob/main/hubconf.py#L145), which hopefully makes everything clearer.
307
+
308
+ ### News: ONNX Exportation and Inference are supported
309
+
310
+ We also provided a flexible working example in [metric3d_onnx_export.py](./onnx/metric3d_onnx_export.py) to export the Pytorch Hub model to ONNX format. We could test with the following commands:
311
+
312
+ ```bash
313
+ # Export the model to ONNX model
314
+ python3 onnx/metric_3d_onnx_export.py metric3d_vit_small # metric3d_vit_large/metric3d_convnext_large
315
+
316
+ # Test the inference of the ONNX model
317
+ python3 onnx/test_onnx.py metric3d_vit_small.onnx
318
+ ```
319
+
320
+ [ros2_vision_inference](https://github.com/Owen-Liuyuxuan/ros2_vision_inference) provides a Python example, showcasing a pipeline from image to point clouds and integrated into ROS2 systems.
321
+
322
+ ### Download Checkpoint
323
+ | | Encoder | Decoder | Link |
324
+ |:----:|:-------------------:|:-----------------:|:-------------------------------------------------------------------------------------------------:|
325
+ | v1-T | ConvNeXt-Tiny | Hourglass-Decoder | [Download 🤗](https://huggingface.co/JUGGHM/Metric3D/blob/main/convtiny_hourglass_v1.pth) |
326
+ | v1-L | ConvNeXt-Large | Hourglass-Decoder | [Download](https://drive.google.com/file/d/1KVINiBkVpJylx_6z1lAC7CQ4kmn-RJRN/view?usp=drive_link) |
327
+ | v2-S | DINO2reg-ViT-Small | RAFT-4iter | [Download](https://drive.google.com/file/d/1YfmvXwpWmhLg3jSxnhT7LvY0yawlXcr_/view?usp=drive_link) |
328
+ | v2-L | DINO2reg-ViT-Large | RAFT-8iter | [Download](https://drive.google.com/file/d/1eT2gG-kwsVzNy5nJrbm4KC-9DbNKyLnr/view?usp=drive_link) |
329
+ | v2-g | DINO2reg-ViT-giant2 | RAFT-8iter | [Download 🤗](https://huggingface.co/JUGGHM/Metric3D/blob/main/metric_depth_vit_giant2_800k.pth) |
330
+
331
+ ### Dataset Mode
332
+ 1. put the trained ckpt file ```model.pth``` in ```weight/```.
333
+ 2. generate data annotation by following the code ```data/gene_annos_kitti_demo.py```, which includes 'rgb', (optional) 'intrinsic', (optional) 'depth', (optional) 'depth_scale'.
334
+ 3. change the 'test_data_path' in ```test_*.sh``` to the ```*.json``` path.
335
+ 4. run ```source test_kitti.sh``` or ```source test_nyu.sh```.
336
+
337
+ ### In-the-Wild Mode
338
+ 1. put the trained ckpt file ```model.pth``` in ```weight/```.
339
+ 2. change the 'test_data_path' in ```test.sh``` to the image folder path.
340
+ 3. run ```source test_vit.sh``` for transformers and ```source test.sh``` for convnets.
341
+ As no intrinsics are provided, we provided by default 9 settings of focal length.
342
+
343
+ ### Metric3D and Droid-Slam
344
+ If you are interested in combining metric3D and monocular visual slam system to achieve the metric slam, you can refer to this [repo](https://github.com/Jianxff/droid_metric).
345
+
346
+ ## ❓ Q & A
347
+ ### Q1: Why depth maps look good but pointclouds are distorted?
348
+ Because the focal length is not properly set! Please find a proper focal length by modifying codes [here](mono/utils/do_test.py#309) yourself.
349
+
350
+ ### Q2: Why the point clouds are too slow to be generated?
351
+ Because the images are too large! Use smaller ones instead.
352
+
353
+ ### Q3: Why predicted depth maps are not satisfactory?
354
+ First be sure all black padding regions at image boundaries are cropped out. Then please try again.
355
+ Besides, metric 3D is not almighty. Some objects (chandeliers, drones...) / camera views (aerial view, bev...) do not occur frequently in the training datasets. We will going deeper into this and release more powerful solutions.
356
+
357
+ ## 📧 Citation
358
+ If you use this toolbox in your research or wish to refer to the baseline results published here, please use the following BibTeX entries:
359
+ ```
360
+ @misc{Metric3D,
361
+ author = {Yin, Wei and Hu, Mu},
362
+ title = {OpenMetric3D: An Open Toolbox for Monocular Depth Estimation},
363
+ howpublished = {\url{https://github.com/YvanYin/Metric3D}},
364
+ year = {2024}
365
+ }
366
+ ```
367
+ <!-- ```
368
+ @article{hu2024metric3dv2,
369
+ title={Metric3D v2: A Versatile Monocular Geometric Foundation Model for Zero-shot Metric Depth and Surface Normal Estimation},
370
+ author={Hu, Mu and Yin, Wei and Zhang, Chi and Cai, Zhipeng and Long, Xiaoxiao and Chen, Hao and Wang, Kaixuan and Yu, Gang and Shen, Chunhua and Shen, Shaojie},
371
+ journal={arXiv preprint arXiv:2404.15506},
372
+ year={2024}
373
+ }
374
+ ``` -->
375
+ Also please cite our papers if this help your research.
376
+ ```
377
+ @article{hu2024metric3dv2,
378
+ title={Metric3d v2: A versatile monocular geometric foundation model for zero-shot metric depth and surface normal estimation},
379
+ author={Hu, Mu and Yin, Wei and Zhang, Chi and Cai, Zhipeng and Long, Xiaoxiao and Chen, Hao and Wang, Kaixuan and Yu, Gang and Shen, Chunhua and Shen, Shaojie},
380
+ journal={IEEE Transactions on Pattern Analysis and Machine Intelligence},
381
+ year={2024},
382
+ publisher={IEEE}
383
+ }
384
+ ```
385
+ ```
386
+ @article{yin2023metric,
387
+ title={Metric3D: Towards Zero-shot Metric 3D Prediction from A Single Image},
388
+ author={Wei Yin, Chi Zhang, Hao Chen, Zhipeng Cai, Gang Yu, Kaixuan Wang, Xiaozhi Chen, Chunhua Shen},
389
+ booktitle={ICCV},
390
+ year={2023}
391
+ }
392
+ ```
393
+
394
+ ## License and Contact
395
+
396
+ The *Metric 3D* code is under a 2-clause BSD License. For further commercial inquiries, please contact Dr. Wei Yin [yvanwy@outlook.com] and Mr. Mu Hu [mhuam@connect.ust.hk].
external/Metric3D/hubconf.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ dependencies = ['torch', 'torchvision']
2
+
3
+ import os
4
+ import torch
5
+ try:
6
+ from mmcv.utils import Config, DictAction
7
+ except:
8
+ from mmengine import Config, DictAction
9
+
10
+ from mono.model.monodepth_model import get_configured_monodepth_model
11
+ metric3d_dir = os.path.dirname(__file__)
12
+
13
+ MODEL_TYPE = {
14
+ 'ConvNeXt-Tiny': {
15
+ 'cfg_file': f'{metric3d_dir}/mono/configs/HourglassDecoder/convtiny.0.3_150.py',
16
+ 'ckpt_file': 'https://huggingface.co/JUGGHM/Metric3D/resolve/main/convtiny_hourglass_v1.pth',
17
+ },
18
+ 'ConvNeXt-Large': {
19
+ 'cfg_file': f'{metric3d_dir}/mono/configs/HourglassDecoder/convlarge.0.3_150.py',
20
+ 'ckpt_file': 'https://huggingface.co/JUGGHM/Metric3D/resolve/main/convlarge_hourglass_0.3_150_step750k_v1.1.pth',
21
+ },
22
+ 'ViT-Small': {
23
+ 'cfg_file': f'{metric3d_dir}/mono/configs/HourglassDecoder/vit.raft5.small.py',
24
+ 'ckpt_file': 'https://huggingface.co/JUGGHM/Metric3D/resolve/main/metric_depth_vit_small_800k.pth',
25
+ },
26
+ 'ViT-Large': {
27
+ 'cfg_file': f'{metric3d_dir}/mono/configs/HourglassDecoder/vit.raft5.large.py',
28
+ 'ckpt_file': 'https://huggingface.co/JUGGHM/Metric3D/resolve/main/metric_depth_vit_large_800k.pth',
29
+ },
30
+ 'ViT-giant2': {
31
+ 'cfg_file': f'{metric3d_dir}/mono/configs/HourglassDecoder/vit.raft5.giant2.py',
32
+ 'ckpt_file': 'https://huggingface.co/JUGGHM/Metric3D/resolve/main/metric_depth_vit_giant2_800k.pth',
33
+ },
34
+ }
35
+
36
+
37
+
38
+ def metric3d_convnext_tiny(pretrain=False, **kwargs):
39
+ '''
40
+ Return a Metric3D model with ConvNeXt-Large backbone and Hourglass-Decoder head.
41
+ For usage examples, refer to: https://github.com/YvanYin/Metric3D/blob/main/hubconf.py
42
+ Args:
43
+ pretrain (bool): whether to load pretrained weights.
44
+ Returns:
45
+ model (nn.Module): a Metric3D model.
46
+ '''
47
+ cfg_file = MODEL_TYPE['ConvNeXt-Tiny']['cfg_file']
48
+ ckpt_file = MODEL_TYPE['ConvNeXt-Tiny']['ckpt_file']
49
+
50
+ cfg = Config.fromfile(cfg_file)
51
+ model = get_configured_monodepth_model(cfg)
52
+ if pretrain:
53
+ model.load_state_dict(
54
+ torch.hub.load_state_dict_from_url(ckpt_file)['model_state_dict'],
55
+ strict=False,
56
+ )
57
+ return model
58
+
59
+ def metric3d_convnext_large(pretrain=False, **kwargs):
60
+ '''
61
+ Return a Metric3D model with ConvNeXt-Large backbone and Hourglass-Decoder head.
62
+ For usage examples, refer to: https://github.com/YvanYin/Metric3D/blob/main/hubconf.py
63
+ Args:
64
+ pretrain (bool): whether to load pretrained weights.
65
+ Returns:
66
+ model (nn.Module): a Metric3D model.
67
+ '''
68
+ cfg_file = MODEL_TYPE['ConvNeXt-Large']['cfg_file']
69
+ ckpt_file = MODEL_TYPE['ConvNeXt-Large']['ckpt_file']
70
+
71
+ cfg = Config.fromfile(cfg_file)
72
+ model = get_configured_monodepth_model(cfg)
73
+ if pretrain:
74
+ model.load_state_dict(
75
+ torch.hub.load_state_dict_from_url(ckpt_file)['model_state_dict'],
76
+ strict=False,
77
+ )
78
+ return model
79
+
80
+ def metric3d_vit_small(pretrain=False, **kwargs):
81
+ '''
82
+ Return a Metric3D model with ViT-Small backbone and RAFT-4iter head.
83
+ For usage examples, refer to: https://github.com/YvanYin/Metric3D/blob/main/hubconf.py
84
+ Args:
85
+ pretrain (bool): whether to load pretrained weights.
86
+ Returns:
87
+ model (nn.Module): a Metric3D model.
88
+ '''
89
+ cfg_file = MODEL_TYPE['ViT-Small']['cfg_file']
90
+ ckpt_file = MODEL_TYPE['ViT-Small']['ckpt_file']
91
+
92
+ cfg = Config.fromfile(cfg_file)
93
+ model = get_configured_monodepth_model(cfg)
94
+ if pretrain:
95
+ model.load_state_dict(
96
+ torch.hub.load_state_dict_from_url(ckpt_file)['model_state_dict'],
97
+ strict=False,
98
+ )
99
+ return model
100
+
101
+ def metric3d_vit_large(pretrain=False, **kwargs):
102
+ '''
103
+ Return a Metric3D model with ViT-Large backbone and RAFT-8iter head.
104
+ For usage examples, refer to: https://github.com/YvanYin/Metric3D/blob/main/hubconf.py
105
+ Args:
106
+ pretrain (bool): whether to load pretrained weights.
107
+ Returns:
108
+ model (nn.Module): a Metric3D model.
109
+ '''
110
+ cfg_file = MODEL_TYPE['ViT-Large']['cfg_file']
111
+ ckpt_file = MODEL_TYPE['ViT-Large']['ckpt_file']
112
+
113
+ cfg = Config.fromfile(cfg_file)
114
+ model = get_configured_monodepth_model(cfg)
115
+ if pretrain:
116
+ model.load_state_dict(
117
+ torch.hub.load_state_dict_from_url(ckpt_file)['model_state_dict'],
118
+ strict=False,
119
+ )
120
+ return model
121
+
122
+ def metric3d_vit_giant2(pretrain=False, **kwargs):
123
+ '''
124
+ Return a Metric3D model with ViT-Giant2 backbone and RAFT-8iter head.
125
+ For usage examples, refer to: https://github.com/YvanYin/Metric3D/blob/main/hubconf.py
126
+ Args:
127
+ pretrain (bool): whether to load pretrained weights.
128
+ Returns:
129
+ model (nn.Module): a Metric3D model.
130
+ '''
131
+ cfg_file = MODEL_TYPE['ViT-giant2']['cfg_file']
132
+ ckpt_file = MODEL_TYPE['ViT-giant2']['ckpt_file']
133
+ print("ckpt_file", ckpt_file)
134
+ cfg = Config.fromfile(cfg_file)
135
+ model = get_configured_monodepth_model(cfg)
136
+ if pretrain:
137
+ # model.load_state_dict(
138
+ # torch.hub.load_state_dict_from_url(ckpt_file)['model_state_dict'],
139
+ # strict=False,
140
+ # )
141
+ ckpt_path = "/mnt/prev_nas/qhy_1/GenSpace/osdsynth/external/Metric3D/weight/metric_depth_vit_giant2_800k.pth"
142
+ state_dict = torch.load(ckpt_path, map_location="cpu")['model_state_dict']
143
+ model.load_state_dict(state_dict, strict=False,)
144
+ return model
145
+
146
+
147
+
148
+ if __name__ == '__main__':
149
+ import cv2
150
+ import numpy as np
151
+ #### prepare data
152
+ rgb_file = 'data/kitti_demo/rgb/0000000050.png'
153
+ depth_file = 'data/kitti_demo/depth/0000000050.png'
154
+ intrinsic = [707.0493, 707.0493, 604.0814, 180.5066]
155
+ gt_depth_scale = 256.0
156
+ rgb_origin = cv2.imread(rgb_file)[:, :, ::-1]
157
+
158
+ #### ajust input size to fit pretrained model
159
+ # keep ratio resize
160
+ input_size = (616, 1064) # for vit model
161
+ # input_size = (544, 1216) # for convnext model
162
+ h, w = rgb_origin.shape[:2]
163
+ scale = min(input_size[0] / h, input_size[1] / w)
164
+ rgb = cv2.resize(rgb_origin, (int(w * scale), int(h * scale)), interpolation=cv2.INTER_LINEAR)
165
+ # remember to scale intrinsic, hold depth
166
+ intrinsic = [intrinsic[0] * scale, intrinsic[1] * scale, intrinsic[2] * scale, intrinsic[3] * scale]
167
+ # padding to input_size
168
+ padding = [123.675, 116.28, 103.53]
169
+ h, w = rgb.shape[:2]
170
+ pad_h = input_size[0] - h
171
+ pad_w = input_size[1] - w
172
+ pad_h_half = pad_h // 2
173
+ pad_w_half = pad_w // 2
174
+ rgb = cv2.copyMakeBorder(rgb, pad_h_half, pad_h - pad_h_half, pad_w_half, pad_w - pad_w_half, cv2.BORDER_CONSTANT, value=padding)
175
+ pad_info = [pad_h_half, pad_h - pad_h_half, pad_w_half, pad_w - pad_w_half]
176
+
177
+ #### normalize
178
+ mean = torch.tensor([123.675, 116.28, 103.53]).float()[:, None, None]
179
+ std = torch.tensor([58.395, 57.12, 57.375]).float()[:, None, None]
180
+ rgb = torch.from_numpy(rgb.transpose((2, 0, 1))).float()
181
+ rgb = torch.div((rgb - mean), std)
182
+ rgb = rgb[None, :, :, :].cuda()
183
+
184
+ ###################### canonical camera space ######################
185
+ # inference
186
+ model = torch.hub.load('yvanyin/metric3d', 'metric3d_vit_small', pretrain=True)
187
+ model.cuda().eval()
188
+ with torch.no_grad():
189
+ pred_depth, confidence, output_dict = model.inference({'input': rgb})
190
+
191
+ # un pad
192
+ pred_depth = pred_depth.squeeze()
193
+ pred_depth = pred_depth[pad_info[0] : pred_depth.shape[0] - pad_info[1], pad_info[2] : pred_depth.shape[1] - pad_info[3]]
194
+
195
+ # upsample to original size
196
+ pred_depth = torch.nn.functional.interpolate(pred_depth[None, None, :, :], rgb_origin.shape[:2], mode='bilinear').squeeze()
197
+ ###################### canonical camera space ######################
198
+
199
+ #### de-canonical transform
200
+ canonical_to_real_scale = intrinsic[0] / 1000.0 # 1000.0 is the focal length of canonical camera
201
+ pred_depth = pred_depth * canonical_to_real_scale # now the depth is metric
202
+ pred_depth = torch.clamp(pred_depth, 0, 300)
203
+
204
+ #### you can now do anything with the metric depth
205
+ # such as evaluate predicted depth
206
+ if depth_file is not None:
207
+ gt_depth = cv2.imread(depth_file, -1)
208
+ gt_depth = gt_depth / gt_depth_scale
209
+ gt_depth = torch.from_numpy(gt_depth).float().cuda()
210
+ assert gt_depth.shape == pred_depth.shape
211
+
212
+ mask = (gt_depth > 1e-8)
213
+ abs_rel_err = (torch.abs(pred_depth[mask] - gt_depth[mask]) / gt_depth[mask]).mean()
214
+ print('abs_rel_err:', abs_rel_err.item())
215
+
216
+ #### normal are also available
217
+ if 'prediction_normal' in output_dict: # only available for Metric3Dv2, i.e. vit model
218
+ pred_normal = output_dict['prediction_normal'][:, :3, :, :]
219
+ normal_confidence = output_dict['prediction_normal'][:, 3, :, :] # see https://arxiv.org/abs/2109.09881 for details
220
+ # un pad and resize to some size if needed
221
+ pred_normal = pred_normal.squeeze()
222
+ pred_normal = pred_normal[:, pad_info[0] : pred_normal.shape[1] - pad_info[1], pad_info[2] : pred_normal.shape[2] - pad_info[3]]
223
+ # you can now do anything with the normal
224
+ # such as visualize pred_normal
225
+ pred_normal_vis = pred_normal.cpu().numpy().transpose((1, 2, 0))
226
+ pred_normal_vis = (pred_normal_vis + 1) / 2
227
+ cv2.imwrite('normal_vis.png', (pred_normal_vis * 255).astype(np.uint8))
external/Metric3D/requirements_v1.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ torchvision
3
+ opencv-python
4
+ numpy
5
+ Pillow
6
+ DateTime
7
+ matplotlib
8
+ plyfile
9
+ HTML4Vision
10
+ timm
11
+ tensorboardX
12
+ imgaug
13
+ iopath
14
+ imagecorruptions
15
+ mmcv
external/Metric3D/requirements_v2.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch == 2.0.1
2
+ torchvision == 0.15.2
3
+ opencv-python
4
+ numpy == 1.23.1
5
+ xformers == 0.0.21
6
+ Pillow
7
+ DateTime
8
+ matplotlib
9
+ plyfile
10
+ HTML4Vision
11
+ timm
12
+ tensorboardX
13
+ imgaug
14
+ iopath
15
+ imagecorruptions
16
+ mmcv
external/Metric3D/test.sh ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ConvNeXt Large
2
+ python mono/tools/test_scale_cano.py \
3
+ 'mono/configs/HourglassDecoder/convlarge.0.3_150.py' \
4
+ --load-from ./weight/convlarge_hourglass_0.3_150_step750k_v1.1.pth \
5
+ --test_data_path ./data/wild_demo \
6
+ --launcher None \
7
+ --batch_size 2
8
+
9
+ # ConvNeXt Tiny, note: only trained on outdoor data, perform better in outdoor scenes, such as kitti
10
+ python mono/tools/test_scale_cano.py \
11
+ 'mono/configs/HourglassDecoder/convtiny.0.3_150.py' \
12
+ --load-from ./weight/convtiny_hourglass_v1.pth \
13
+ --test_data_path ./data/wild_demo \
14
+ --launcher None \
15
+ --batch_size 2
external/Metric3D/test_kitti.sh ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ python mono/tools/test_scale_cano.py \
2
+ 'mono/configs/HourglassDecoder/test_kitti_convlarge_hourglass_0.3_150.py' \
3
+ --load-from ./weight/convlarge_hourglass_0.3_150_step750k_v1.1.pth \
4
+ --test_data_path ./data/kitti_demo/test_annotations.json \
5
+ --launcher None
external/Metric3D/test_nyu.sh ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ python mono/tools/test_scale_cano.py \
2
+ 'mono/configs/HourglassDecoder/test_nyu_convlarge.0.3_150.py' \
3
+ --load-from ./weight/convlarge_hourglass_0.3_150_step750k_v1.1.pth \
4
+ --test_data_path ./data/nyu_demo/test_annotations.json \
5
+ --launcher None
external/Metric3D/test_vit.sh ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ python mono/tools/test_scale_cano.py \
2
+ 'mono/configs/HourglassDecoder/vit.raft5.small.py' \
3
+ --load-from ./weight/metric_depth_vit_small_800k.pth \
4
+ --test_data_path ./data/wild_demo \
5
+ --launcher None
external/WildCamera/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
external/WildCamera/README.md ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## WildCamera
2
+ This repository contains the code for the paper: **[Tame a Wild Camera: In-the-Wild Monocular Camera Calibration](https://arxiv.org/abs/2306.10988)** in NeurIPS 2023.
3
+ <br>
4
+ Authors: [Shengjie Zhu](https://shngjz.github.io/), [Abhinav Kumar](https://sites.google.com/view/abhinavkumar), [Masa Hu](https://scholar.google.com/citations?user=Xs-NkFMAAAAJ&hl=en), and [Xiaoming Liu](https://www.cse.msu.edu/~liuxm/index2.html)
5
+ <br>
6
+ [[arXiv preprint]](https://arxiv.org/abs/2306.10988) [[Prject Page]](https://shngjz.github.io/WildCamera.github.io/) [[Poster]](https://drive.google.com/file/d/1y8v0jBd6MFtP8urHNBCzh0wsK43djIj0/view?usp=sharing)
7
+
8
+ ## Applications and Qualitative Results
9
+ - 4 DoF Camera Calibration (Zero-Shot)
10
+ <details>
11
+
12
+ - Camera Calibration:
13
+
14
+ https://github.com/ShngJZ/WildCamera/assets/128062217/748cf660-aebd-4a86-8d94-2be28650853b
15
+
16
+ - DollyZoom-Demo1:
17
+
18
+ https://github.com/ShngJZ/WildCamera/assets/128062217/15b18902-9c18-460d-8b5e-7d728cbd63c0
19
+
20
+
21
+ - DollyZoom-Demo2:
22
+
23
+ https://github.com/ShngJZ/WildCamera/assets/128062217/5722039d-d0c0-49db-a7a1-c83c5e69f7fd
24
+
25
+ - DollyZoom-Demo3:
26
+
27
+ https://github.com/ShngJZ/WildCamera/assets/128062217/ef352b58-3e30-4b00-add8-6db5ae1d5de0
28
+
29
+ - Image Crop and Resize Detection and Restoration (Zero-Shot)
30
+ <details>
31
+
32
+ https://github.com/ShngJZ/WildCamera/assets/128062217/c390588f-63e2-4611-b546-b86946f3caf9
33
+
34
+ - In-the-Wild Monocular 3D Object Detection ([Omni3d](https://github.com/facebookresearch/omni3d))
35
+ <details>
36
+
37
+ https://github.com/ShngJZ/WildCamera/assets/128062217/d776e3d0-11c3-48c2-9a1b-e5adc10408ba
38
+
39
+ ## Brief Introduction
40
+ <img src="asset/framework.png" width="1000" >
41
+ We calibrate 4 DoF intrinsic for in-the-wild images.
42
+ The work systematically presents the connection between intrinsic and monocular 3D priors, e.g. intrinsic is inferrable from monocular depth and surface normals.
43
+ We additionally introduce an alternative monocular 3D prior, the incidence field, for calibration.
44
+
45
+ ## Data Preparation
46
+ Pretrained models and data are held in [Hugging Face](https://huggingface.co/datasets/Shengjie/WildCamera/tree/main).
47
+ ```
48
+ WildCamera
49
+ ├── model_zoo
50
+ │ ├── Release
51
+ │ │ ├── wild_camera_all.pth
52
+ │ │ ├── wild_camera_gsv.pth
53
+ │ ├── swin_transformer
54
+ │ │ ├── swin_large_patch4_window7_224_22k.pth
55
+ ├── data
56
+ │ ├── MonoCalib
57
+ │ │ ├── ARKitScenes
58
+ │ │ ├── BIWIRGBDID
59
+ │ │ ├── CAD120
60
+ │ │ ├── ...
61
+ │ │ ├── Waymo
62
+ │ ├── UncalibTwoViewPoseEvaluation
63
+ │ │ ├── megadepth_test_1500
64
+ │ │ ├── scannet_test_1500
65
+ ```
66
+ Use the script to download data in your preferred location.
67
+ Entire dataset takes around 150 GB disk space.
68
+ ```bash
69
+ mkdir model_zoo
70
+ ./asset/download_wildcamera_checkpoint.sh
71
+ ln -s your-data-location data
72
+ ./asset/download_wildcamera_dataset.sh
73
+ ```
74
+
75
+ ## Installation
76
+ ```bash
77
+ conda create -n wildacamera
78
+ conda activate wildacamera
79
+ conda install pytorch==1.13.0 torchvision==0.14.0 torchaudio==0.13.0 pytorch-cuda=11.6 -c pytorch -c nvidia
80
+ pip install mmcv==2.0.0 -f https://download.openmmlab.com/mmcv/dist/cu116/torch1.13/index.html
81
+ pip install timm tensorboard loguru einops natsort h5py tabulate
82
+ ```
83
+ You can choose difference pytorch and cuda version, however, need to follow this [link](https://mmcv.readthedocs.io/en/latest/get_started/installation.html) in selecting corresponded mmcv version.
84
+
85
+
86
+
87
+ ## Demo
88
+ ``` bash
89
+ # Download demo images
90
+ sh asset/download_demo_images.sh
91
+
92
+ # Estimate intrinsic over images collected from github
93
+ python demo/demo_inference.py
94
+
95
+ # Demo inference on dolly zoom videos
96
+ python demo/demo_dollyzoom.py
97
+
98
+ # Demo image restoration
99
+ python demo/demo_restoration.py
100
+ ```
101
+
102
+ ## Usage
103
+ 1. Use torch.hub to load the model (in-the-wild experiment checkpoint):
104
+ ``` bash
105
+ model = torch.hub.load('ShngJZ/WildCamera', "WildCamera", pretrained=True)
106
+ ```
107
+ 2. Calibrate intrinsic and restore image (if needed):
108
+ ``` bash
109
+ import PIL.Image as Image
110
+ rgb = Image.open(path-to-image)
111
+
112
+ # 4 DoF intrinsic
113
+ intrinsic, _ = model.inference(rgb, wtassumption=False)
114
+ # 1 DoF intrinsic
115
+ intrinsic, _ = model.inference(rgb, wtassumption=True)
116
+
117
+ # If need to restore image
118
+ rgb_restored = model.restore_image(rgb, intrinsic, fixcrop=True)
119
+ ```
120
+
121
+ ## Benchmark
122
+ ``` bash
123
+ # Benchmark Tab.2 and Tab.4
124
+ python WildCamera/benchmark/benchmark_calibration.py --experiment_name in_the_wild
125
+
126
+ # Benchmark Tab.3
127
+ python WildCamera/benchmark/benchmark_calibration.py --experiment_name gsv
128
+
129
+ # Benchmark Tab.5
130
+ python WildCamera/benchmark/benchmark_crop.py
131
+
132
+ # Benchmark Tab.6
133
+ python WildCamera/benchmark/benchmark_uncalibtwoview_megadepth.py
134
+ python WildCamera/benchmark/benchmark_uncalibtwoview_scannet.py
135
+ ```
136
+ ## Training
137
+ ``` bash
138
+ # In-the-Wild Experiment
139
+ CUDA_VISIBLE_DEVICES=0,1 python WildCamera/train/train_calibrator.py \
140
+ --experiment_name calbr_in_the_wild \
141
+ --experiment_set in_the_wild \
142
+ --steps_per_epoch 2500
143
+
144
+ # GSV Experiment
145
+ CUDA_VISIBLE_DEVICES=0,1 python WildCamera/train/train_calibrator.py \
146
+ --experiment_name calbr_gsv \
147
+ --experiment_set gsv
148
+ ```
149
+
150
+ ## Citation <a name="citing"></a>
151
+
152
+ Please use the following BibTeX to cite our work.
153
+
154
+ ```BibTeX
155
+ @inproceedings{zhu2023tame,
156
+ author = {Shengjie Zhu and Abhinav Kumar and Masa Hu and Xiaoming Liu},
157
+ title = {Tame a Wild Camera: In-the-Wild Monocular Camera Calibration},
158
+ booktitle = {NeurIPS},
159
+ year = {2023},
160
+ }
161
+ ```
162
+
163
+
164
+ If you use the Tame-a-Wild-Camera benchmark, we kindly ask you to additionally cite all datasets. BibTex entries are provided below.
165
+
166
+ <details><summary>Dataset BibTex</summary>
167
+
168
+ ```BibTex
169
+ @inproceedings{
170
+ dehghan2021arkitscenes,
171
+ title={{ARK}itScenes - A Diverse Real-World Dataset for 3D Indoor Scene Understanding Using Mobile {RGB}-D Data},
172
+ author={Gilad Baruch and Zhuoyuan Chen and Afshin Dehghan and Tal Dimry and Yuri Feigin and Peter Fu and Thomas Gebauer and Brandon Joffe and Daniel Kurz and Arik Schwartz and Elad Shulman},
173
+ booktitle={Thirty-fifth Conference on Neural Information Processing Systems Datasets and Benchmarks Track (Round 1)},
174
+ year={2021},
175
+ url={https://openreview.net/forum?id=tjZjv_qh_CE}
176
+ }
177
+ ```
178
+ ```BibTex
179
+ @inproceedings{cordts2016cityscapes,
180
+ title={The cityscapes dataset for semantic urban scene understanding},
181
+ author={Cordts, Marius and Omran, Mohamed and Ramos, Sebastian and Rehfeld, Timo and Enzweiler, Markus and Benenson, Rodrigo and Franke, Uwe and Roth, Stefan and Schiele, Bernt},
182
+ booktitle={Proceedings of the IEEE conference on computer vision and pattern recognition},
183
+ pages={3213--3223},
184
+ year={2016}
185
+ }
186
+ ```
187
+ ```BibTex
188
+ @inproceedings{geiger2012we,
189
+ title={Are we ready for autonomous driving? the kitti vision benchmark suite},
190
+ author={Geiger, Andreas and Lenz, Philip and Urtasun, Raquel},
191
+ booktitle={2012 IEEE conference on computer vision and pattern recognition},
192
+ pages={3354--3361},
193
+ year={2012},
194
+ organization={IEEE}
195
+ }
196
+ ```
197
+ ```BibTex
198
+ @inproceedings{li2018megadepth,
199
+ title={Megadepth: Learning single-view depth prediction from internet photos},
200
+ author={Li, Zhengqi and Snavely, Noah},
201
+ booktitle={Proceedings of the IEEE conference on computer vision and pattern recognition},
202
+ pages={2041--2050},
203
+ year={2018}
204
+ }
205
+ ```
206
+ ```BibTex
207
+ @inproceedings{yu2023mvimgnet,
208
+ title={Mvimgnet: A large-scale dataset of multi-view images},
209
+ author={Yu, Xianggang and Xu, Mutian and Zhang, Yidan and Liu, Haolin and Ye, Chongjie and Wu, Yushuang and Yan, Zizheng and Zhu, Chenming and Xiong, Zhangyang and Liang, Tianyou and others},
210
+ booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition},
211
+ pages={9150--9161},
212
+ year={2023}
213
+ }
214
+ ```
215
+ ```BibTex
216
+ @article{fuhrmann2014mve,
217
+ title={Mve-a multi-view reconstruction environment.},
218
+ author={Fuhrmann, Simon and Langguth, Fabian and Goesele, Michael},
219
+ journal={GCH},
220
+ volume={3},
221
+ pages={4},
222
+ year={2014}
223
+ }
224
+ ```
225
+ ```BibTex
226
+ @inproceedings{caesar2020nuscenes,
227
+ title={nuscenes: A multimodal dataset for autonomous driving},
228
+ author={Caesar, Holger and Bankiti, Varun and Lang, Alex H and Vora, Sourabh and Liong, Venice Erin and Xu, Qiang and Krishnan, Anush and Pan, Yu and Baldan, Giancarlo and Beijbom, Oscar},
229
+ booktitle={Proceedings of the IEEE/CVF conference on computer vision and pattern recognition},
230
+ pages={11621--11631},
231
+ year={2020}
232
+ }
233
+ ```
234
+ ```BibTex
235
+ @inproceedings{Silberman:ECCV12,
236
+ author = {Nathan Silberman, Derek Hoiem, Pushmeet Kohli and Rob Fergus},
237
+ title = {Indoor Segmentation and Support Inference from RGBD Images},
238
+ booktitle = {ECCV},
239
+ year = {2012}
240
+ }
241
+ ```
242
+ ```BibTex
243
+ @inproceedings{ahmadyan2021objectron,
244
+ title={Objectron: A large scale dataset of object-centric videos in the wild with pose annotations},
245
+ author={Ahmadyan, Adel and Zhang, Liangkai and Ablavatski, Artsiom and Wei, Jianing and Grundmann, Matthias},
246
+ booktitle={Proceedings of the IEEE/CVF conference on computer vision and pattern recognition},
247
+ pages={7822--7831},
248
+ year={2021}
249
+ }
250
+ ```
251
+ ```BibTex
252
+ @inproceedings{sturm2012benchmark,
253
+ title={A benchmark for the evaluation of RGB-D SLAM systems},
254
+ author={Sturm, J{\"u}rgen and Engelhard, Nikolas and Endres, Felix and Burgard, Wolfram and Cremers, Daniel},
255
+ booktitle={2012 IEEE/RSJ international conference on intelligent robots and systems},
256
+ pages={573--580},
257
+ year={2012},
258
+ organization={IEEE}
259
+ }
260
+ ```
261
+ ```BibTex
262
+ @inproceedings{dai2017scannet,
263
+ title={Scannet: Richly-annotated 3d reconstructions of indoor scenes},
264
+ author={Dai, Angela and Chang, Angel X and Savva, Manolis and Halber, Maciej and Funkhouser, Thomas and Nie{\ss}ner, Matthias},
265
+ booktitle={Proceedings of the IEEE conference on computer vision and pattern recognition},
266
+ pages={5828--5839},
267
+ year={2017}
268
+ }
269
+ ```
270
+ ```BibTex
271
+ @article{chang2015shapenet,
272
+ title={Shapenet: An information-rich 3d model repository},
273
+ author={Chang, Angel X and Funkhouser, Thomas and Guibas, Leonidas and Hanrahan, Pat and Huang, Qixing and Li, Zimo and Savarese, Silvio and Savva, Manolis and Song, Shuran and Su, Hao and others},
274
+ journal={arXiv preprint arXiv:1512.03012},
275
+ year={2015}
276
+ }
277
+ ```
278
+ ```BibTex
279
+ @inproceedings{xiao2013sun3d,
280
+ title={Sun3d: A database of big spaces reconstructed using sfm and object labels},
281
+ author={Xiao, Jianxiong and Owens, Andrew and Torralba, Antonio},
282
+ booktitle={Proceedings of the IEEE international conference on computer vision},
283
+ pages={1625--1632},
284
+ year={2013}
285
+ }
286
+ ```
287
+ ```BibTex
288
+ @inproceedings{sun2020scalability,
289
+ title={Scalability in perception for autonomous driving: Waymo open dataset},
290
+ author={Sun, Pei and Kretzschmar, Henrik and Dotiwalla, Xerxes and Chouard, Aurelien and Patnaik, Vijaysai and Tsui, Paul and Guo, James and Zhou, Yin and Chai, Yuning and Caine, Benjamin and others},
291
+ booktitle={Proceedings of the IEEE/CVF conference on computer vision and pattern recognition},
292
+ pages={2446--2454},
293
+ year={2020}
294
+ }
295
+ ```
296
+ </details>
297
+
298
+
299
+
300
+
301
+
302
+
303
+
304
+
305
+
306
+
307
+
308
+
309
+
310
+
external/WildCamera/hubconf.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ dependencies = ['torch']
2
+ import torch
3
+ from WildCamera.newcrfs.newcrf_incidencefield import NEWCRFIF
4
+
5
+ def WildCamera(pretrained=True):
6
+ model = NEWCRFIF(version='large07', pretrained=None)
7
+ if pretrained:
8
+ # pretrained_resource = "https://huggingface.co/datasets/Shengjie/WildCamera/resolve/main/checkpoint/wild_camera_all.pth"
9
+ # state_dict = torch.hub.load_state_dict_from_url(pretrained_resource, map_location='cpu')
10
+ state_dict = torch.load(
11
+ "/mnt/prev_nas/qhy/WildCamera/checkpoint/wild_camera_all.pth",
12
+ map_location="cpu"
13
+ )
14
+ model.load_state_dict(state_dict, strict=True)
15
+ return model
16
+
17
+ if __name__ == "__main__":
18
+ model = torch.hub.load('ShngJZ/WildCamera', "WildCamera", pretrained=True)
processor/__init__.py ADDED
File without changes
processor/captions.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+
3
+ from osdsynth.utils.logger import SkipImageException
4
+
5
+ global_qs_list = [
6
+ "Can you provide a detailed description of this image in one paragraph of 30 words or less?",
7
+ "Could you give a concise, detailed account of what's depicted in this image, all in one paragraph, aiming for no more than 30 words?",
8
+ "Please offer a detailed portrayal of this image, condensed into one paragraph, keeping it under 30 words.",
9
+ "Could you sketch out a detailed narrative of this image within a 30-word limit, all in a single paragraph?",
10
+ "Would you be able to distill the essence of this image into one detailed paragraph of exactly 30 words?",
11
+ "Can you unpack this image's details in a succinct paragraph, ensuring it's contained to up to 30 words?",
12
+ "Could you elaborate on what this image shows, using no more than 30 words, all within one paragraph?",
13
+ "In 30 words or fewer, can you dissect the details of this image, presented in a single paragraph?",
14
+ "Could you render a vivid description of this image within the confines of 30 words, all in one paragraph?",
15
+ "Please distill the details of this image into a brief yet rich description, not exceeding 30 words, all in one paragraph.",
16
+ "Can you encapsulate this image's details in a comprehensive paragraph, without exceeding 30 words?",
17
+ "Would you mind providing a detailed explanation of this image, adhering to a 30-word limit, all in one paragraph?",
18
+ "Could you convey the intricate details of this image in a brief composition of no more than 30 words, contained in one paragraph?",
19
+ "Please craft a detailed depiction of this image, ensuring it's concise with a maximum of 30 words, all within a single paragraph.",
20
+ "Can you delineate the specifics of this image in a succinct narrative, capped at 30 words, all in one paragraph?",
21
+ ]
22
+
23
+ landmark_prompt = [
24
+ "In the context of: {global_caption} Try to categorize the following image into one of these categories ['indoor', 'outdoor'], use 'others' if it is not a natural image."
25
+ ]
26
+
27
+
28
+ class CaptionImage:
29
+ def __init__(self, cfg, logger, device, init_lava=False):
30
+ self.cfg = cfg
31
+ self.logger = logger
32
+ self.device = device
33
+
34
+ # Initialize LLava, deprecated, only use placeholders
35
+ if init_lava:
36
+ from osdsynth.processor.wrappers.llava import LLavaWrapper
37
+
38
+ self.llava_processor = LLavaWrapper(cfg, logger, device)
39
+ else:
40
+ self.llava_processor = None
41
+
42
+ def process_landmark(self, image_bgr):
43
+ image_tensor, image_size = self.llava_processor.process_image(image_bgr)
44
+
45
+ global_qs = random.choice(global_qs_list)
46
+ global_caption = self.llava_processor.process_vqa(image_tensor, image_size, global_qs, 1024)
47
+
48
+ landmark_qs = random.choice(landmark_prompt)
49
+ landmark_qs = landmark_qs.format(global_caption=global_caption)
50
+ landmark_caption = self.llava_processor.process_vqa(image_tensor, image_size, landmark_qs, 50)
51
+
52
+ if "indoor" in landmark_caption.lower():
53
+ landmark = "indoor"
54
+ elif "outdoor" in landmark_caption.lower():
55
+ landmark = "outdoor"
56
+ else:
57
+ raise SkipImageException("LLava failed to predict the landmark.")
58
+
59
+ return landmark, global_caption
60
+
61
+ def process_local_caption(self, detections, global_caption="", use_placeholder=True, is_one=False, is_three=False):
62
+ n_objects = len(detections)
63
+ if not is_three:
64
+ if n_objects < 2 and is_one==False:
65
+ raise SkipImageException("Ddetected objects less than 2")
66
+ if n_objects == 0:
67
+ raise SkipImageException("No objects detected finally")
68
+ else:
69
+ if n_objects < 3:
70
+ raise SkipImageException("Ddetected objects less than 3")
71
+ if n_objects == 0:
72
+ raise SkipImageException("No objects detected finally")
73
+
74
+ for obj_idx in range(n_objects):
75
+ if use_placeholder:
76
+ # detections[obj_idx]["caption"] = f"<region{obj_idx}>"
77
+ detections[obj_idx]["caption"] = f"<region{obj_idx}: {detections[obj_idx]['class_name']}>"
78
+ else:
79
+ assert self.llava_processor is not None
80
+ detections[obj_idx]["caption"] = f"<region{obj_idx}>"
81
+
82
+ # prepare dense caption
83
+ cropped_image = detections[obj_idx]["image_crop_modified"]
84
+ image_tensor, image_size = self.llava_processor.process_image(cropped_image, is_pil_rgb=True)
85
+
86
+ local_qs_template = r""""Can you describe the {class_name} in this close-up within five words? Highlight its color, appearance, style. For example: 'Man in red hat walking', 'Wooden pallet with boxes'."""
87
+ local_qs = local_qs_template.format(
88
+ global_caption=global_caption, class_name=detections[obj_idx]["class_name"]
89
+ )
90
+ local_caption = self.llava_processor.process_vqa(image_tensor, image_size, local_qs, 50)
91
+ detections[obj_idx]["dense_caption"] = local_caption.lower().replace(".", "").strip('"')
92
+ return detections
processor/pointcloud.py ADDED
@@ -0,0 +1,476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ from collections import Counter
3
+
4
+ import cv2
5
+ import matplotlib
6
+ import numpy as np
7
+ import open3d as o3d
8
+ import torch
9
+ from osdsynth.processor.wrappers.metric3d_v2 import get_depth_model, inference_depth
10
+ from osdsynth.processor.wrappers.perspective_fields import (
11
+ create_rotation_matrix,
12
+ get_perspective_fields_model,
13
+ run_perspective_fields_model,
14
+ )
15
+ from PIL import Image
16
+ from scipy.spatial.transform import Rotation
17
+ from wis3d import Wis3D
18
+
19
+
20
+ class PointCloudReconstruction:
21
+ """Class to reconstruct point cloud from depth maps."""
22
+
23
+ def __init__(self, cfg, logger, device, init_models=True):
24
+ """Initialize the class."""
25
+ self.cfg = cfg
26
+ self.logger = logger
27
+ self.device = device
28
+ self.vis = self.cfg.vis
29
+
30
+ if init_models:
31
+ # Initialize the perspective_fields_model
32
+ self.perspective_fields_model = get_perspective_fields_model(cfg, device)
33
+
34
+ # Initialize the Camera Intrinsics Model
35
+ self.wilde_camera_model = torch.hub.load("osdsynth/external/WildCamera", "WildCamera", pretrained=True,source='local').to(device)
36
+
37
+ # Initialize the Metric3D_v2
38
+ self.depth_model = get_depth_model(device)
39
+ else:
40
+ self.perspective_fields_model = self.wilde_camera_model = self.depth_model = None
41
+
42
+ def process(self, filename, image_bgr, detections_list):
43
+ """Reconstruct point cloud from depth map."""
44
+
45
+ image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
46
+ image_rgb_pil = Image.fromarray(image_rgb)
47
+
48
+ # Run Perspective Fields, this returns the pitch, roll
49
+ (
50
+ vis_perspective_fields,
51
+ perspective_fields,
52
+ ) = run_perspective_fields_model(self.perspective_fields_model, image_bgr)
53
+
54
+ # Perspective Fields to Rotation Matrix
55
+ perspective_R = create_rotation_matrix(
56
+ roll=perspective_fields["roll"],
57
+ pitch=perspective_fields["pitch"],
58
+ yaw=0,
59
+ degrees=True,
60
+ )
61
+
62
+ # Infer camera intrinsics
63
+ intrinsic, _ = self.wilde_camera_model.inference(image_rgb_pil, wtassumption=False)
64
+
65
+ # Infer depth
66
+ metric_depth = inference_depth(image_rgb, intrinsic, self.depth_model)
67
+
68
+ # Depth to points
69
+ pts3d = depth_to_points(metric_depth[None], intrinsic=intrinsic)
70
+ cano_pts3d = depth_to_points(metric_depth[None], R=perspective_R.T, intrinsic=intrinsic)
71
+
72
+ # Translate the points to ground
73
+ cano_pts3d_flattened = cano_pts3d.reshape(-1, 3)
74
+ sorted_flattened_points = cano_pts3d_flattened[cano_pts3d_flattened[:, 2].argsort()]
75
+ fifty_percent_index = int(sorted_flattened_points.shape[0] * 0.5)
76
+ selected_nearest_points = sorted_flattened_points[:fifty_percent_index]
77
+ min_y = np.min(selected_nearest_points[:, 1])
78
+ cano_pts3d[:, :, 1] -= min_y
79
+
80
+ max_x = np.max(cano_pts3d[:, :, 0])
81
+ min_x = np.min(cano_pts3d[:, :, 0])
82
+ max_z = np.max(cano_pts3d[:, :, 2])
83
+ min_z = np.min(cano_pts3d[:, :, 2])
84
+ xz_max_min = [max_x, min_x, max_z, min_z]
85
+
86
+ if self.vis:
87
+ wis3d = Wis3D(self.cfg.wis3d_folder, filename)
88
+ # wis3d.add_point_cloud(vertices=pts3d.reshape((-1, 3)), colors=image_rgb.reshape(-1, 3), name="pts3d")
89
+ wis3d.add_point_cloud(
90
+ vertices=cano_pts3d.reshape((-1, 3)), colors=image_rgb.reshape(-1, 3), name="cano_pts3d"
91
+ )
92
+
93
+
94
+
95
+ ### Create object points ###
96
+ n_objects = len(detections_list)
97
+
98
+ for obj_idx in range(n_objects):
99
+ if detections_list[obj_idx]["xyxy"][0] > cano_pts3d.shape[1]:
100
+ detections_list[obj_idx]["xyxy"][0] = cano_pts3d.shape[1]-1
101
+ if detections_list[obj_idx]["xyxy"][1] > cano_pts3d.shape[0]:
102
+ detections_list[obj_idx]["xyxy"][1] = cano_pts3d.shape[0]-1
103
+ if detections_list[obj_idx]["xyxy"][2] > cano_pts3d.shape[1]:
104
+ detections_list[obj_idx]["xyxy"][2] = cano_pts3d.shape[1]-1
105
+ if detections_list[obj_idx]["xyxy"][3] > cano_pts3d.shape[0]:
106
+ detections_list[obj_idx]["xyxy"][3] = cano_pts3d.shape[0]-1
107
+
108
+ bbox = detections_list[obj_idx]["xyxy"]
109
+
110
+ detections_list[obj_idx]["left_edge"] = -cano_pts3d[int((int(bbox[1])+int(bbox[3]))/ 2)][0][0]
111
+ detections_list[obj_idx]["right_edge"] = -cano_pts3d[int((int(bbox[1])+int(bbox[3]))/ 2)][-1][0]
112
+
113
+ detections_list[obj_idx]["square"] = np.abs((int(bbox[1])-int(bbox[3]))*(int(bbox[0])-int(bbox[2])))
114
+
115
+ xc = int(intrinsic[0, 2])
116
+ yc = int(intrinsic[1, 2])
117
+ detections_list[obj_idx]["f"] = cano_pts3d[yc][xc] * 1000
118
+
119
+ mask = detections_list[obj_idx]["subtracted_mask"]
120
+ class_name = detections_list[obj_idx]["class_name"]
121
+
122
+ object_pcd = create_object_pcd(cano_pts3d, image_rgb, mask)
123
+
124
+ # The object should at least contains 5 points
125
+ if len(object_pcd.points) < max(self.cfg.min_points_threshold, 5):
126
+ print("camera_object_pcd points less than threshold, skip this detection")
127
+ continue
128
+
129
+ object_pcd = process_pcd(self.cfg, object_pcd)
130
+
131
+ if len(object_pcd.points) < self.cfg.min_points_threshold_after_denoise:
132
+ print(f"{class_name} pcd_bbox too less points ({len(object_pcd.points)}), skip this detection")
133
+ continue
134
+
135
+ axis_aligned_bbox, oriented_bbox = get_bounding_box(self.cfg, object_pcd)
136
+
137
+ if axis_aligned_bbox.volume() < 1e-6:
138
+ print(f"{class_name} pcd_bbox got small volume, skip this detection")
139
+ continue
140
+
141
+ detections_list[obj_idx]["pcd"] = object_pcd
142
+ detections_list[obj_idx]["axis_aligned_bbox"] = axis_aligned_bbox
143
+ detections_list[obj_idx]["oriented_bbox"] = oriented_bbox
144
+
145
+ # Filter detections to include only those with a 'pcd' key
146
+ filtered_detections = [det for det in detections_list if "pcd" in det]
147
+
148
+ instance_colored_pcds = color_by_instance([det["pcd"] for det in filtered_detections])
149
+ axis_aligned_bbox = [det["axis_aligned_bbox"] for det in filtered_detections]
150
+ oriented_bboxes = [det["oriented_bbox"] for det in filtered_detections]
151
+
152
+ if self.vis:
153
+ obj_id = 0
154
+ for obj_pcd, obj_aa_box, obj_or_box in zip(instance_colored_pcds, axis_aligned_bbox, oriented_bboxes):
155
+ class_name = filtered_detections[obj_id]["class_name"]
156
+ pcd_points = np.asarray(obj_pcd.points)
157
+ pcd_colors = np.asarray(obj_pcd.colors)
158
+
159
+ # Convert bbox to center, euler, extent
160
+ aa_center, aa_eulers, aa_extent = axis_aligned_bbox_to_center_euler_extent(
161
+ obj_aa_box.get_min_bound(), obj_aa_box.get_max_bound()
162
+ )
163
+ or_center, or_eulers, or_extent = oriented_bbox_to_center_euler_extent(
164
+ obj_or_box.center, obj_or_box.R, obj_or_box.extent
165
+ )
166
+
167
+ wis3d.add_point_cloud(vertices=pcd_points, colors=pcd_colors, name=f"{obj_id:02d}_{class_name}")
168
+ wis3d.add_boxes(
169
+ positions=aa_center, eulers=aa_eulers, extents=aa_extent, name=f"{obj_id:02d}_{class_name}_aa_bbox"
170
+ )
171
+ # wis3d.add_boxes(positions=or_center, eulers=or_eulers, extents=or_extent, name=f"{obj_id:02d}_{class_name}_or_bbox")
172
+ obj_id += 1
173
+
174
+ angles = [perspective_fields["roll"],perspective_fields["pitch"]]
175
+ return filtered_detections, angles, xz_max_min
176
+
177
+
178
+ def depth_to_points(depth, R=None, t=None, fov=None, intrinsic=None):
179
+ K = intrinsic
180
+ Kinv = np.linalg.inv(K)
181
+ if R is None:
182
+ R = np.eye(3)
183
+ if t is None:
184
+ t = np.zeros(3)
185
+
186
+ # M converts from your coordinate to PyTorch3D's coordinate system
187
+ M = np.eye(3)
188
+
189
+ height, width = depth.shape[1:3]
190
+
191
+ x = np.arange(width)
192
+ y = np.arange(height)
193
+ coord = np.stack(np.meshgrid(x, y), -1)
194
+ coord = np.concatenate((coord, np.ones_like(coord)[:, :, [0]]), -1) # z=1
195
+ coord = coord.astype(np.float32)
196
+ coord = coord[None] # bs, h, w, 3
197
+
198
+ D = depth[:, :, :, None, None]
199
+ pts3D_1 = D * Kinv[None, None, None, ...] @ coord[:, :, :, :, None]
200
+ # pts3D_1 live in your coordinate system. Convert them to Py3D's
201
+ pts3D_1 = M[None, None, None, ...] @ pts3D_1
202
+ # from reference to targe tviewpoint
203
+ pts3D_2 = R[None, None, None, ...] @ pts3D_1 + t[None, None, None, :, None]
204
+
205
+ # G converts from your coordinate to PyTorch3D's coordinate system
206
+ G = np.eye(3)
207
+ G[0, 0] = -1.0
208
+ G[1, 1] = -1.0
209
+
210
+ return pts3D_2[:, :, :, :3, 0][0] @ G.T
211
+
212
+
213
+ def create_object_pcd(image_points, image_rgb, mask):
214
+ points = image_points[mask]
215
+ colors = image_rgb[mask] / 255.0
216
+
217
+ # Perturb the points a bit to avoid colinearity
218
+ points += np.random.normal(0, 4e-3, points.shape)
219
+
220
+ # Create an Open3D PointCloud object
221
+ pcd = o3d.geometry.PointCloud()
222
+ pcd.points = o3d.utility.Vector3dVector(points)
223
+ pcd.colors = o3d.utility.Vector3dVector(colors)
224
+ return pcd
225
+
226
+
227
+ def get_bounding_box(cfg, pcd):
228
+ axis_aligned_bbox = pcd.get_axis_aligned_bounding_box()
229
+
230
+ try:
231
+ oriented_bbox = pcd.get_oriented_bounding_box(robust=True)
232
+ except RuntimeError as e:
233
+ print(f"Met {e}.")
234
+ oriented_bbox = None
235
+
236
+ return axis_aligned_bbox, oriented_bbox
237
+
238
+
239
+ def points_to_pcd(points, colors=None):
240
+ pcd = o3d.geometry.PointCloud()
241
+ pcd.points = o3d.utility.Vector3dVector(points.reshape(-1, 3))
242
+ if colors is not None:
243
+ pcd.colors = o3d.utility.Vector3dVector(colors.reshape(-1, 3))
244
+ return pcd
245
+
246
+
247
+ def process_pcd(cfg, pcd, run_dbscan=True):
248
+ scale = np.linalg.norm(np.asarray(pcd.points).std(axis=0)) * 3.0 + 1e-6
249
+ [pcd, _] = pcd.remove_statistical_outlier(nb_neighbors=20, std_ratio=2)
250
+ pcd = pcd.voxel_down_sample(voxel_size=max(0.01, scale / 40))
251
+
252
+ if cfg.dbscan_remove_noise and run_dbscan:
253
+ # print("Before dbscan:", len(pcd.points))
254
+ pcd = pcd_denoise_dbscan(pcd, eps=cfg.dbscan_eps, min_points=cfg.dbscan_min_points) #
255
+ # print("After dbscan:", len(pcd.points))
256
+
257
+ return pcd
258
+
259
+
260
+ def pcd_denoise_dbscan(pcd: o3d.geometry.PointCloud, eps=0.02, min_points=10) -> o3d.geometry.PointCloud:
261
+ ### Remove noise via clustering
262
+ pcd_clusters = pcd.cluster_dbscan(
263
+ eps=eps,
264
+ min_points=min_points,
265
+ )
266
+
267
+ # Convert to numpy arrays
268
+ obj_points = np.asarray(pcd.points)
269
+ obj_colors = np.asarray(pcd.colors)
270
+ pcd_clusters = np.array(pcd_clusters)
271
+
272
+ # Count all labels in the cluster
273
+ counter = Counter(pcd_clusters)
274
+
275
+ # Remove the noise label
276
+ if counter and (-1 in counter):
277
+ del counter[-1]
278
+
279
+ if counter:
280
+ # Find the label of the largest cluster
281
+ most_common_label, _ = counter.most_common(1)[0]
282
+
283
+ # Create mask for points in the largest cluster
284
+ largest_mask = pcd_clusters == most_common_label
285
+
286
+ # Apply mask
287
+ largest_cluster_points = obj_points[largest_mask]
288
+ largest_cluster_colors = obj_colors[largest_mask]
289
+
290
+ # If the largest cluster is too small, return the original point cloud
291
+ if len(largest_cluster_points) < 5:
292
+ return pcd
293
+
294
+ # Create a new PointCloud object
295
+ largest_cluster_pcd = o3d.geometry.PointCloud()
296
+ largest_cluster_pcd.points = o3d.utility.Vector3dVector(largest_cluster_points)
297
+ largest_cluster_pcd.colors = o3d.utility.Vector3dVector(largest_cluster_colors)
298
+
299
+ pcd = largest_cluster_pcd
300
+
301
+ return pcd
302
+
303
+
304
+ def create_object_pcd(image_points, image_rgb, mask):
305
+ points = image_points[mask]
306
+ colors = image_rgb[mask] / 255.0
307
+
308
+ # Perturb the points a bit to avoid colinearity
309
+ points += np.random.normal(0, 4e-3, points.shape)
310
+
311
+ # Create an Open3D PointCloud object
312
+ pcd = o3d.geometry.PointCloud()
313
+ pcd.points = o3d.utility.Vector3dVector(points)
314
+ pcd.colors = o3d.utility.Vector3dVector(colors)
315
+ return pcd
316
+
317
+
318
+ def color_by_instance(pcds):
319
+ cmap = matplotlib.colormaps.get_cmap("turbo")
320
+ instance_colors = cmap(np.linspace(0, 1, len(pcds)))
321
+ for i in range(len(pcds)):
322
+ pcd = pcds[i]
323
+ pcd.colors = o3d.utility.Vector3dVector(np.tile(instance_colors[i, :3], (len(pcd.points), 1)))
324
+ return pcds
325
+
326
+
327
+ def oriented_bbox_to_center_euler_extent(bbox_center, box_R, bbox_extent):
328
+ center = np.asarray(bbox_center)
329
+ extent = np.asarray(bbox_extent)
330
+ eulers = Rotation.from_matrix(box_R.copy()).as_euler("XYZ")
331
+ return center, eulers, extent
332
+
333
+
334
+ def axis_aligned_bbox_to_center_euler_extent(min_coords, max_coords):
335
+ # Calculate the center
336
+ center = tuple((min_val + max_val) / 2.0 for min_val, max_val in zip(min_coords, max_coords))
337
+
338
+ # Euler angles for an axis-aligned bounding box are always 0
339
+ eulers = (0, 0, 0)
340
+
341
+ # Calculate the extents
342
+ extent = tuple(max_val - min_val for min_val, max_val in zip(min_coords, max_coords))
343
+
344
+ return center, eulers, extent
345
+
346
+
347
+ # Distance calculations
348
+ def human_like_distance(distance_meters):
349
+ # Define the choices with units included, focusing on the 0.1 to 10 meters range
350
+ if distance_meters < 1: # For distances less than 1 meter
351
+ choices = [
352
+ (
353
+ round(distance_meters * 100, 2),
354
+ "centimeters",
355
+ 0.2,
356
+ ), # Centimeters for very small distances
357
+ (
358
+ round(distance_meters * 39.3701, 2),
359
+ "inches",
360
+ 0.8,
361
+ ), # Inches for the majority of cases under 1 meter
362
+ ]
363
+ elif distance_meters < 3: # For distances less than 3 meters
364
+ choices = [
365
+ (round(distance_meters, 2), "meters", 0.5),
366
+ (
367
+ round(distance_meters * 3.28084, 2),
368
+ "feet",
369
+ 0.5,
370
+ ), # Feet as a common unit within indoor spaces
371
+ ]
372
+ else: # For distances from 3 up to 10 meters
373
+ choices = [
374
+ (
375
+ round(distance_meters, 2),
376
+ "meters",
377
+ 0.7,
378
+ ), # Meters for clarity and international understanding
379
+ (
380
+ round(distance_meters * 3.28084, 2),
381
+ "feet",
382
+ 0.3,
383
+ ), # Feet for additional context
384
+ ]
385
+
386
+ # Normalize probabilities and make a selection
387
+ total_probability = sum(prob for _, _, prob in choices)
388
+ cumulative_distribution = []
389
+ cumulative_sum = 0
390
+ for value, unit, probability in choices:
391
+ cumulative_sum += probability / total_probability # Normalize probabilities
392
+ cumulative_distribution.append((cumulative_sum, value, unit))
393
+
394
+ # Randomly choose based on the cumulative distribution
395
+ r = random.random()
396
+ for cumulative_prob, value, unit in cumulative_distribution:
397
+ if r < cumulative_prob:
398
+ return f"{value} {unit}"
399
+
400
+ # Fallback to the last choice if something goes wrong
401
+ return f"{choices[-1][0]} {choices[-1][1]}"
402
+
403
+
404
+ def calculate_distances_between_point_clouds(A, B):
405
+ dist_pcd1_to_pcd2 = np.asarray(A.compute_point_cloud_distance(B))
406
+ dist_pcd2_to_pcd1 = np.asarray(B.compute_point_cloud_distance(A))
407
+ combined_distances = np.concatenate((dist_pcd1_to_pcd2, dist_pcd2_to_pcd1))
408
+ avg_dist = np.mean(combined_distances)
409
+ return human_like_distance(avg_dist)
410
+
411
+
412
+ def calculate_centroid(pcd):
413
+ """Calculate the centroid of a point cloud."""
414
+ points = np.asarray(pcd.points)
415
+ centroid = np.mean(points, axis=0)
416
+ return centroid
417
+
418
+
419
+ def calculate_relative_positions(centroids):
420
+ """Calculate the relative positions between centroids of point clouds."""
421
+ num_centroids = len(centroids)
422
+ relative_positions_info = []
423
+
424
+ for i in range(num_centroids):
425
+ for j in range(i + 1, num_centroids):
426
+ relative_vector = centroids[j] - centroids[i]
427
+
428
+ distance = np.linalg.norm(relative_vector)
429
+ relative_positions_info.append(
430
+ {"pcd_pair": (i, j), "relative_vector": relative_vector, "distance": distance}
431
+ )
432
+
433
+ return relative_positions_info
434
+
435
+
436
+ def get_bounding_box_height(pcd):
437
+ """
438
+ Compute the height of the bounding box for a given point cloud.
439
+
440
+ Parameters:
441
+ pcd (open3d.geometry.PointCloud): The input point cloud.
442
+
443
+ Returns:
444
+ float: The height of the bounding box.
445
+ """
446
+ aabb = pcd.get_axis_aligned_bounding_box()
447
+ return aabb.get_extent()[1] # Assuming the Y-axis is the up-direction
448
+
449
+
450
+ def compare_bounding_box_height(pcd_i, pcd_j):
451
+ """
452
+ Compare the bounding box heights of two point clouds.
453
+
454
+ Parameters:
455
+ pcd_i (open3d.geometry.PointCloud): The first point cloud.
456
+ pcd_j (open3d.geometry.PointCloud): The second point cloud.
457
+
458
+ Returns:
459
+ bool: True if the bounding box of pcd_i is taller than that of pcd_j, False otherwise.
460
+ """
461
+ height_i = get_bounding_box_height(pcd_i)
462
+ height_j = get_bounding_box_height(pcd_j)
463
+
464
+ return height_i > height_j
465
+
466
+ def get_square(point_1, point_2):
467
+ """Calculate the square of the distance between two points."""
468
+ return (point_1[0]-point_2[0]) * (point_1[1]-point_2[1])
469
+
470
+ def get_focal_length(intrinsic, c_point):
471
+ """Calculate the focal length from the intrinsic matrix."""
472
+ xc = intrinsic[0, 2]
473
+ yc = intrinsic[1, 2]
474
+
475
+
476
+ return f
processor/prompt.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ from itertools import combinations
3
+
4
+ import numpy as np
5
+ from osdsynth.processor.prompt_utils import *
6
+ from osdsynth.processor.prompt_T2Ibench import *
7
+ from osdsynth.processor.prompt_ImageEditbench import *
8
+ from osdsynth.processor.prompt_CR import *
9
+
10
+
11
+
12
+
13
+ class T2IPromptGenerator:
14
+ def __init__(self, cfg, logger, device):
15
+ """Initialize the class."""
16
+ self.cfg = cfg
17
+ self.logger = logger
18
+ self.device = device
19
+ self.vis = True
20
+
21
+ def evaluate_predicates_on_pairs(self, detections, n_conv=3, spatial_choice=-1):
22
+ # 全部是SpatialBench的prompt
23
+ all_prompt_variants = [
24
+ camera_front_camera_center, # 0
25
+ camera_back_camera_center, # 1
26
+ camera_left_camera_center, # 2
27
+ camera_right_camera_center, # 3
28
+
29
+ camera_front_object_center, # 4
30
+ camera_back_object_center, # 5
31
+ camera_left_object_center, # 6
32
+ camera_right_object_center, # 7
33
+
34
+ object_side_by_side_same_direction, # 8
35
+ object_side_by_side_opposite_direction, # 9
36
+ object_face_to_face, # 10
37
+ object_back_to_back, # 11
38
+
39
+ object_front, # 12
40
+ object_back, # 13
41
+ object_left, # 14
42
+ object_right, # 15
43
+
44
+ camera_two_objects_closer, # 16
45
+ camera_two_objects_farther, # 17
46
+ camera_two_objects_left, # 18
47
+ camera_two_objects_right, # 19
48
+
49
+ object_apart_0_5meter, # 20
50
+ object_apart_1meter, # 21
51
+ object_apart_1_5meter, # 22
52
+ object_apart_2meter, # 23
53
+
54
+ camera_1meter_away, # 24
55
+ camera_2meter_away, # 25
56
+ camera_3meter_away, # 26
57
+ camera_4meter_away, # 27
58
+
59
+ object_bigger_than1_2, # 28
60
+ object_higher_20cm, # 29
61
+ object_longer_50cm, # 30
62
+ object_wider_30cm, # 31
63
+
64
+ side_by_side_front, # 32
65
+ side_by_side_left, # 33
66
+ side_by_side_right, # 34
67
+ side_by_side_back, # 35
68
+ ]
69
+
70
+ if spatial_choice != -1:
71
+ all_prompt_variants = [all_prompt_variants[spatial_choice]]
72
+ else:
73
+ raise ValueError("spatial_choice must not be -1 for T2Ibench")
74
+
75
+
76
+ if spatial_choice not in [0,1,2,3,4,5,6,7,24,25,26,27]:
77
+ all_combinations = list(combinations(range(len(detections)), 2))
78
+ random.shuffle(all_combinations)
79
+ selected_combinations = all_combinations[:3]
80
+ object_pairs = [(detections[i], detections[j]) for i, j in selected_combinations]
81
+
82
+
83
+
84
+ results = []
85
+ correct = 0
86
+
87
+ for A, B in object_pairs:
88
+ all_prompt_variants = [item for item in all_prompt_variants]
89
+ # selected_predicates_choices = random.sample(all_prompt_variants, n_conv)
90
+ selected_predicates_choices = random.sample(all_prompt_variants, len(all_prompt_variants))
91
+
92
+ for prompt_func in selected_predicates_choices:
93
+ res = prompt_func(A, B)
94
+ results.append((res, A, B, prompt_func.__name__))
95
+ correct = correct + 1 if res[2] else correct
96
+ score = res[3]
97
+
98
+ return results, correct, score
99
+ else:
100
+ A = detections[0]
101
+
102
+ results = []
103
+ correct = 0
104
+
105
+ all_prompt_variants = [item for item in all_prompt_variants]
106
+ selected_predicates_choices = random.sample(all_prompt_variants, len(all_prompt_variants))
107
+
108
+ for prompt_func in selected_predicates_choices:
109
+ res = prompt_func(A)
110
+ results.append((res, A, prompt_func.__name__))
111
+ correct = correct + 1 if res[2] else correct
112
+ score = res[3]
113
+
114
+ return results, correct, score
115
+
116
+
117
+ class ImageEditPromptGenerator:
118
+ def __init__(self, cfg, logger, device):
119
+ """Initialize the class."""
120
+ self.cfg = cfg
121
+ self.logger = logger
122
+ self.device = device
123
+ self.vis = True
124
+
125
+ def evaluate_predicates_on_pairs(self, detections, n_conv=3, spatial_choice=-1):
126
+ # 全部是SpatialBench的prompt
127
+ all_prompt_variants = [
128
+ camera_to_front_camera_center, # 0
129
+ camera_to_left_camera_center, # 1
130
+ camera_to_right_camera_center, # 2
131
+ camera_to_back_camera_center, # 3
132
+
133
+ camera_to_front_object_center, # 4
134
+ camera_to_left_object_center, # 5
135
+ camera_to_right_object_center, # 6
136
+ camera_to_back_object_center, # 7
137
+
138
+ object_insert_side_by_side_same_orientation, # 8
139
+ object_insert_side_by_side_opposite_orientation, # 9
140
+ object_insert_face_to_face, # 10
141
+ object_insert_back_to_back, # 11
142
+
143
+ object_insert_front_object_center, # 12
144
+ object_insert_left_object_center, # 13
145
+ object_insert_right_object_center, # 14
146
+ object_insert_behind_object_center, # 15
147
+
148
+ object_insert_front_camera_center, # 16
149
+ object_insert_left_camera_center, # 17
150
+ object_insert_right_camera_center, # 18
151
+ object_insert_behind_camera_center, # 19
152
+
153
+ objectmove_close_1meter, # 20
154
+ objectmove_far_1meter, # 21
155
+ objectmove_left_1meter, # 22
156
+ objectmove_right_1meter, # 23
157
+
158
+ camera_forward_1meter, # 24
159
+ camera_leftward_1meter, # 25
160
+ camera_rightward_1meter, # 26
161
+ camera_backward_1meter, # 27
162
+
163
+ object_make_12bigger, # 28
164
+ object_make_20cm_higher, # 29
165
+ object_make_50cm_longer, # 30
166
+ object_make_40cm_wider, # 31
167
+ ]
168
+
169
+ if spatial_choice != -1:
170
+ all_prompt_variants = [all_prompt_variants[spatial_choice]]
171
+ else:
172
+ raise ValueError("spatial_choice must not be -1 for T2Ibench")
173
+
174
+
175
+ if spatial_choice not in [0,1,2,3,4,5,6,7,20,21,22,23,24,25,26,27,28,29,30,31]:
176
+ object_pairs = [(detections[0], detections[1])]
177
+
178
+
179
+
180
+ results = []
181
+ correct = 0
182
+
183
+ for A, B in object_pairs:
184
+ all_prompt_variants = [item for item in all_prompt_variants]
185
+ # selected_predicates_choices = random.sample(all_prompt_variants, n_conv)
186
+ selected_predicates_choices = random.sample(all_prompt_variants, len(all_prompt_variants))
187
+
188
+ for prompt_func in selected_predicates_choices:
189
+ res = prompt_func(A, B)
190
+ results.append((res, A, B, prompt_func.__name__))
191
+ correct = correct + 1 if res[2] else correct
192
+ score = res[3]
193
+
194
+ return results, correct, score
195
+ else:
196
+ A = detections[0]
197
+
198
+ results = []
199
+ correct = 0
200
+
201
+ all_prompt_variants = [item for item in all_prompt_variants]
202
+ selected_predicates_choices = random.sample(all_prompt_variants, len(all_prompt_variants))
203
+
204
+ for prompt_func in selected_predicates_choices:
205
+ res = prompt_func(A)
206
+ results.append((res, A, prompt_func.__name__))
207
+ correct = correct + 1 if res[2] else correct
208
+ score = res[3]
209
+
210
+ return results, correct, score
211
+
212
+ class CRPromptGenerator:
213
+ def __init__(self, cfg, logger, device):
214
+ """Initialize the class."""
215
+ self.cfg = cfg
216
+ self.logger = logger
217
+ self.device = device
218
+ self.vis = True
219
+
220
+ def evaluate_predicates_on_pairs(self, detections, is_three=False, spatial_choice=-1):
221
+ # 全部是SpatialBench的prompt
222
+ all_prompt_variants_two = [
223
+ CR_two_front,
224
+ CR_two_back,
225
+ CR_two_left,
226
+ CR_two_right,
227
+ ]
228
+
229
+ all_prompt_variants_three = [
230
+ CR_three_front,
231
+ CR_three_back,
232
+ CR_three_left,
233
+ CR_three_right,
234
+ ]
235
+
236
+
237
+
238
+
239
+ A = detections[0]
240
+ B = detections[1]
241
+ if is_three:
242
+ C = detections[2]
243
+ all_prompt_variants = all_prompt_variants_three
244
+ else:
245
+ C = None
246
+ all_prompt_variants = all_prompt_variants_two
247
+
248
+
249
+
250
+ if spatial_choice != -1:
251
+ all_prompt_variants = [all_prompt_variants[spatial_choice]]
252
+ else:
253
+ raise ValueError("spatial_choice must not be -1 for T2Ibench")
254
+
255
+
256
+ results = []
257
+ correct = 0
258
+
259
+
260
+ all_prompt_variants = [item for item in all_prompt_variants]
261
+ # selected_predicates_choices = random.sample(all_prompt_variants, n_conv)
262
+ selected_predicates_choices = random.sample(all_prompt_variants, len(all_prompt_variants))
263
+
264
+ prompt_func = selected_predicates_choices[0]
265
+
266
+ if is_three:
267
+ res = prompt_func(A, B, C)
268
+ results.append((res, A, B, C, prompt_func.__name__))
269
+
270
+ else:
271
+ res = prompt_func(A, B)
272
+ results.append((res, A, B, prompt_func.__name__))
273
+
274
+ correct = correct + 1 if res[2] else correct
275
+ score = res[3]
276
+
277
+ return results, correct, score
processor/prompt_CR.py ADDED
@@ -0,0 +1,687 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ from itertools import combinations
3
+
4
+ import numpy as np
5
+ from osdsynth.processor.pointcloud import calculate_distances_between_point_clouds, human_like_distance
6
+ # from osdsynth.processor.prompt_template import *
7
+ from osdsynth.processor.prompt_utils import *
8
+ # from osdsynth.processor.prompt_spatitalbench_template import *
9
+ from osdsynth.processor.prompt import *
10
+
11
+
12
+ def get_upper(theta):
13
+ for i in [-1,0,1,2]:
14
+ if theta < i * np.pi / 2 - np.pi / 4:
15
+ return i * np.pi / 2 - np.pi / 4
16
+ return 3 * np.pi / 2 - np.pi / 4
17
+
18
+
19
+
20
+ def CR_two_front(A, B):
21
+ A_desc, A_cloud = A["caption"], A["pcd"]
22
+ A_desc = A_desc.lower()
23
+ B_desc, B_cloud = B["caption"], B["pcd"]
24
+ B_desc = B_desc.lower()
25
+
26
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
27
+ A_pos = A_cloud.get_center()
28
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
29
+ B_pos = B_cloud.get_center()
30
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
31
+
32
+
33
+ A_rotation_matrix = A["rotation_matrix"]
34
+ B_rotation_matrix = B["rotation_matrix"]
35
+
36
+ B_rotation_matrix = A_rotation_matrix.T @ B_rotation_matrix # 在A的坐标系下,B的旋转矩阵
37
+
38
+ A_P_B = A_rotation_matrix.T @ (B_pos - A_pos) # 在A的坐标系下,B相对于A的位置
39
+ A_P_B_last = A['A_P_B']
40
+
41
+
42
+ theta1 = np.arctan2(A_P_B[2], A_P_B[0])
43
+ theta2 = np.arctan2(A_P_B_last[2], A_P_B_last[0])
44
+ theta1_upper = get_upper(theta1)
45
+
46
+ if theta1_upper < np.pi and theta1_upper > -np.pi/2:
47
+ theta1_lower = theta1_upper - np.pi / 2
48
+ position = True if theta1_upper > theta2 > theta1_lower else False
49
+ else: # 135~180和-180~-135的情况
50
+ position = True if theta2 < -3/4*np.pi or theta2 > 3/4*np.pi else False
51
+
52
+
53
+ max_angle = 30
54
+
55
+
56
+ angle_rad_A = np.arccos(np.clip(np.dot(A_rotation_matrix.T[0], np.array([0,0,-1])), -1.0, 1.0))
57
+ direction = angle_rad_A < max_angle / 180 * np.pi
58
+
59
+ check = position and direction
60
+
61
+ question_template = f"Are [A] and [B] maintaining their original relative relationship when viewed from the front of [A]?"
62
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
63
+
64
+ answer = "Yes" if check else "No"
65
+
66
+ score = 0
67
+ if check:
68
+ score = 1
69
+ else:
70
+ if position:
71
+ w1 = 1
72
+ else:
73
+ if theta1_upper < np.pi and theta1_upper > -np.pi/2:
74
+ w1 = 1 - np.min([np.abs(theta1_upper-theta2), np.abs(theta2-theta1_lower)]) / (np.pi / 6) # 30度的阈值
75
+ else: # 135~180和-180~-135的情况
76
+ theta2 = theta2 + 2 * np.pi if theta2 < -3/4*np.pi else theta2 # 转化到0~2pi
77
+ w1 = 1 - np.min([np.abs(1.25*np.pi-theta2), np.abs(theta2-0.75*np.pi)]) / (np.pi / 6) # 30度的阈值
78
+
79
+ if direction:
80
+ w2 = 1
81
+ else:
82
+ w2 = 1 - np.abs(angle_rad_A - max_angle / 180 * np.pi) / (np.pi / 6) # 30度的阈值
83
+ score = 0 if w1<0 or w2<0 else w1 * w2
84
+
85
+ return question, answer, check, score
86
+
87
+ def CR_two_back(A, B):
88
+ A_desc, A_cloud = A["caption"], A["pcd"]
89
+ A_desc = A_desc.lower()
90
+ B_desc, B_cloud = B["caption"], B["pcd"]
91
+ B_desc = B_desc.lower()
92
+
93
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
94
+ A_pos = A_cloud.get_center()
95
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
96
+ B_pos = B_cloud.get_center()
97
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
98
+
99
+
100
+ A_rotation_matrix = A["rotation_matrix"]
101
+ B_rotation_matrix = B["rotation_matrix"]
102
+
103
+ B_rotation_matrix = A_rotation_matrix.T @ B_rotation_matrix # 在A的坐标系下,B的旋转矩阵
104
+
105
+ A_P_B = A_rotation_matrix.T @ (B_pos - A_pos) # 在A的坐标系下,B相对于A的位置
106
+ A_P_B_last = A['A_P_B']
107
+
108
+
109
+ theta1 = np.arctan2(A_P_B[2], A_P_B[0])
110
+ theta2 = np.arctan2(A_P_B_last[2], A_P_B_last[0])
111
+ theta1_upper = get_upper(theta1)
112
+ if theta1_upper < np.pi and theta1_upper > -np.pi/2:
113
+ theta1_lower = theta1_upper - np.pi / 2
114
+ position = True if theta1_upper > theta2 > theta1_lower else False
115
+ else: # 135~180和-180~-135的情况
116
+ position = True if theta2 < -3/4*np.pi or theta2 > 3/4*np.pi else False
117
+
118
+
119
+ max_angle = 30
120
+
121
+ angle_rad_A = np.arccos(np.clip(np.dot(A_rotation_matrix.T[0], np.array([0,0,1])), -1.0, 1.0))
122
+ direction = angle_rad_A < max_angle / 180 * np.pi
123
+
124
+ check = position and direction
125
+
126
+ question_template = f"Are [A] and [B] maintaining their original relative relationship when viewed from the back of [A]?"
127
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
128
+
129
+ answer = "Yes" if check else "No"
130
+
131
+ score = 0
132
+ if check:
133
+ score = 1
134
+ else:
135
+ if position:
136
+ w1 = 1
137
+ else:
138
+ if theta1_upper < np.pi and theta1_upper > -np.pi/2:
139
+ w1 = 1 - np.min([np.abs(theta1_upper-theta2), np.abs(theta2-theta1_lower)]) / (np.pi / 6) # 30度的阈值
140
+ else: # 135~180和-180~-135的情况
141
+ theta2 = theta2 + 2 * np.pi if theta2 < -3/4*np.pi else theta2 # 转化到0~2pi
142
+ w1 = 1 - np.min([np.abs(1.25*np.pi-theta2), np.abs(theta2-0.75*np.pi)]) / (np.pi / 6) # 30度的阈值
143
+
144
+ if direction:
145
+ w2 = 1
146
+ else:
147
+ w2 = 1 - np.abs(angle_rad_A - max_angle / 180 * np.pi) / (np.pi / 6) # 30度的阈值
148
+ score = 0 if w1<0 or w2<0 else w1 * w2
149
+
150
+ return question, answer, check, score
151
+
152
+ def CR_two_left(A, B):
153
+ A_desc, A_cloud = A["caption"], A["pcd"]
154
+ A_desc = A_desc.lower()
155
+ B_desc, B_cloud = B["caption"], B["pcd"]
156
+ B_desc = B_desc.lower()
157
+
158
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
159
+ A_pos = A_cloud.get_center()
160
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
161
+ B_pos = B_cloud.get_center()
162
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
163
+
164
+
165
+ A_rotation_matrix = A["rotation_matrix"]
166
+ B_rotation_matrix = B["rotation_matrix"]
167
+
168
+ B_rotation_matrix = A_rotation_matrix.T @ B_rotation_matrix # 在A的坐标系下,B的旋转矩阵
169
+
170
+ A_P_B = A_rotation_matrix.T @ (B_pos - A_pos) # 在A的坐标系下,B相对于A的位置
171
+ A_P_B_last = A['A_P_B']
172
+
173
+ theta1 = np.arctan2(A_P_B[2], A_P_B[0])
174
+ theta2 = np.arctan2(A_P_B_last[2], A_P_B_last[0])
175
+ theta1_upper = get_upper(theta1)
176
+ if theta1_upper < np.pi and theta1_upper > -np.pi/2:
177
+ theta1_lower = theta1_upper - np.pi / 2
178
+ position = True if theta1_upper > theta2 > theta1_lower else False
179
+ else: # 135~180和-180~-135的情况
180
+ position = True if theta2 < -3/4*np.pi or theta2 > 3/4*np.pi else False
181
+
182
+
183
+ max_angle = 30
184
+
185
+
186
+ angle_rad_A = np.arccos(np.clip(np.dot(A_rotation_matrix.T[0], np.array([-1,0,0])), -1.0, 1.0))
187
+ direction = angle_rad_A < max_angle / 180 * np.pi
188
+
189
+ check = position and direction
190
+
191
+ question_template = f"Are [A] and [B] maintaining their original relative relationship when viewed from the left of [A]?"
192
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
193
+
194
+ answer = "Yes" if check else "No"
195
+
196
+ score = 0
197
+ if check:
198
+ score = 1
199
+ else:
200
+ if position:
201
+ w1 = 1
202
+ else:
203
+ if theta1_upper < np.pi and theta1_upper > -np.pi/2:
204
+ w1 = 1 - np.min([np.abs(theta1_upper-theta2), np.abs(theta2-theta1_lower)]) / (np.pi / 6) # 30度的阈值
205
+ else: # 135~180和-180~-135的情况
206
+ theta2 = theta2 + 2 * np.pi if theta2 < -3/4*np.pi else theta2 # 转化到0~2pi
207
+ w1 = 1 - np.min([np.abs(1.25*np.pi-theta2), np.abs(theta2-0.75*np.pi)]) / (np.pi / 6) # 30度的阈值
208
+
209
+ if direction:
210
+ w2 = 1
211
+ else:
212
+ w2 = 1 - np.abs(angle_rad_A - max_angle / 180 * np.pi) / (np.pi / 6) # 30度的阈值
213
+ score = 0 if w1<0 or w2<0 else w1 * w2
214
+
215
+ return question, answer, check, score
216
+
217
+ def CR_two_right(A, B):
218
+ A_desc, A_cloud = A["caption"], A["pcd"]
219
+ A_desc = A_desc.lower()
220
+ B_desc, B_cloud = B["caption"], B["pcd"]
221
+ B_desc = B_desc.lower()
222
+
223
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
224
+ A_pos = A_cloud.get_center()
225
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
226
+ B_pos = B_cloud.get_center()
227
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
228
+
229
+
230
+ A_rotation_matrix = A["rotation_matrix"]
231
+ B_rotation_matrix = B["rotation_matrix"]
232
+
233
+ B_rotation_matrix = A_rotation_matrix.T @ B_rotation_matrix # 在A的坐标系下,B的旋转矩阵
234
+
235
+ A_P_B = A_rotation_matrix.T @ (B_pos - A_pos) # 在A的坐标系下,B相对于A的位置
236
+ A_P_B_last = A['A_P_B']
237
+
238
+
239
+ theta1 = np.arctan2(A_P_B[2], A_P_B[0])
240
+ theta2 = np.arctan2(A_P_B_last[2], A_P_B_last[0])
241
+ theta1_upper = get_upper(theta1)
242
+ if theta1_upper < np.pi and theta1_upper > -np.pi/2:
243
+ theta1_lower = theta1_upper - np.pi / 2
244
+ position = True if theta1_upper > theta2 > theta1_lower else False
245
+ else: # 135~180和-180~-135的情况
246
+ position = True if theta2 < -3/4*np.pi or theta2 > 3/4*np.pi else False
247
+
248
+
249
+ max_angle = 30
250
+ # angle_rad_AB = np.arccos(np.clip(np.dot(B_rotation_matrix.T[0], np.array([1,0,0])), -1.0, 1.0))
251
+ # same_direction = angle_rad_AB < max_angle / 180 * np.pi
252
+
253
+ angle_rad_A = np.arccos(np.clip(np.dot(A_rotation_matrix.T[0], np.array([1,0,0])), -1.0, 1.0))
254
+ direction = angle_rad_A < max_angle / 180 * np.pi
255
+
256
+ check = position and direction
257
+
258
+ question_template = f"Are [A] and [B] maintaining their original relative relationship when viewed from the right of [A]?"
259
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
260
+
261
+ answer = "Yes" if check else "No"
262
+
263
+ score = 0
264
+ if check:
265
+ score = 1
266
+ else:
267
+ if position:
268
+ w1 = 1
269
+ else:
270
+ if theta1_upper < np.pi and theta1_upper > -np.pi/2:
271
+ w1 = 1 - np.min([np.abs(theta1_upper-theta2), np.abs(theta2-theta1_lower)]) / (np.pi / 6) # 30度的阈值
272
+ else: # 135~180和-180~-135的情况
273
+ theta2 = theta2 + 2 * np.pi if theta2 < -3/4*np.pi else theta2 # 转化到0~2pi
274
+ w1 = 1 - np.min([np.abs(1.25*np.pi-theta2), np.abs(theta2-0.75*np.pi)]) / (np.pi / 6) # 30度的阈值
275
+
276
+ if direction:
277
+ w2 = 1
278
+ else:
279
+ w2 = 1 - np.abs(angle_rad_A - max_angle / 180 * np.pi) / (np.pi / 6) # 30度的阈值
280
+ score = 0 if w1<0 or w2<0 else w1 * w2
281
+
282
+ return question, answer, check, score
283
+
284
+
285
+ def CR_three_front(A, B, C):
286
+ A_desc, A_cloud = A["caption"], A["pcd"]
287
+ A_desc = A_desc.lower()
288
+ B_desc, B_cloud = B["caption"], B["pcd"]
289
+ B_desc = B_desc.lower()
290
+ C_desc, C_cloud = C["caption"], C["pcd"]
291
+ C_desc = C_desc.lower()
292
+
293
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
294
+ A_pos = A_cloud.get_center()
295
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
296
+ B_pos = B_cloud.get_center()
297
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
298
+ C_pos = C_cloud.get_center()
299
+ C_pos[0] = -C_pos[0]; C_pos[1] = -C_pos[1]
300
+
301
+
302
+ A_rotation_matrix = A["rotation_matrix"]
303
+ B_rotation_matrix = B["rotation_matrix"]
304
+ C_rotation_matrix = C["rotation_matrix"]
305
+
306
+ A_rotation_matrix = C_rotation_matrix.T @ A_rotation_matrix # 在C的坐标系下,A的旋转矩阵
307
+ B_rotation_matrix = C_rotation_matrix.T @ B_rotation_matrix # 在C的坐标系下,B的旋转矩阵
308
+
309
+ C_P_A = C_rotation_matrix.T @ (A_pos - C_pos) # 在C的坐标系下,A相对于C的位置
310
+ C_P_B = C_rotation_matrix.T @ (B_pos - C_pos) # 在C的坐标系下,B相对于C的位置
311
+ C_P_A_last = C['C_P_A']
312
+ C_P_B_last = C['C_P_B']
313
+
314
+ theta_CA1 = np.arctan2(C_P_A[2], C_P_A[0])
315
+ theta_CB1 = np.arctan2(C_P_B[2], C_P_B[0])
316
+ theta_CA2 = np.arctan2(C_P_A_last[2], C_P_A_last[0])
317
+ theta_CB2 = np.arctan2(C_P_B_last[2], C_P_B_last[0])
318
+
319
+
320
+ theta_CA1_upper = get_upper(theta_CA1)
321
+ theta_CA1_lower = theta_CA1_upper - np.pi / 2
322
+ if theta_CA1_upper < np.pi and theta_CA1_upper > -np.pi/2:
323
+ theta1_lower = theta_CA1_upper - np.pi / 2
324
+ position_CA = True if theta_CA1_upper > theta_CA2 > theta1_lower else False
325
+ else: # 135~180和-180~-135的情况
326
+ position_CA = True if theta_CA2 < -3/4*np.pi or theta_CA2 > 3/4*np.pi else False
327
+
328
+
329
+ theta_CB1_upper = get_upper(theta_CB1)
330
+ theta_CB1_lower = theta_CB1_upper - np.pi / 2
331
+ if theta_CB1_upper < np.pi and theta_CB1_upper > -np.pi/2:
332
+ theta1_lower = theta_CB1_upper - np.pi / 2
333
+ position_CB = True if theta_CB1_upper > theta_CB2 > theta1_lower else False
334
+ else: # 135~180和-180~-135的情况
335
+ position_CB = True if theta_CB2 < -3/4*np.pi or theta_CB2 > 3/4*np.pi else False
336
+
337
+
338
+ position = position_CA and position_CB
339
+
340
+
341
+ max_angle = 30
342
+
343
+
344
+ angle_rad_C = np.arccos(np.clip(np.dot(C_rotation_matrix.T[0], np.array([0,0,-1])), -1.0, 1.0))
345
+ direction = angle_rad_C < max_angle / 180 * np.pi
346
+
347
+
348
+ check = position and direction
349
+ question_template = f"Are [A], [B] and [C] maintaining their original relative relationship when viewed from the front of [C]?"
350
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc).replace("[C]", C_desc)
351
+ answer = "Yes" if check else "No"
352
+
353
+ score = 0
354
+ if check:
355
+ score = 1
356
+ else:
357
+ if position_CA:
358
+ w1 = 1
359
+ else:
360
+ if theta_CA1_upper < np.pi and theta_CA1_upper > -np.pi/2:
361
+ w1 = 1 - np.min([np.abs(theta_CA1_upper-theta_CA2), np.abs(theta_CA2-theta_CA1_lower)]) / (np.pi / 6) # 30度的阈值
362
+ else: # 135~180和-180~-135的情况
363
+ theta_CA2 = theta_CA2 + 2 * np.pi if theta_CA2 < -3/4*np.pi else theta_CA2
364
+ w1 = 1 - np.min([np.abs(1.25*np.pi-theta_CA2), np.abs(theta_CA2-0.75*np.pi)]) / (np.pi / 6) # 30度的阈值
365
+
366
+ if position_CB:
367
+ w2 = 1
368
+ else:
369
+ if theta_CB1_upper < np.pi and theta_CB1_upper > -np.pi/2:
370
+ w2 = 1 - np.min([np.abs(theta_CB1_upper-theta_CB2), np.abs(theta_CB2-theta_CB1_lower)]) / (np.pi / 6)
371
+ else: # 135~180和-180~-135的情况
372
+ theta_CB2 = theta_CB2 + 2 * np.pi if theta_CB2 < -3/4*np.pi else theta_CB2
373
+ w2 = 1 - np.min([np.abs(1.25*np.pi-theta_CB2), np.abs(theta_CB2-0.75*np.pi)]) / (np.pi / 6) # 30度的阈值
374
+
375
+ if direction:
376
+ w3 = 1
377
+ else:
378
+ w3 = 1 - np.abs(angle_rad_C - max_angle / 180 * np.pi) / (np.pi / 6) # 30度的阈值
379
+ score = 0 if w1<0 or w2<0 or w3<0 else w1 * w2 * w3
380
+
381
+ return question, answer, check, score
382
+
383
+ def CR_three_back(A, B, C):
384
+ A_desc, A_cloud = A["caption"], A["pcd"]
385
+ A_desc = A_desc.lower()
386
+ B_desc, B_cloud = B["caption"], B["pcd"]
387
+ B_desc = B_desc.lower()
388
+ C_desc, C_cloud = C["caption"], C["pcd"]
389
+ C_desc = C_desc.lower()
390
+
391
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
392
+ A_pos = A_cloud.get_center()
393
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
394
+ B_pos = B_cloud.get_center()
395
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
396
+ C_pos = C_cloud.get_center()
397
+ C_pos[0] = -C_pos[0]; C_pos[1] = -C_pos[1]
398
+
399
+
400
+ A_rotation_matrix = A["rotation_matrix"]
401
+ B_rotation_matrix = B["rotation_matrix"]
402
+ C_rotation_matrix = C["rotation_matrix"]
403
+
404
+ A_rotation_matrix = C_rotation_matrix.T @ A_rotation_matrix # 在C的坐标系下,A的旋转矩阵
405
+ B_rotation_matrix = C_rotation_matrix.T @ B_rotation_matrix # 在C的坐标系下,B的旋转矩阵
406
+
407
+ C_P_A = C_rotation_matrix.T @ (A_pos - C_pos) # 在C的坐标系下,A相对于C的位置
408
+ C_P_B = C_rotation_matrix.T @ (B_pos - C_pos) # 在C的坐标系下,B相对于C的位置
409
+ C_P_A_last = C['C_P_A']
410
+ C_P_B_last = C['C_P_B']
411
+
412
+ theta_CA1 = np.arctan2(C_P_A[2], C_P_A[0])
413
+ theta_CB1 = np.arctan2(C_P_B[2], C_P_B[0])
414
+ theta_CA2 = np.arctan2(C_P_A_last[2], C_P_A_last[0])
415
+ theta_CB2 = np.arctan2(C_P_B_last[2], C_P_B_last[0])
416
+
417
+ theta_CA1_upper = get_upper(theta_CA1)
418
+ theta_CA1_lower = theta_CA1_upper - np.pi / 2
419
+ if theta_CA1_upper < np.pi and theta_CA1_upper > -np.pi/2:
420
+ theta1_lower = theta_CA1_upper - np.pi / 2
421
+ position_CA = True if theta_CA1_upper > theta_CA2 > theta1_lower else False
422
+ else: # 135~180和-180~-135的情况
423
+ position_CA = True if theta_CA2 < -3/4*np.pi or theta_CA2 > 3/4*np.pi else False
424
+
425
+
426
+ theta_CB1_upper = get_upper(theta_CB1)
427
+ theta_CB1_lower = theta_CB1_upper - np.pi / 2
428
+ if theta_CB1_upper < np.pi and theta_CB1_upper > -np.pi/2:
429
+ theta1_lower = theta_CB1_upper - np.pi / 2
430
+ position_CB = True if theta_CB1_upper > theta_CB2 > theta1_lower else False
431
+ else: # 135~180和-180~-135的情况
432
+ position_CB = True if theta_CB2 < -3/4*np.pi or theta_CB2 > 3/4*np.pi else False
433
+
434
+
435
+ position = position_CA and position_CB
436
+
437
+
438
+ max_angle = 30
439
+ # angle_rad_AC = np.arccos(np.clip(np.dot(A_rotation_matrix.T[0], np.array([1,0,0])), -1.0, 1.0))
440
+ # angle_rad_BC = np.arccos(np.clip(np.dot(B_rotation_matrix.T[0], np.array([1,0,0])), -1.0, 1.0))
441
+ # same_direction_AC = angle_rad_AC < max_angle / 180 * np.pi
442
+ # same_direction_BC = angle_rad_BC < max_angle / 180 * np.pi
443
+ # same_direction = same_direction_AC and same_direction_BC
444
+
445
+
446
+ angle_rad_C = np.arccos(np.clip(np.dot(C_rotation_matrix.T[0], np.array([0,0,1])), -1.0, 1.0))
447
+ direction = angle_rad_C < max_angle / 180 * np.pi
448
+
449
+
450
+ check = position and direction
451
+ question_template = f"Are [A], [B] and [C] maintaining their original relative relationship when viewed from the back of [C]?"
452
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc).replace("[C]", C_desc)
453
+ answer = "Yes" if check else "No"
454
+
455
+ score = 0
456
+ if check:
457
+ score = 1
458
+ else:
459
+ if position_CA:
460
+ w1 = 1
461
+ else:
462
+ if theta_CA1_upper < np.pi and theta_CA1_upper > -np.pi/2:
463
+ w1 = 1 - np.min([np.abs(theta_CA1_upper-theta_CA2), np.abs(theta_CA2-theta_CA1_lower)]) / (np.pi / 6) # 30度的阈值
464
+ else: # 135~180和-180~-135的情况
465
+ theta_CA2 = theta_CA2 + 2 * np.pi if theta_CA2 < -3/4*np.pi else theta_CA2
466
+ w1 = 1 - np.min([np.abs(1.25*np.pi-theta_CA2), np.abs(theta_CA2-0.75*np.pi)]) / (np.pi / 6) # 30度的阈值
467
+
468
+ if position_CB:
469
+ w2 = 1
470
+ else:
471
+ if theta_CB1_upper < np.pi and theta_CB1_upper > -np.pi/2:
472
+ w2 = 1 - np.min([np.abs(theta_CB1_upper-theta_CB2), np.abs(theta_CB2-theta_CB1_lower)]) / (np.pi / 6)
473
+ else: # 135~180和-180~-135的情况
474
+ theta_CB2 = theta_CB2 + 2 * np.pi if theta_CB2 < -3/4*np.pi else theta_CB2
475
+ w2 = 1 - np.min([np.abs(1.25*np.pi-theta_CB2), np.abs(theta_CB2-0.75*np.pi)]) / (np.pi / 6) # 30度的阈值
476
+
477
+ if direction:
478
+ w3 = 1
479
+ else:
480
+ w3 = 1 - np.abs(angle_rad_C - max_angle / 180 * np.pi) / (np.pi / 6) # 30度的阈值
481
+ score = 0 if w1<0 or w2<0 or w3<0 else w1 * w2 * w3
482
+
483
+ return question, answer, check, score
484
+
485
+ def CR_three_left(A, B, C):
486
+ A_desc, A_cloud = A["caption"], A["pcd"]
487
+ A_desc = A_desc.lower()
488
+ B_desc, B_cloud = B["caption"], B["pcd"]
489
+ B_desc = B_desc.lower()
490
+ C_desc, C_cloud = C["caption"], C["pcd"]
491
+ C_desc = C_desc.lower()
492
+
493
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
494
+ A_pos = A_cloud.get_center()
495
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
496
+ B_pos = B_cloud.get_center()
497
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
498
+ C_pos = C_cloud.get_center()
499
+ C_pos[0] = -C_pos[0]; C_pos[1] = -C_pos[1]
500
+
501
+
502
+ A_rotation_matrix = A["rotation_matrix"]
503
+ B_rotation_matrix = B["rotation_matrix"]
504
+ C_rotation_matrix = C["rotation_matrix"]
505
+
506
+ A_rotation_matrix = C_rotation_matrix.T @ A_rotation_matrix # 在C的坐标系下,A的旋转矩阵
507
+ B_rotation_matrix = C_rotation_matrix.T @ B_rotation_matrix # 在C的坐标系下,B的旋转矩阵
508
+
509
+ C_P_A = C_rotation_matrix.T @ (A_pos - C_pos) # 在C的坐标系下,A相对于C的位置
510
+ C_P_B = C_rotation_matrix.T @ (B_pos - C_pos) # 在C的坐标系下,B相对于C的位置
511
+ C_P_A_last = C['C_P_A']
512
+ C_P_B_last = C['C_P_B']
513
+
514
+ theta_CA1 = np.arctan2(C_P_A[2], C_P_A[0])
515
+ theta_CB1 = np.arctan2(C_P_B[2], C_P_B[0])
516
+ theta_CA2 = np.arctan2(C_P_A_last[2], C_P_A_last[0])
517
+ theta_CB2 = np.arctan2(C_P_B_last[2], C_P_B_last[0])
518
+
519
+ theta_CA1_upper = get_upper(theta_CA1)
520
+ theta_CA1_lower = theta_CA1_upper - np.pi / 2
521
+ if theta_CA1_upper < np.pi and theta_CA1_upper > -np.pi/2:
522
+ theta1_lower = theta_CA1_upper - np.pi / 2
523
+ position_CA = True if theta_CA1_upper > theta_CA2 > theta1_lower else False
524
+ else: # 135~180和-180~-135的情况
525
+ position_CA = True if theta_CA2 < -3/4*np.pi or theta_CA2 > 3/4*np.pi else False
526
+
527
+
528
+ theta_CB1_upper = get_upper(theta_CB1)
529
+ theta_CB1_lower = theta_CB1_upper - np.pi / 2
530
+ if theta_CB1_upper < np.pi and theta_CB1_upper > -np.pi/2:
531
+ theta1_lower = theta_CB1_upper - np.pi / 2
532
+ position_CB = True if theta_CB1_upper > theta_CB2 > theta1_lower else False
533
+ else: # 135~180和-180~-135的情况
534
+ position_CB = True if theta_CB2 < -3/4*np.pi or theta_CB2 > 3/4*np.pi else False
535
+
536
+
537
+ position = position_CA and position_CB
538
+
539
+
540
+ max_angle = 30
541
+ # angle_rad_AC = np.arccos(np.clip(np.dot(A_rotation_matrix.T[0], np.array([1,0,0])), -1.0, 1.0))
542
+ # angle_rad_BC = np.arccos(np.clip(np.dot(B_rotation_matrix.T[0], np.array([1,0,0])), -1.0, 1.0))
543
+ # same_direction_AC = angle_rad_AC < max_angle / 180 * np.pi
544
+ # same_direction_BC = angle_rad_BC < max_angle / 180 * np.pi
545
+ # same_direction = same_direction_AC and same_direction_BC
546
+
547
+
548
+ angle_rad_C = np.arccos(np.clip(np.dot(C_rotation_matrix.T[0], np.array([-1,0,0])), -1.0, 1.0))
549
+ direction = angle_rad_C < max_angle / 180 * np.pi
550
+
551
+
552
+ check = position and direction
553
+ question_template = f"Are [A], [B] and [C] maintaining their original relative relationship when viewed from the left of [C]?"
554
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc).replace("[C]", C_desc)
555
+ answer = "Yes" if check else "No"
556
+
557
+ score = 0
558
+ if check:
559
+ score = 1
560
+ else:
561
+ if position_CA:
562
+ w1 = 1
563
+ else:
564
+ if theta_CA1_upper < np.pi and theta_CA1_upper > -np.pi/2:
565
+ w1 = 1 - np.min([np.abs(theta_CA1_upper-theta_CA2), np.abs(theta_CA2-theta_CA1_lower)]) / (np.pi / 6) # 30度的阈值
566
+ else: # 135~180和-180~-135的情况
567
+ theta_CA2 = theta_CA2 + 2 * np.pi if theta_CA2 < -3/4*np.pi else theta_CA2
568
+ w1 = 1 - np.min([np.abs(1.25*np.pi-theta_CA2), np.abs(theta_CA2-0.75*np.pi)]) / (np.pi / 6) # 30度的阈值
569
+
570
+ if position_CB:
571
+ w2 = 1
572
+ else:
573
+ if theta_CB1_upper < np.pi and theta_CB1_upper > -np.pi/2:
574
+ w2 = 1 - np.min([np.abs(theta_CB1_upper-theta_CB2), np.abs(theta_CB2-theta_CB1_lower)]) / (np.pi / 6)
575
+ else: # 135~180和-180~-135的情况
576
+ theta_CB2 = theta_CB2 + 2 * np.pi if theta_CB2 < -3/4*np.pi else theta_CB2
577
+ w2 = 1 - np.min([np.abs(1.25*np.pi-theta_CB2), np.abs(theta_CB2-0.75*np.pi)]) / (np.pi / 6) # 30度的阈值
578
+
579
+ if direction:
580
+ w3 = 1
581
+ else:
582
+ w3 = 1 - np.abs(angle_rad_C - max_angle / 180 * np.pi) / (np.pi / 6) # 30度的阈值
583
+ score = 0 if w1<0 or w2<0 or w3<0 else w1 * w2 * w3
584
+
585
+ return question, answer, check, score
586
+
587
+ def CR_three_right(A, B, C):
588
+ A_desc, A_cloud = A["caption"], A["pcd"]
589
+ A_desc = A_desc.lower()
590
+ B_desc, B_cloud = B["caption"], B["pcd"]
591
+ B_desc = B_desc.lower()
592
+ C_desc, C_cloud = C["caption"], C["pcd"]
593
+ C_desc = C_desc.lower()
594
+
595
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
596
+ A_pos = A_cloud.get_center()
597
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
598
+ B_pos = B_cloud.get_center()
599
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
600
+ C_pos = C_cloud.get_center()
601
+ C_pos[0] = -C_pos[0]; C_pos[1] = -C_pos[1]
602
+
603
+
604
+ A_rotation_matrix = A["rotation_matrix"]
605
+ B_rotation_matrix = B["rotation_matrix"]
606
+ C_rotation_matrix = C["rotation_matrix"]
607
+
608
+ A_rotation_matrix = C_rotation_matrix.T @ A_rotation_matrix # 在C的坐标系下,A的旋转矩阵
609
+ B_rotation_matrix = C_rotation_matrix.T @ B_rotation_matrix # 在C的坐标系下,B的旋转矩阵
610
+
611
+ C_P_A = C_rotation_matrix.T @ (A_pos - C_pos) # 在C的坐标系下,A相对于C的位置
612
+ C_P_B = C_rotation_matrix.T @ (B_pos - C_pos) # 在C的坐标系下,B相对于C的位置
613
+ C_P_A_last = C['C_P_A']
614
+ C_P_B_last = C['C_P_B']
615
+
616
+ theta_CA1 = np.arctan2(C_P_A[2], C_P_A[0])
617
+ theta_CB1 = np.arctan2(C_P_B[2], C_P_B[0])
618
+ theta_CA2 = np.arctan2(C_P_A_last[2], C_P_A_last[0])
619
+ theta_CB2 = np.arctan2(C_P_B_last[2], C_P_B_last[0])
620
+
621
+ theta_CA1_upper = get_upper(theta_CA1)
622
+ theta_CA1_lower = theta_CA1_upper - np.pi / 2
623
+ if theta_CA1_upper < np.pi and theta_CA1_upper > -np.pi/2:
624
+ theta1_lower = theta_CA1_upper - np.pi / 2
625
+ position_CA = True if theta_CA1_upper > theta_CA2 > theta1_lower else False
626
+ else: # 135~180和-180~-135的情况
627
+ position_CA = True if theta_CA2 < -3/4*np.pi or theta_CA2 > 3/4*np.pi else False
628
+
629
+
630
+ theta_CB1_upper = get_upper(theta_CB1)
631
+ theta_CB1_lower = theta_CB1_upper - np.pi / 2
632
+ if theta_CB1_upper < np.pi and theta_CB1_upper > -np.pi/2:
633
+ theta1_lower = theta_CB1_upper - np.pi / 2
634
+ position_CB = True if theta_CB1_upper > theta_CB2 > theta1_lower else False
635
+ else: # 135~180和-180~-135的情况
636
+ position_CB = True if theta_CB2 < -3/4*np.pi or theta_CB2 > 3/4*np.pi else False
637
+
638
+
639
+ position = position_CA and position_CB
640
+
641
+
642
+ max_angle = 30
643
+ # angle_rad_AC = np.arccos(np.clip(np.dot(A_rotation_matrix.T[0], np.array([1,0,0])), -1.0, 1.0))
644
+ # angle_rad_BC = np.arccos(np.clip(np.dot(B_rotation_matrix.T[0], np.array([1,0,0])), -1.0, 1.0))
645
+ # same_direction_AC = angle_rad_AC < max_angle / 180 * np.pi
646
+ # same_direction_BC = angle_rad_BC < max_angle / 180 * np.pi
647
+ # same_direction = same_direction_AC and same_direction_BC
648
+
649
+
650
+ angle_rad_C = np.arccos(np.clip(np.dot(C_rotation_matrix.T[0], np.array([1,0,0])), -1.0, 1.0))
651
+ direction = angle_rad_C < max_angle / 180 * np.pi
652
+
653
+
654
+ check = position and direction
655
+ question_template = f"Are [A], [B] and [C] maintaining their original relative relationship when viewed from the right of [C]?"
656
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc).replace("[C]", C_desc)
657
+ answer = "Yes" if check else "No"
658
+
659
+ score = 0
660
+ if check:
661
+ score = 1
662
+ else:
663
+ if position_CA:
664
+ w1 = 1
665
+ else:
666
+ if theta_CA1_upper < np.pi and theta_CA1_upper > -np.pi/2:
667
+ w1 = 1 - np.min([np.abs(theta_CA1_upper-theta_CA2), np.abs(theta_CA2-theta_CA1_lower)]) / (np.pi / 6) # 30度的阈值
668
+ else: # 135~180和-180~-135的情况
669
+ theta_CA2 = theta_CA2 + 2 * np.pi if theta_CA2 < -3/4*np.pi else theta_CA2
670
+ w1 = 1 - np.min([np.abs(1.25*np.pi-theta_CA2), np.abs(theta_CA2-0.75*np.pi)]) / (np.pi / 6) # 30度的阈值
671
+
672
+ if position_CB:
673
+ w2 = 1
674
+ else:
675
+ if theta_CB1_upper < np.pi and theta_CB1_upper > -np.pi/2:
676
+ w2 = 1 - np.min([np.abs(theta_CB1_upper-theta_CB2), np.abs(theta_CB2-theta_CB1_lower)]) / (np.pi / 6)
677
+ else: # 135~180和-180~-135的情况
678
+ theta_CB2 = theta_CB2 + 2 * np.pi if theta_CB2 < -3/4*np.pi else theta_CB2
679
+ w2 = 1 - np.min([np.abs(1.25*np.pi-theta_CB2), np.abs(theta_CB2-0.75*np.pi)]) / (np.pi / 6) # 30度的阈值
680
+
681
+ if direction:
682
+ w3 = 1
683
+ else:
684
+ w3 = 1 - np.abs(angle_rad_C - max_angle / 180 * np.pi) / (np.pi / 6) # 30度的阈值
685
+ score = 0 if w1<0 or w2<0 or w3<0 else w1 * w2 * w3
686
+
687
+ return question, answer, check, score
processor/prompt_ImageEditbench.py ADDED
@@ -0,0 +1,1055 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ from itertools import combinations
3
+
4
+ import numpy as np
5
+ from osdsynth.processor.pointcloud import calculate_distances_between_point_clouds, human_like_distance
6
+ # from osdsynth.processor.prompt_template import *
7
+ from osdsynth.processor.prompt_utils import *
8
+ # from osdsynth.processor.prompt_spatitalbench_template import *
9
+ from osdsynth.processor.prompt import *
10
+ import torch
11
+
12
+ def camera_to_front_camera_center(A):
13
+ A_desc, A_cloud = A["caption"], A["pcd"]
14
+ A_desc = A_desc.lower()
15
+
16
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
17
+ A_pos = A_cloud.get_center()
18
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
19
+
20
+ A_rotation_matrix = A["rotation_matrix"]
21
+
22
+ max_angle = 30
23
+ angle_rad = np.arccos(np.clip(np.dot(A_rotation_matrix.T[0], np.array([0,0,-1])), -1.0, 1.0))
24
+ is_front_view = angle_rad < max_angle / 180 * np.pi
25
+
26
+ check = is_front_view
27
+
28
+ question_template = f"Is the camera facing the front of [A]?"
29
+ question = question_template.replace("[A]", A_desc)
30
+
31
+ answer = "Yes" if check else "No"
32
+
33
+ score = 0
34
+ if check:
35
+ score = 1
36
+ else:
37
+ score = 1 - 1*np.abs((angle_rad*180/np.pi - max_angle) / (45))
38
+ score = 0 if score < 0 else score
39
+
40
+ return question, answer, check, score
41
+
42
+ def camera_to_left_camera_center(A):
43
+ A_desc, A_cloud = A["caption"], A["pcd"]
44
+ A_desc = A_desc.lower()
45
+
46
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
47
+ A_pos = A_cloud.get_center()
48
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
49
+
50
+ A_rotation_matrix = A["rotation_matrix"]
51
+
52
+ max_angle = 30
53
+ angle_rad = np.arccos(np.clip(np.dot(-A_rotation_matrix.T[2], np.array([0,0,-1])), -1.0, 1.0))
54
+ is_left_view = angle_rad < max_angle / 180 * np.pi
55
+
56
+ check = is_left_view
57
+
58
+ question_template = f"Is the camera facing the left of [A]?"
59
+ question = question_template.replace("[A]", A_desc)
60
+
61
+ answer = "Yes" if check else "No"
62
+
63
+ score = 0
64
+ if check:
65
+ score = 1
66
+ else:
67
+ score = 1 - 1*np.abs((angle_rad*180/np.pi - max_angle) / (45))
68
+ score = 0 if score < 0 else score
69
+
70
+ return question, answer, check, score
71
+
72
+ def camera_to_right_camera_center(A):
73
+ A_desc, A_cloud = A["caption"], A["pcd"]
74
+ A_desc = A_desc.lower()
75
+
76
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
77
+ A_pos = A_cloud.get_center()
78
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
79
+
80
+ A_rotation_matrix = A["rotation_matrix"]
81
+
82
+ max_angle = 30
83
+ angle_rad = np.arccos(np.clip(np.dot(A_rotation_matrix.T[2], np.array([0,0,-1])), -1.0, 1.0))
84
+ is_right_view = angle_rad < max_angle / 180 * np.pi
85
+
86
+ check = is_right_view
87
+
88
+ question_template = f"Is the camera facing the right of [A]?"
89
+ question = question_template.replace("[A]", A_desc)
90
+
91
+ answer = "Yes" if check else "No"
92
+
93
+ score = 0
94
+ if check:
95
+ score = 1
96
+ else:
97
+ score = 1 - 1*np.abs((angle_rad*180/np.pi - max_angle) / (45))
98
+ score = 0 if score < 0 else score
99
+
100
+ return question, answer, check, score
101
+
102
+ def camera_to_back_camera_center(A):
103
+ A_desc, A_cloud = A["caption"], A["pcd"]
104
+ A_desc = A_desc.lower()
105
+
106
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
107
+ A_pos = A_cloud.get_center()
108
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
109
+
110
+ A_rotation_matrix = A["rotation_matrix"]
111
+
112
+ max_angle = 30
113
+ angle_rad = np.arccos(np.clip(np.dot(-A_rotation_matrix.T[0], np.array([0,0,-1])), -1.0, 1.0))
114
+ is_back_view = angle_rad < max_angle / 180 * np.pi
115
+
116
+ check = is_back_view
117
+
118
+ question_template = f"Is the camera facing the back of [A]?"
119
+ question = question_template.replace("[A]", A_desc)
120
+
121
+ answer = "Yes" if check else "No"
122
+
123
+ score = 0
124
+ if check:
125
+ score = 1
126
+ else:
127
+ score = 1 - 1*np.abs((angle_rad*180/np.pi - max_angle) / (45))
128
+ score = 0 if score < 0 else score
129
+
130
+ return question, answer, check, score
131
+
132
+ def camera_to_front_object_center(A):
133
+ A_desc, A_cloud = A["caption"], A["pcd"]
134
+ A_desc = A_desc.lower()
135
+
136
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
137
+ A_pos = A_cloud.get_center()
138
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
139
+
140
+ A_rotation_matrix = A["rotation_matrix"]
141
+ max_angle = 30
142
+ angle_rad = np.arccos(np.clip(np.dot(A_rotation_matrix.T[0], np.array([0,0,-1])), -1.0, 1.0))
143
+ is_front_view = angle_rad < max_angle / 180 * np.pi
144
+
145
+ check = is_front_view
146
+
147
+ question_template = f"Is the camera facing the front of [A]?"
148
+ question = question_template.replace("[A]", A_desc)
149
+
150
+ answer = "Yes" if check else "No"
151
+
152
+ score = 0
153
+ if check:
154
+ score = 1
155
+ else:
156
+ score = 1 - 1*np.abs((angle_rad*180/np.pi - max_angle) / (45))
157
+ score = 0 if score < 0 else score
158
+
159
+ return question, answer, check, score
160
+
161
+ def camera_to_left_object_center(A):
162
+ A_desc, A_cloud = A["caption"], A["pcd"]
163
+ A_desc = A_desc.lower()
164
+
165
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
166
+ A_pos = A_cloud.get_center()
167
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
168
+
169
+ A_rotation_matrix = A["rotation_matrix"]
170
+
171
+ max_angle = 30
172
+ angle_rad = np.arccos(np.clip(np.dot(-A_rotation_matrix.T[2], np.array([0,0,-1])), -1.0, 1.0))
173
+ is_left_view = angle_rad < max_angle / 180 * np.pi
174
+
175
+ check = is_left_view
176
+
177
+ question_template = f"Is the camera facing the left of [A]?"
178
+ question = question_template.replace("[A]", A_desc)
179
+
180
+ answer = "Yes" if check else "No"
181
+
182
+ score = 0
183
+ if check:
184
+ score = 1
185
+ else:
186
+ score = 1 - 1*np.abs((angle_rad*180/np.pi - max_angle) / (45))
187
+ score = 0 if score < 0 else score
188
+
189
+ return question, answer, check, score
190
+
191
+ def camera_to_right_object_center(A):
192
+ A_desc, A_cloud = A["caption"], A["pcd"]
193
+ A_desc = A_desc.lower()
194
+
195
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
196
+ A_pos = A_cloud.get_center()
197
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
198
+
199
+ A_rotation_matrix = A["rotation_matrix"]
200
+
201
+ max_angle = 30
202
+ angle_rad = np.arccos(np.clip(np.dot(A_rotation_matrix.T[2], np.array([0,0,-1])), -1.0, 1.0))
203
+ is_right_view = angle_rad < max_angle / 180 * np.pi
204
+
205
+ check = is_right_view
206
+
207
+ question_template = f"Is the camera facing the right of [A]?"
208
+ question = question_template.replace("[A]", A_desc)
209
+
210
+ answer = "Yes" if check else "No"
211
+
212
+ score = 0
213
+ if check:
214
+ score = 1
215
+ else:
216
+ score = 1 - 1*np.abs((angle_rad*180/np.pi - max_angle) / (45))
217
+ score = 0 if score < 0 else score
218
+
219
+ return question, answer, check, score
220
+
221
+ def camera_to_back_object_center(A):
222
+ A_desc, A_cloud = A["caption"], A["pcd"]
223
+ A_desc = A_desc.lower()
224
+
225
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
226
+ A_pos = A_cloud.get_center()
227
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
228
+
229
+ A_rotation_matrix = A["rotation_matrix"]
230
+
231
+ max_angle = 30
232
+ angle_rad = np.arccos(np.clip(np.dot(-A_rotation_matrix.T[0], np.array([0,0,-1])), -1.0, 1.0))
233
+ is_back_view = angle_rad < max_angle / 180 * np.pi
234
+
235
+ check = is_back_view
236
+
237
+ question_template = f"Is the camera facing the back of [A]?"
238
+ question = question_template.replace("[A]", A_desc)
239
+
240
+ answer = "Yes" if check else "No"
241
+
242
+ score = 0
243
+ if check:
244
+ score = 1
245
+ else:
246
+ score = 1 - 1*np.abs((angle_rad*180/np.pi - max_angle) / (45))
247
+ score = 0 if score < 0 else score
248
+
249
+ return question, answer, check, score
250
+
251
+ def object_insert_side_by_side_same_orientation(A, B):
252
+ A_desc, A_cloud = A["caption"], A["pcd"]
253
+ B_desc, B_cloud = B["caption"], B["pcd"]
254
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
255
+
256
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
257
+ A_pos = A_cloud.get_center()
258
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
259
+
260
+ B_pos = B_cloud.get_center()
261
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
262
+
263
+ # A_rotation_matrix = A["rotation_matrix"]
264
+ B_rotation_matrix = B["rotation_matrix"]
265
+ B_P_A = B_rotation_matrix.T @ (A_pos - B_pos) # 在B物体参考系下,A物体的位置
266
+ A_rotation_matrix = B_rotation_matrix.T @ A["rotation_matrix"]
267
+
268
+ is_side_by_side = np.abs(np.arctan(B_P_A[2]/ B_P_A[0])) > np.pi * 1 / 3
269
+
270
+ # 比较X轴的夹角
271
+ max_angle = 30
272
+ angle_rad = np.arccos(np.clip(np.dot(A_rotation_matrix.T[0], np.array([1,0,0])), -1.0, 1.0))
273
+ is_same_orientation = angle_rad < max_angle / 180 * np.pi
274
+
275
+ check = is_same_orientation and is_side_by_side
276
+
277
+ print("is_same_orientation", is_same_orientation, "is_side_by_side", is_side_by_side)
278
+ question_template = f"Is [A] and [B] side by side, facing the same direction?"
279
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
280
+ answer = "Yes" if check else "No"
281
+
282
+ score = 0
283
+ if check:
284
+ score = 1
285
+ else:
286
+ if is_same_orientation:
287
+ w1 = 1
288
+ else:
289
+ w1 = 1 - 1*np.abs((angle_rad*180/np.pi - max_angle) / (45))
290
+
291
+ if is_side_by_side:
292
+ w2 = 1
293
+ else:
294
+ w2 = 1 - 1*np.abs((np.abs(np.arctan(B_P_A[2]/ B_P_A[0])) - np.pi * 1 / 3) / (np.pi/12))
295
+ score = 0 if w1 < 0 or w2<0 else w1*w2
296
+ if w1 == 1:
297
+ score = 0.5
298
+ return question, answer, check, score
299
+
300
+ def object_insert_side_by_side_opposite_orientation(A, B):
301
+ A_desc, A_cloud = A["caption"], A["pcd"]
302
+ B_desc, B_cloud = B["caption"], B["pcd"]
303
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
304
+
305
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
306
+ A_pos = A_cloud.get_center()
307
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
308
+
309
+ B_pos = B_cloud.get_center()
310
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
311
+
312
+ # A_rotation_matrix = A["rotation_matrix"]
313
+ B_rotation_matrix = B["rotation_matrix"]
314
+ B_P_A = B_rotation_matrix.T @ (A_pos - B_pos) # 在B物体参考系下,A物体的位置
315
+ A_rotation_matrix = B_rotation_matrix.T @ A["rotation_matrix"]
316
+
317
+ is_side_by_side = np.abs(np.arctan(B_P_A[2]/ B_P_A[0])) > np.pi * 1 / 3
318
+ # 比较X轴的夹角
319
+ max_angle = 30
320
+ angle_rad = np.arccos(np.clip(np.dot(A_rotation_matrix.T[0], np.array([-1,0,0])), -1.0, 1.0))
321
+ is_opposite_orientation = angle_rad < max_angle / 180 * np.pi
322
+
323
+ check = is_opposite_orientation and is_side_by_side
324
+
325
+ print("is_opposite_orientation", is_opposite_orientation, "is_side_by_side", is_side_by_side)
326
+ question_template = f"Is [A] and [B] side by side, facing the opposite direction?"
327
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
328
+ answer = "Yes" if check else "No"
329
+
330
+ score = 0
331
+ if check:
332
+ score = 1
333
+ else:
334
+ if is_opposite_orientation:
335
+ w1 = 1
336
+ else:
337
+ w1 = 1 - 1*np.abs((angle_rad*180/np.pi - max_angle) / (45))
338
+ if is_side_by_side:
339
+ w2 = 1
340
+ else:
341
+ w2 = 1 - 1*np.abs((np.abs(np.arctan(B_P_A[2]/ B_P_A[0])) - np.pi * 1 / 3) / (np.pi/12))
342
+ score = 0 if w1 < 0 or w2<0 else w1*w2
343
+ if w1 == 1:
344
+ score = 0.5
345
+ return question, answer, check, score
346
+
347
+ def object_insert_face_to_face(A, B):
348
+ A_desc, A_cloud = A["caption"], A["pcd"]
349
+ B_desc, B_cloud = B["caption"], B["pcd"]
350
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
351
+
352
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
353
+ A_pos = A_cloud.get_center()
354
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
355
+
356
+ B_pos = B_cloud.get_center()
357
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
358
+
359
+ # A_rotation_matrix = A["rotation_matrix"]
360
+ B_rotation_matrix = B["rotation_matrix"]
361
+ B_P_A = B_rotation_matrix.T @ (A_pos - B_pos) # 在B物体参考系下,A物体的位置
362
+ A_rotation_matrix = B_rotation_matrix.T @ A["rotation_matrix"]
363
+
364
+
365
+ is_line = B_P_A[0] > 0 and np.abs(np.arctan(B_P_A[2]/ B_P_A[0])) < np.pi/3# 在一条线上,且A在B的前面
366
+
367
+ max_angle = 30
368
+ angle_rad = np.arccos(np.clip(np.dot(A_rotation_matrix.T[0], [-1,0,0]), -1.0, 1.0))
369
+ is_opposite_orientation = angle_rad < max_angle / 180 * np.pi
370
+
371
+ check = is_opposite_orientation and is_line
372
+
373
+ print("is_opposite_orientation", is_opposite_orientation, "is_line", is_line)
374
+ question_template = f"Is [A] and [B] face to face?"
375
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
376
+
377
+ answer = "Yes" if check else "No"
378
+
379
+ score = 0
380
+ if check:
381
+ score = 1
382
+ else:
383
+ if is_opposite_orientation:
384
+ w1 = 1
385
+ else:
386
+ w1 = 1 - 1*np.abs((angle_rad*180/np.pi - max_angle) / (45))
387
+ if is_line:
388
+ w2 = 1
389
+ else:
390
+ w2 = 1 - 1*np.abs((np.abs(np.arctan(B_P_A[2]/ B_P_A[0])) - np.pi * 1 / 3) / (np.pi/12))
391
+ if B_P_A[0] < 0 or np.abs(np.arctan(B_P_A[2]/ B_P_A[0])) > np.pi/3:
392
+ w2 = 0
393
+ score = 0 if w1<0 or w2<0 else w1*w2
394
+ if w1 == 1:
395
+ score = 0.5
396
+ return question, answer, check, score
397
+
398
+ def object_insert_back_to_back(A, B):
399
+ A_desc, A_cloud = A["caption"], A["pcd"]
400
+ B_desc, B_cloud = B["caption"], B["pcd"]
401
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
402
+
403
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
404
+ A_pos = A_cloud.get_center()
405
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
406
+
407
+ B_pos = B_cloud.get_center()
408
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
409
+
410
+ # A_rotation_matrix = A["rotation_matrix"]
411
+ B_rotation_matrix = B["rotation_matrix"]
412
+ B_P_A = B_rotation_matrix.T @ (A_pos - B_pos) # 在B物体参考系下,A物体的位置
413
+ A_rotation_matrix = B_rotation_matrix.T @ A["rotation_matrix"]
414
+
415
+
416
+ is_line = B_P_A[0] < 0 and np.abs(np.arctan(B_P_A[2]/ B_P_A[0])) < np.pi/3# 在一条线上,且A在B的前面
417
+
418
+ max_angle = 30
419
+ angle_rad = np.arccos(np.clip(np.dot(A_rotation_matrix.T[0], [-1,0,0]), -1.0, 1.0))
420
+ is_opposite_orientation = angle_rad < max_angle / 180 * np.pi
421
+
422
+ check = is_opposite_orientation and is_line
423
+
424
+ print("is_opposite_orientation", is_opposite_orientation, "is_line", is_line)
425
+ question_template = f"Is [A] and [B] back to back?"
426
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
427
+
428
+ answer = "Yes" if check else "No"
429
+
430
+ score = 0
431
+ if check:
432
+ score = 1
433
+ else:
434
+ if is_opposite_orientation:
435
+ w1 = 1
436
+ else:
437
+ w1 = 1 - 1*np.abs((angle_rad*180/np.pi - max_angle) / (45))
438
+ if is_line:
439
+ w2 = 1
440
+ else:
441
+ w2 = 1 - 1*np.abs((np.abs(np.arctan(B_P_A[2]/ B_P_A[0])) - np.pi * 1 / 3) / (np.pi/12))
442
+ if B_P_A[0] > 0 or np.abs(np.arctan(B_P_A[2]/ B_P_A[0])) > np.pi/3:
443
+ w2 = 0
444
+ score = 0 if w1<0 or w2<0 else w1*w2
445
+ if w1 == 1:
446
+ score = 0.5
447
+ return question, answer, check, score
448
+
449
+ def object_insert_front_object_center(A, B):
450
+ A_desc, A_cloud = A["caption"], A["pcd"]
451
+ B_desc, B_cloud = B["caption"], B["pcd"]
452
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
453
+
454
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
455
+ A_pos = A_cloud.get_center()
456
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
457
+
458
+ B_pos = B_cloud.get_center()
459
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
460
+
461
+ A_rotation_matrix = A["rotation_matrix"]
462
+ # B_rotation_matrix = B["rotation_matrix"]
463
+ A_P_B = A_rotation_matrix.T @ (B_pos - A_pos) # 在A物体参考系下,A物体的位置
464
+
465
+
466
+ is_front = A_P_B[0] > 0
467
+
468
+ check = is_front
469
+
470
+ question_template = f"Is [B] in front of [A]?"
471
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
472
+
473
+ answer = "Yes" if check else "No"
474
+
475
+ score = 0
476
+ if check:
477
+ score = 1
478
+
479
+ return question, answer, check, score
480
+
481
+ def object_insert_left_object_center(A, B):
482
+ A_desc, A_cloud = A["caption"], A["pcd"]
483
+ B_desc, B_cloud = B["caption"], B["pcd"]
484
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
485
+
486
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
487
+ A_pos = A_cloud.get_center()
488
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
489
+
490
+ B_pos = B_cloud.get_center()
491
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
492
+
493
+ A_rotation_matrix = A["rotation_matrix"]
494
+ # B_rotation_matrix = B["rotation_matrix"]
495
+ A_P_B = A_rotation_matrix.T @ (B_pos - A_pos) # 在A物体参考系下,A物体的位置
496
+
497
+ max_angle = 30
498
+ A_P_B_direcetion = A_P_B / np.linalg.norm(A_P_B)
499
+ angle_rad = np.arccos(np.clip(np.dot(A_P_B_direcetion, np.array([0,0,-1])), -1.0, 1.0))
500
+ B_is_in_left_A = A_P_B[2] < 0 and angle_rad < max_angle / 180 * np.pi# 在一条线上,且A在B的前面
501
+
502
+ is_left = A_P_B[2] < 0 and B_is_in_left_A
503
+
504
+ check = is_left
505
+
506
+ question_template = f"Is [B] in the left of [A]?"
507
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
508
+
509
+ answer = "Yes" if check else "No"
510
+
511
+ score = 0
512
+ if check:
513
+ score = 1
514
+ else:
515
+ score = 1 - 1*np.abs((angle_rad*180/np.pi - max_angle) / (45))
516
+ score = 0 if score < 0 or A_P_B[2] > 0 else score
517
+
518
+ return question, answer, check, score
519
+
520
+ def object_insert_right_object_center(A, B):
521
+ A_desc, A_cloud = A["caption"], A["pcd"]
522
+ B_desc, B_cloud = B["caption"], B["pcd"]
523
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
524
+
525
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
526
+ A_pos = A_cloud.get_center()
527
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
528
+
529
+ B_pos = B_cloud.get_center()
530
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
531
+
532
+ A_rotation_matrix = A["rotation_matrix"]
533
+ # B_rotation_matrix = B["rotation_matrix"]
534
+ A_P_B = A_rotation_matrix.T @ (B_pos - A_pos) # 在A物体参考系下,A物体的位置
535
+
536
+ max_angle = 30
537
+ A_P_B_direcetion = A_P_B / np.linalg.norm(A_P_B)
538
+ angle_rad = np.arccos(np.clip(np.dot(A_P_B_direcetion, np.array([0,0,1])), -1.0, 1.0))
539
+ B_is_in_right_A = A_P_B[2] > 0 and angle_rad < max_angle / 180 * np.pi# 在一条线上,且A在B的前面
540
+
541
+ is_right = A_P_B[2] > 0 and B_is_in_right_A
542
+
543
+ check = is_right
544
+
545
+ question_template = f"Is [B] in the right of [A]?"
546
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
547
+
548
+ answer = "Yes" if check else "No"
549
+
550
+ score = 0
551
+ if check:
552
+ score = 1
553
+ else:
554
+ score = 1 - 1*np.abs((angle_rad*180/np.pi - max_angle) / (45))
555
+ score = 0 if score < 0 or A_P_B[2] < 0 else score
556
+
557
+ return question, answer, check, score
558
+
559
+ def object_insert_behind_object_center(A, B):
560
+ A_desc, A_cloud = A["caption"], A["pcd"]
561
+ B_desc, B_cloud = B["caption"], B["pcd"]
562
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
563
+
564
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
565
+ A_pos = A_cloud.get_center()
566
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
567
+
568
+ B_pos = B_cloud.get_center()
569
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
570
+
571
+ A_rotation_matrix = A["rotation_matrix"]
572
+ # B_rotation_matrix = B["rotation_matrix"]
573
+ A_P_B = A_rotation_matrix.T @ (B_pos - A_pos) # 在A物体参考系下,A物体的位置
574
+
575
+ is_behind = A_P_B[0] < 0
576
+
577
+ check = is_behind
578
+
579
+ question_template = f"Is [B] behind [A]?"
580
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
581
+
582
+ answer = "Yes" if check else "No"
583
+
584
+ score = 0
585
+ if check:
586
+ score = 1
587
+
588
+ return question, answer, check, score
589
+
590
+
591
+ ## 描述物体
592
+ # 定性
593
+
594
+ def object_insert_front_camera_center(A, B):
595
+ A_desc, A_cloud = A["caption"], A["pcd"]
596
+ B_desc, B_cloud = B["caption"], B["pcd"]
597
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
598
+
599
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
600
+ A_pos = A_cloud.get_center()
601
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
602
+
603
+ B_pos = B_cloud.get_center()
604
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
605
+
606
+ is_front = B_pos[2] < A_pos[2]
607
+
608
+ check = is_front
609
+
610
+ question_template = f"Is [B] in front of [A]?"
611
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
612
+
613
+ answer = "Yes" if check else "No"
614
+
615
+ score = 0
616
+ if check:
617
+ score = 1
618
+
619
+ return question, answer, check, score
620
+
621
+ def object_insert_left_camera_center(A, B):
622
+ A_desc, A_cloud = A["caption"], A["pcd"]
623
+ B_desc, B_cloud = B["caption"], B["pcd"]
624
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
625
+
626
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
627
+ A_pos = A_cloud.get_center()
628
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
629
+
630
+ B_pos = B_cloud.get_center()
631
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
632
+
633
+
634
+ is_left = B_pos[0] < A_pos[0]
635
+
636
+ check = is_left
637
+
638
+ question_template = f"Is [B] in left of [A]?"
639
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
640
+
641
+ answer = "Yes" if check else "No"
642
+
643
+ score = 0
644
+ if check:
645
+ score = 1
646
+
647
+ return question, answer, check, score
648
+
649
+ def object_insert_right_camera_center(A, B):
650
+ A_desc, A_cloud = A["caption"], A["pcd"]
651
+ B_desc, B_cloud = B["caption"], B["pcd"]
652
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
653
+
654
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
655
+ A_pos = A_cloud.get_center()
656
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
657
+
658
+ B_pos = B_cloud.get_center()
659
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
660
+
661
+ is_right = B_pos[0] > A_pos[0]
662
+
663
+ check = is_right
664
+
665
+ question_template = f"Is [B] in right of [A]?"
666
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
667
+
668
+ answer = "Yes" if check else "No"
669
+
670
+ score = 0
671
+ if check:
672
+ score = 1
673
+
674
+ return question, answer, check, score
675
+
676
+ def object_insert_behind_camera_center(A, B):
677
+ A_desc, A_cloud = A["caption"], A["pcd"]
678
+ B_desc, B_cloud = B["caption"], B["pcd"]
679
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
680
+
681
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
682
+ A_pos = A_cloud.get_center()
683
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
684
+
685
+ B_pos = B_cloud.get_center()
686
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
687
+
688
+
689
+ is_behind = B_pos[2] > A_pos[2]
690
+
691
+ check = is_behind
692
+
693
+ question_template = f"Is [B] in behind of [A]?"
694
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
695
+
696
+ answer = "Yes" if check else "No"
697
+
698
+ score = 0
699
+ if check:
700
+ score = 1
701
+
702
+ return question, answer, check, score
703
+
704
+ def objectmove_close_1meter(A):
705
+ A_desc, A_cloud = A["caption"], A["pcd"]
706
+
707
+ A_pos = A_cloud.get_center()
708
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
709
+
710
+ distance = A_pos[2] -A['last_pos'][2]
711
+
712
+ delta = 1.0/3
713
+ gt_distance = -1
714
+
715
+ check = (1+delta)*gt_distance < distance and distance < (1-delta)*gt_distance
716
+
717
+ question_template = f"Does [A] move 1 meter close to the camera?"
718
+ question = question_template.replace("[A]", A_desc)
719
+
720
+ answer = "Yes" if check else "No"
721
+
722
+ score = 0
723
+ if check:
724
+ score = 1
725
+ else:
726
+ score = 1 - 1*np.abs(((distance - gt_distance) / gt_distance)- delta)/delta
727
+ score = 0 if score < 0 else score
728
+
729
+ return question, answer, check, score
730
+
731
+ def objectmove_far_1meter(A):
732
+ A_desc, A_cloud = A["caption"], A["pcd"]
733
+
734
+ A_pos = A_cloud.get_center()
735
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
736
+
737
+ distance = A_pos[2] -A['last_pos'][2]
738
+
739
+ delta = 1.0/3
740
+ gt_distance = 1
741
+
742
+ check = (1-delta)*gt_distance < distance and distance < (1+delta)*gt_distance
743
+
744
+ question_template = f"Does [A] move 1 meter far to the camera?"
745
+ question = question_template.replace("[A]", A_desc)
746
+
747
+ answer = "Yes" if check else "No"
748
+
749
+ score = 0
750
+ if check:
751
+ score = 1
752
+ else:
753
+ score = 1 - 1*np.abs(((distance - gt_distance) / gt_distance)- delta)/delta
754
+ score = 0 if score < 0 else score
755
+
756
+ return question, answer, check, score
757
+
758
+ def objectmove_left_1meter(A):
759
+ A_desc, A_cloud = A["caption"], A["pcd"]
760
+
761
+ A_pos = A_cloud.get_center()
762
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
763
+
764
+ distance = A_pos[0] -A['last_pos'][0]
765
+
766
+ delta = 1.0/3
767
+ gt_distance = -1
768
+
769
+ check = (1+delta)*gt_distance < distance and distance < (1-delta)*gt_distance
770
+
771
+ question_template = f"Does [A] move 1 meter left?"
772
+ question = question_template.replace("[A]", A_desc)
773
+
774
+ answer = "Yes" if check else "No"
775
+
776
+ score = 0
777
+ if check:
778
+ score = 1
779
+ else:
780
+ score = 1 - 1*np.abs(((distance - gt_distance) / gt_distance)- delta)/delta
781
+ score = 0 if score < 0 else score
782
+
783
+ return question, answer, check, score
784
+
785
+ def objectmove_right_1meter(A):
786
+ A_desc, A_cloud = A["caption"], A["pcd"]
787
+
788
+ A_pos = A_cloud.get_center()
789
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
790
+
791
+ distance = A_pos[0] -A['last_pos'][0]
792
+
793
+ delta = 1.0/3
794
+ gt_distance = 1
795
+
796
+ check = (1-delta)*gt_distance < distance and distance < (1+delta)*gt_distance
797
+
798
+ question_template = f"Does [A] move 1 meter right?"
799
+ question = question_template.replace("[A]", A_desc)
800
+
801
+ answer = "Yes" if check else "No"
802
+
803
+ score = 0
804
+ if check:
805
+ score = 1
806
+ else:
807
+ score = 1 - 1*np.abs(((distance - gt_distance) / gt_distance)- delta)/delta
808
+ score = 0 if score < 0 else score
809
+
810
+ return question, answer, check, score
811
+
812
+
813
+ def camera_forward_1meter(A):
814
+ A_desc, A_cloud = A["caption"], A["pcd"]
815
+
816
+ A_pos = A_cloud.get_center()
817
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
818
+
819
+ distance = A_pos[2] - A['last_pos'][2]
820
+
821
+ delta = 1.0/3
822
+ gt_distance = -1
823
+
824
+ check = (1+delta)*gt_distance < distance and distance < (1-delta)*gt_distance
825
+
826
+ question_template = f"Does camera move 1 meter forward? [A]"
827
+ question = question_template.replace("[A]", A_desc)
828
+
829
+ answer = "Yes" if check else "No"
830
+
831
+ score = 0
832
+ if check:
833
+ score = 1
834
+ else:
835
+ score = 1 - 1*np.abs(((distance - gt_distance) / gt_distance)- delta)/delta
836
+ score = 0 if score < 0 else score
837
+
838
+ return question, answer, check, score
839
+
840
+ def camera_leftward_1meter(A):
841
+ A_desc, A_cloud = A["caption"], A["pcd"]
842
+
843
+ A_pos = A_cloud.get_center()
844
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
845
+
846
+ distance = A_pos[0] - A['last_pos'][0]
847
+
848
+ delta = 1.0/3
849
+ gt_distance = 1
850
+
851
+ check = (1+delta)*gt_distance < distance and distance < (1-delta)*gt_distance
852
+
853
+ question_template = f"Does camera move 1 meter leftward? [A]"
854
+ question = question_template.replace("[A]", A_desc)
855
+
856
+ answer = "Yes" if check else "No"
857
+
858
+ score = 0
859
+ if check:
860
+ score = 1
861
+ else:
862
+ score = 1 - 1*np.abs(((distance - gt_distance) / gt_distance)- delta)/delta
863
+ score = 0 if score < 0 else score
864
+
865
+ return question, answer, check, score
866
+
867
+ def camera_rightward_1meter(A):
868
+ A_desc, A_cloud = A["caption"], A["pcd"]
869
+
870
+ A_pos = A_cloud.get_center()
871
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
872
+
873
+ distance = A_pos[0] - A['last_pos'][0]
874
+
875
+ delta = 1.0/3
876
+ gt_distance = -1
877
+
878
+ check = (1-delta)*gt_distance < distance and distance < (1+delta)*gt_distance
879
+
880
+ question_template = f"Does camera move 1 meter rightward? [A]"
881
+ question = question_template.replace("[A]", A_desc)
882
+
883
+ answer = "Yes" if check else "No"
884
+
885
+ score = 0
886
+ if check:
887
+ score = 1
888
+ else:
889
+ score = 1 - 1*np.abs(((distance - gt_distance) / gt_distance)- delta)/delta
890
+ score = 0 if score < 0 else score
891
+
892
+ return question, answer, check, score
893
+
894
+ def camera_backward_1meter(A):
895
+ A_desc, A_cloud = A["caption"], A["pcd"]
896
+
897
+ A_pos = A_cloud.get_center()
898
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
899
+
900
+ distance = A_pos[2] - A['last_pos'][2]
901
+
902
+ delta = 1.0/3
903
+ gt_distance = 1
904
+
905
+ check = (1-delta)*gt_distance < distance and distance < (1+delta)*gt_distance
906
+
907
+ question_template = f"Does camera move 1 meter backward? [A]"
908
+ question = question_template.replace("[A]", A_desc)
909
+
910
+ answer = "Yes" if check else "No"
911
+
912
+ score = 0
913
+ if check:
914
+ score = 1
915
+ else:
916
+ score = 1 - 1*np.abs(((distance - gt_distance) / gt_distance)- delta)/delta
917
+ score = 0 if score < 0 else score
918
+
919
+ return question, answer, check, score
920
+
921
+
922
+ # 定量
923
+ def object_make_12bigger(A):
924
+ A_desc, A_cloud = A["caption"], A["pcd"]
925
+
926
+
927
+ A_rotation_matrix = A["rotation_matrix"]
928
+ theta_A = np.arctan2(A_rotation_matrix.T[0][2], A_rotation_matrix.T[0][0])
929
+ A_center = A["pcd"].get_center()
930
+ R = A["pcd"].get_rotation_matrix_from_xyz((0, 0, theta_A))
931
+ A["pcd"] = A["pcd"].rotate(R)
932
+ A_length = A["pcd"].get_axis_aligned_bounding_box().get_extent()[0]
933
+ A_height = A["pcd"].get_axis_aligned_bounding_box().get_extent()[1]
934
+ A_width = A["pcd"].get_axis_aligned_bounding_box().get_extent()[2]
935
+ volume = A_length * A_height * A_width
936
+
937
+ distance = volume / A['last_volume'] - 1
938
+
939
+ delta = 1.0/3
940
+ gt_distance = 0.2
941
+
942
+ check = (1-delta)*gt_distance < distance and distance < (1+delta)*gt_distance
943
+
944
+ question_template = f"Does [A] become 1.5 times its initial dimensions.?"
945
+ question = question_template.replace("[A]", A_desc)
946
+
947
+ answer = "Yes" if check else "No"
948
+
949
+ score = 0
950
+ if check:
951
+ score = 1
952
+ else:
953
+ score = 1 - 1*np.abs(((distance - gt_distance) / gt_distance)- delta)/delta
954
+ score = 0 if score < 0 else score
955
+
956
+ return question, answer, check, score
957
+
958
+ def object_make_20cm_higher(A):
959
+ A_desc, A_cloud = A["caption"], A["pcd"]
960
+ A_desc = A_desc.lower()
961
+
962
+ # 计算距离
963
+
964
+ height = A["pcd"].get_axis_aligned_bounding_box().get_extent()[1]
965
+ last_height = A["last_height"]
966
+ distance = height-last_height
967
+
968
+ delta = 1.0/3
969
+ gt_distance = 0.2
970
+
971
+ check = (1-delta)*gt_distance < distance and distance < (1+delta)*gt_distance
972
+
973
+ question_template = f"Is [A] higher 20cm than [B]?"
974
+ question = question_template.replace("[A]", A_desc)
975
+
976
+ answer = "Yes" if check else "No"
977
+
978
+ score = 0
979
+ if check:
980
+ score = 1
981
+ else:
982
+ score = 1 - 1*np.abs(((distance - gt_distance) / gt_distance)- delta)/delta
983
+ score = 0 if score < 0 else score
984
+
985
+ return question, answer, check, score
986
+
987
+ def object_make_50cm_longer(A):
988
+ A_desc, A_cloud = A["caption"], A["pcd"]
989
+ A_desc = A_desc.lower()
990
+
991
+ # 计算距离
992
+
993
+ A_rotation_matrix = A["rotation_matrix"]
994
+ theta_A = np.arctan2(A_rotation_matrix.T[0][2], A_rotation_matrix.T[0][0])
995
+ A_center = A["pcd"].get_center()
996
+ R = A["pcd"].get_rotation_matrix_from_xyz((0, 0, theta_A))
997
+ A["pcd"] = A["pcd"].rotate(R)
998
+ length = A["pcd"].get_axis_aligned_bounding_box().get_extent()[0]
999
+
1000
+ last_length = A["last_length"]
1001
+ distance = length-last_length
1002
+
1003
+ delta = 1.0/3
1004
+ gt_distance = 0.5
1005
+
1006
+ check = (1-delta)*gt_distance < distance and distance < (1+delta)*gt_distance
1007
+
1008
+ question_template = f"Is [A] higher 20cm than [B]?"
1009
+ question = question_template.replace("[A]", A_desc)
1010
+
1011
+ answer = "Yes" if check else "No"
1012
+
1013
+ score = 0
1014
+ if check:
1015
+ score = 1
1016
+ else:
1017
+ score = 1 - 1*np.abs(((distance - gt_distance) / gt_distance)- delta)/delta
1018
+ score = 0 if score < 0 else score
1019
+
1020
+ return question, answer, check, score
1021
+
1022
+ def object_make_40cm_wider(A):
1023
+ A_desc, A_cloud = A["caption"], A["pcd"]
1024
+ A_desc = A_desc.lower()
1025
+
1026
+ # 计算距离
1027
+
1028
+ A_rotation_matrix = A["rotation_matrix"]
1029
+ theta_A = np.arctan2(A_rotation_matrix.T[0][2], A_rotation_matrix.T[0][0])
1030
+ A_center = A["pcd"].get_center()
1031
+ R = A["pcd"].get_rotation_matrix_from_xyz((0, 0, theta_A))
1032
+ A["pcd"] = A["pcd"].rotate(R)
1033
+ width = A["pcd"].get_axis_aligned_bounding_box().get_extent()[2]
1034
+
1035
+ last_width = A["last_width"]
1036
+ distance = width-last_width
1037
+
1038
+ delta = 1.0/3
1039
+ gt_distance = 0.4
1040
+
1041
+ check = (1-delta)*gt_distance < distance and distance < (1+delta)*gt_distance
1042
+
1043
+ question_template = f"Is [A] higher 20cm than [B]?"
1044
+ question = question_template.replace("[A]", A_desc)
1045
+
1046
+ answer = "Yes" if check else "No"
1047
+
1048
+ score = 0
1049
+ if check:
1050
+ score = 1
1051
+ else:
1052
+ score = 1 - 1*np.abs(((distance - gt_distance) / gt_distance)- delta)/delta
1053
+ score = 0 if score < 0 else score
1054
+
1055
+ return question, answer, check, score
processor/prompt_T2Ibench.py ADDED
@@ -0,0 +1,1296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ from itertools import combinations
3
+
4
+ import numpy as np
5
+ from osdsynth.processor.pointcloud import calculate_distances_between_point_clouds, human_like_distance
6
+ # from osdsynth.processor.prompt_template import *
7
+ from osdsynth.processor.prompt_utils import *
8
+ # from osdsynth.processor.prompt_spatitalbench_template import *
9
+ from osdsynth.processor.prompt import *
10
+
11
+ def camera_front_camera_center(A):
12
+ A_desc, A_cloud = A["caption"], A["pcd"]
13
+ A_desc = A_desc.lower()
14
+
15
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
16
+ A_pos = A_cloud.get_center()
17
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
18
+
19
+ A_rotation_matrix = A["rotation_matrix"]
20
+
21
+ max_angle = 15
22
+ angle_rad = np.arccos(np.clip(np.dot(A_rotation_matrix.T[0], np.array([0,0,-1])), -1.0, 1.0))
23
+ is_front = angle_rad < max_angle / 180 * np.pi
24
+
25
+ check = is_front
26
+
27
+ question_template = f"Does the camera face the front of [A]?"
28
+ question = question_template.replace("[A]", A_desc)
29
+
30
+ answer = "Yes" if check else "No"
31
+
32
+ score = 0
33
+ if check:
34
+ score = 1
35
+ else:
36
+ score = 1 - 1*np.abs((angle_rad*180/np.pi-max_angle)/(45-max_angle))
37
+ score = 0 if score < 0 else score
38
+
39
+ return question, answer, check, score
40
+
41
+ def camera_back_camera_center(A):
42
+ A_desc, A_cloud = A["caption"], A["pcd"]
43
+ A_desc = A_desc.lower()
44
+
45
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
46
+ A_pos = A_cloud.get_center()
47
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
48
+
49
+ A_rotation_matrix = A["rotation_matrix"]
50
+
51
+ max_angle = 15
52
+ angle_rad = np.arccos(np.clip(np.dot(-A_rotation_matrix.T[0], np.array([0,0,-1])), -1.0, 1.0))
53
+ is_back = angle_rad < max_angle / 180 * np.pi
54
+
55
+ check = is_back
56
+
57
+ question_template = f"Does the camera face the back of [A]?"
58
+ question = question_template.replace("[A]", A_desc)
59
+
60
+ answer = "Yes" if check else "No"
61
+
62
+ score = 0
63
+ if check:
64
+ score = 1
65
+ else:
66
+ score = 1 - 1*np.abs((angle_rad*180/np.pi-max_angle)/(45-max_angle))
67
+ score = 0 if score < 0 else score
68
+
69
+ return question, answer, check, score
70
+
71
+ def camera_left_camera_center(A):
72
+ A_desc, A_cloud = A["caption"], A["pcd"]
73
+ A_desc = A_desc.lower()
74
+
75
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
76
+ A_pos = A_cloud.get_center()
77
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
78
+
79
+ A_rotation_matrix = A["rotation_matrix"]
80
+
81
+ max_angle = 30
82
+ angle_rad = np.arccos(np.clip(np.dot(-A_rotation_matrix.T[2], np.array([0,0,-1])), -1.0, 1.0))
83
+ is_left = angle_rad < max_angle / 180 * np.pi
84
+
85
+ check = is_left
86
+
87
+ question_template = f"Does the camera face the left of [A]?"
88
+ question = question_template.replace("[A]", A_desc)
89
+
90
+ answer = "Yes" if check else "No"
91
+
92
+ score = 0
93
+ if check:
94
+ score = 1
95
+ else:
96
+ score = 1 - 1*np.abs((angle_rad*180/np.pi-max_angle)/(60-max_angle))
97
+ score = 0 if score < 0 else score
98
+
99
+ return question, answer, check, score
100
+
101
+ def camera_right_camera_center(A):
102
+ A_desc, A_cloud = A["caption"], A["pcd"]
103
+ A_desc = A_desc.lower()
104
+
105
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
106
+ A_pos = A_cloud.get_center()
107
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
108
+
109
+ A_rotation_matrix = A["rotation_matrix"]
110
+
111
+ max_angle = 30
112
+ angle_rad = np.arccos(np.clip(np.dot(A_rotation_matrix.T[2], np.array([0,0,-1])), -1.0, 1.0))
113
+ is_right = angle_rad < max_angle / 180 * np.pi
114
+
115
+ check = is_right
116
+
117
+ question_template = f"Does the camera face the right of [A]?"
118
+ question = question_template.replace("[A]", A_desc)
119
+
120
+ answer = "Yes" if check else "No"
121
+
122
+ score = 0
123
+ if check:
124
+ score = 1
125
+ else:
126
+ score = 1 - 1*np.abs((angle_rad*180/np.pi-max_angle)/(60-max_angle))
127
+ score = 0 if score < 0 else score
128
+
129
+ return question, answer, check, score
130
+
131
+
132
+
133
+ def camera_front_object_center(A):
134
+ A_desc, A_cloud = A["caption"], A["pcd"]
135
+ A_desc = A_desc.lower()
136
+
137
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
138
+ A_pos = A_cloud.get_center()
139
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
140
+
141
+ A_rotation_matrix = A["rotation_matrix"]
142
+
143
+ max_angle = 15
144
+ angle_rad = np.arccos(np.clip(np.dot(A_rotation_matrix.T[0], np.array([0,0,-1])), -1.0, 1.0))
145
+ is_front = angle_rad < max_angle / 180 * np.pi
146
+
147
+ check = is_front
148
+
149
+ question_template = f"Does the camera face the front of [A]?"
150
+ question = question_template.replace("[A]", A_desc)
151
+
152
+ answer = "Yes" if check else "No"
153
+
154
+ score = 0
155
+ if check:
156
+ score = 1
157
+ else:
158
+ score = 1 - 1*np.abs((angle_rad*180/np.pi-max_angle)/(45-max_angle))
159
+ score = 0 if score < 0 else score
160
+
161
+ return question, answer, check, score
162
+
163
+ def camera_back_object_center(A):
164
+ A_desc, A_cloud = A["caption"], A["pcd"]
165
+ A_desc = A_desc.lower()
166
+
167
+ # 从PyTorch3D的坐标系转���到OpenCV的坐标系
168
+ A_pos = A_cloud.get_center()
169
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
170
+
171
+ A_rotation_matrix = A["rotation_matrix"]
172
+
173
+ max_angle = 15
174
+ angle_rad = np.arccos(np.clip(np.dot(-A_rotation_matrix.T[0], np.array([0,0,-1])), -1.0, 1.0))
175
+ is_back = angle_rad < max_angle / 180 * np.pi
176
+
177
+ check = is_back
178
+
179
+ question_template = f"Does the camera face the back of [A]?"
180
+ question = question_template.replace("[A]", A_desc)
181
+
182
+ answer = "Yes" if check else "No"
183
+
184
+ score = 0
185
+ if check:
186
+ score = 1
187
+ else:
188
+ score = 1 - 1*np.abs((angle_rad*180/np.pi-max_angle)/(45-max_angle))
189
+ score = 0 if score < 0 else score
190
+
191
+ return question, answer, check, score
192
+
193
+ def camera_left_object_center(A):
194
+ A_desc, A_cloud = A["caption"], A["pcd"]
195
+ A_desc = A_desc.lower()
196
+
197
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
198
+ A_pos = A_cloud.get_center()
199
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
200
+
201
+ A_rotation_matrix = A["rotation_matrix"]
202
+
203
+ max_angle = 30
204
+ angle_rad = np.arccos(np.clip(np.dot(-A_rotation_matrix.T[2], np.array([0,0,-1])), -1.0, 1.0))
205
+ is_left = angle_rad < max_angle / 180 * np.pi
206
+
207
+ check = is_left
208
+
209
+ question_template = f"Does the camera face the left of [A]?"
210
+ question = question_template.replace("[A]", A_desc)
211
+
212
+ answer = "Yes" if check else "No"
213
+
214
+ score = 0
215
+ if check:
216
+ score = 1
217
+ else:
218
+ score = 1 - 1*np.abs((angle_rad*180/np.pi-max_angle)/(60-max_angle))
219
+ score = 0 if score < 0 else score
220
+
221
+ return question, answer, check, score
222
+
223
+ def camera_right_object_center(A):
224
+ A_desc, A_cloud = A["caption"], A["pcd"]
225
+ A_desc = A_desc.lower()
226
+
227
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
228
+ A_pos = A_cloud.get_center()
229
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
230
+
231
+ A_rotation_matrix = A["rotation_matrix"]
232
+
233
+ max_angle = 30
234
+ angle_rad = np.arccos(np.clip(np.dot(A_rotation_matrix.T[2], np.array([0,0,-1])), -1.0, 1.0))
235
+ is_right = angle_rad < max_angle / 180 * np.pi
236
+
237
+ check = is_right
238
+
239
+ question_template = f"Does the camera face the right of [A]?"
240
+ question = question_template.replace("[A]", A_desc)
241
+
242
+ answer = "Yes" if check else "No"
243
+
244
+ score = 0
245
+ if check:
246
+ score = 1
247
+ else:
248
+ score = 1 - 1*np.abs((angle_rad*180/np.pi-max_angle)/(60-max_angle))
249
+ score = 0 if score < 0 else score
250
+
251
+ return question, answer, check, score
252
+
253
+
254
+
255
+ def object_side_by_side_same_direction(A, B):
256
+ A_desc, A_cloud = A["caption"], A["pcd"]
257
+ B_desc, B_cloud = B["caption"], B["pcd"]
258
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
259
+
260
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
261
+ A_pos = A_cloud.get_center()
262
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
263
+
264
+ B_pos = B_cloud.get_center()
265
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
266
+
267
+ # A_rotation_matrix = A["rotation_matrix"]
268
+ B_rotation_matrix = B["rotation_matrix"]
269
+ B_P_A = B_rotation_matrix.T @ (A_pos - B_pos) # 在B物体参考系下,A物体的位置
270
+ A_rotation_matrix = B_rotation_matrix.T @ A["rotation_matrix"]
271
+
272
+ max_angle = 30
273
+
274
+
275
+ side_by_side_radius = np.abs(np.arctan(B_P_A[2]/ B_P_A[0]))
276
+ is_side_by_side = side_by_side_radius > (90 - max_angle) / 180 * np.pi
277
+
278
+ # 比较X轴的夹角
279
+ angle_rad = np.arccos(np.clip(np.dot(A_rotation_matrix.T[0], np.array([1,0,0])), -1.0, 1.0))
280
+ is_same_orientation = angle_rad < max_angle / 180 * np.pi
281
+
282
+ check = is_same_orientation and is_side_by_side
283
+
284
+ question_template = f"Is [A] and [B] side by side, facing the same direction?"
285
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
286
+ answer = "Yes" if check else "No"
287
+
288
+ score = 0
289
+ if check:
290
+ score = 1
291
+ else:
292
+ w1 = 1 - np.abs(side_by_side_radius - (90 - max_angle) / 180 * np.pi) / (np.pi / 12) # 15度的阈值
293
+ w2 = 1 - np.abs(angle_rad - max_angle / 180 * np.pi) / (np.pi / 12) # 15度的阈值
294
+ score = 0 if w1 < 0 or w2 < 0 else w1 * w2
295
+ score = 0 if score < 0 else score
296
+
297
+ return question, answer, check, score
298
+
299
+ def object_side_by_side_opposite_direction(A, B):
300
+ A_desc, A_cloud = A["caption"], A["pcd"]
301
+ B_desc, B_cloud = B["caption"], B["pcd"]
302
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
303
+
304
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
305
+ A_pos = A_cloud.get_center()
306
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
307
+
308
+ B_pos = B_cloud.get_center()
309
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
310
+
311
+ # A_rotation_matrix = A["rotation_matrix"]
312
+ B_rotation_matrix = B["rotation_matrix"]
313
+ B_P_A = B_rotation_matrix.T @ (A_pos - B_pos) # 在B物体参考系下,A物体的位置
314
+ A_rotation_matrix = B_rotation_matrix.T @ A["rotation_matrix"]
315
+
316
+ max_angle = 30
317
+
318
+
319
+ side_by_side_radius = np.abs(np.arctan(B_P_A[2]/ B_P_A[0]))
320
+ is_side_by_side = side_by_side_radius > (90 - max_angle) / 180 * np.pi
321
+
322
+ angle_rad = np.arccos(np.clip(np.dot(A_rotation_matrix.T[0], np.array([-1,0,0])), -1.0, 1.0))
323
+ is_opposite_orientation = angle_rad < max_angle / 180 * np.pi
324
+
325
+ check = is_opposite_orientation and is_side_by_side
326
+
327
+ question_template = f"Is [A] and [B] side by side, facing the opposite direction?"
328
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
329
+ answer = "Yes" if check else "No"
330
+
331
+ score = 0
332
+ if check:
333
+ score = 1
334
+ else:
335
+ w1 = 1 - np.abs(side_by_side_radius - (90 - max_angle) / 180 * np.pi) / (np.pi / 12) # 15度的阈值
336
+ w2 = 1 - np.abs(angle_rad - max_angle / 180 * np.pi) / (np.pi / 12) # 15度的阈值
337
+ score = 0 if w1 < 0 or w2 < 0 else w1 * w2
338
+ score = 0 if score < 0 else score
339
+
340
+ return question, answer, check, score
341
+
342
+ def object_face_to_face(A, B):
343
+ A_desc, A_cloud = A["caption"], A["pcd"]
344
+ B_desc, B_cloud = B["caption"], B["pcd"]
345
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
346
+
347
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
348
+ A_pos = A_cloud.get_center()
349
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
350
+
351
+ B_pos = B_cloud.get_center()
352
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
353
+
354
+ # A_rotation_matrix = A["rotation_matrix"]
355
+ B_rotation_matrix = B["rotation_matrix"]
356
+ B_P_A = B_rotation_matrix.T @ (A_pos - B_pos) # 在B物体参考系下,A物体的位置
357
+ A_rotation_matrix = B_rotation_matrix.T @ A["rotation_matrix"]
358
+
359
+ max_angle = 30
360
+
361
+
362
+ face_to_face_radius = np.abs(np.arctan(B_P_A[2]/ B_P_A[0]))
363
+ is_line = B_P_A[0] > 0 and face_to_face_radius < max_angle * np.pi# 在一条线上,且A在B的前面
364
+
365
+
366
+ angle_rad = np.arccos(np.clip(np.dot(A_rotation_matrix.T[0], [-1,0,0]), -1.0, 1.0))
367
+ is_opposite_orientation = angle_rad < max_angle / 180 * np.pi
368
+
369
+ check = is_opposite_orientation and is_line
370
+
371
+ question_template = f"Is [A] and [B] face to face?"
372
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
373
+
374
+ answer = "Yes" if check else "No"
375
+
376
+ score = 0
377
+ if check:
378
+ score = 1
379
+ else:
380
+ w1 = 1 if B_P_A[0] > 0 else -1
381
+ w2 = 1 - np.abs(face_to_face_radius - max_angle * np.pi) / (np.pi / 12) # 15度的阈值
382
+ w3 = 1 - np.abs(angle_rad - max_angle / 180 * np.pi) / (np.pi / 12) # 15度的阈值
383
+ score = 0 if w1 < 0 or w2 < 0 or w3 < 0 else w1 * w2 * w3
384
+ score = 0 if score < 0 else score
385
+
386
+ return question, answer, check, score
387
+
388
+ def object_back_to_back(A, B):
389
+ A_desc, A_cloud = A["caption"], A["pcd"]
390
+ B_desc, B_cloud = B["caption"], B["pcd"]
391
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
392
+
393
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
394
+ A_pos = A_cloud.get_center()
395
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
396
+
397
+ B_pos = B_cloud.get_center()
398
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
399
+
400
+ # A_rotation_matrix = A["rotation_matrix"]
401
+ B_rotation_matrix = B["rotation_matrix"]
402
+ B_P_A = B_rotation_matrix.T @ (A_pos - B_pos) # 在B物体参考系下,A物体的位置
403
+ A_rotation_matrix = B_rotation_matrix.T @ A["rotation_matrix"]
404
+
405
+ max_angle = 30
406
+
407
+ face_to_face_radius = np.abs(np.arctan(B_P_A[2]/ B_P_A[0]))
408
+ is_line = B_P_A[0] < 0 and face_to_face_radius < max_angle / 180 * np.pi# 在一条线上,且A在B的前面
409
+
410
+ angle_rad = np.arccos(np.clip(np.dot(A_rotation_matrix.T[0], [-1,0,0]), -1.0, 1.0))
411
+ is_opposite_orientation = angle_rad < max_angle / 180 * np.pi
412
+
413
+ check = is_opposite_orientation and is_line
414
+
415
+ question_template = f"Is [A] and [B] back to back?"
416
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
417
+
418
+ answer = "Yes" if check else "No"
419
+
420
+ score = 0
421
+ if check:
422
+ score = 1
423
+ else:
424
+ w1 = 1 if B_P_A[0] < 0 else -1
425
+ w2 = 1 - np.abs(face_to_face_radius - max_angle * np.pi) / (np.pi / 12) # 15度的阈值
426
+ w3 = 1 - np.abs(angle_rad - max_angle / 180 * np.pi) / (np.pi / 12) # 15度的阈值
427
+ score = 0 if w1 < 0 or w2 < 0 or w3 < 0 else w1 * w2 * w3
428
+ score = 0 if score < 0 else score
429
+
430
+ return question, answer, check, score
431
+
432
+
433
+
434
+ def object_front(A, B):
435
+ A_desc, A_cloud = A["caption"], A["pcd"]
436
+ B_desc, B_cloud = B["caption"], B["pcd"]
437
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
438
+
439
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
440
+ A_pos = A_cloud.get_center()
441
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
442
+
443
+ B_pos = B_cloud.get_center()
444
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
445
+
446
+ # A_rotation_matrix = A["rotation_matrix"]
447
+ A_rotation_matrix = A["rotation_matrix"]
448
+ A_P_B = A_rotation_matrix.T @ (B_pos - A_pos) # 在A物体参考系下,B物体的位置
449
+
450
+ max_angle = 15
451
+ A_P_B_direcetion = A_P_B / np.linalg.norm(A_P_B)
452
+ angle_rad = np.arccos(np.clip(np.dot(A_P_B_direcetion, np.array([1,0,0])), -1.0, 1.0))
453
+
454
+ B_is_in_front_A = A_P_B[0] > 0 and angle_rad < max_angle / 180 * np.pi# 在一条线上,且A在B的前面
455
+
456
+ check = B_is_in_front_A
457
+
458
+ question_template = f"Is [B] in front of [A], from the view of [A]?"
459
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
460
+
461
+ answer = "Yes" if check else "No"
462
+
463
+ score = 0
464
+ if check:
465
+ score = 1
466
+ else:
467
+ score = 1 - 1*np.abs((angle_rad*180/np.pi - max_angle) / (45-max_angle))
468
+ score = 0 if score < 0 else score
469
+
470
+ return question, answer, check, score
471
+
472
+ def object_back(A, B):
473
+ A_desc, A_cloud = A["caption"], A["pcd"]
474
+ B_desc, B_cloud = B["caption"], B["pcd"]
475
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
476
+
477
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
478
+ A_pos = A_cloud.get_center()
479
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
480
+
481
+ B_pos = B_cloud.get_center()
482
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
483
+
484
+ # A_rotation_matrix = A["rotation_matrix"]
485
+ A_rotation_matrix = A["rotation_matrix"]
486
+ A_P_B = A_rotation_matrix.T @ (B_pos - A_pos) # 在A物体参考系下,B物体的位置
487
+
488
+ max_angle = 15
489
+ A_P_B_direcetion = A_P_B / np.linalg.norm(A_P_B)
490
+ angle_rad = np.arccos(np.clip(np.dot(A_P_B_direcetion, np.array([-1,0,0])), -1.0, 1.0))
491
+ B_is_in_back_A = A_P_B[0] < 0 and angle_rad < max_angle / 180 * np.pi# 在一条线上,且A在B的前面
492
+
493
+ check = B_is_in_back_A
494
+
495
+ question_template = f"Is [B] in back of [A], from the view of [A]?"
496
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
497
+
498
+ answer = "Yes" if check else "No"
499
+
500
+ score = 0
501
+ if check:
502
+ score = 1
503
+ else:
504
+ score = 1 - 1*np.abs((angle_rad*180/np.pi - max_angle) / (45-max_angle))
505
+ score = 0 if score < 0 else score
506
+
507
+ return question, answer, check, score
508
+
509
+ def object_left(A, B):
510
+ A_desc, A_cloud = A["caption"], A["pcd"]
511
+ B_desc, B_cloud = B["caption"], B["pcd"]
512
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
513
+
514
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
515
+ A_pos = A_cloud.get_center()
516
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
517
+
518
+ B_pos = B_cloud.get_center()
519
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
520
+
521
+ # A_rotation_matrix = A["rotation_matrix"]
522
+ A_rotation_matrix = A["rotation_matrix"]
523
+ A_P_B = A_rotation_matrix.T @ (B_pos - A_pos) # 在A物体参考系下,B物体的位置
524
+
525
+ max_angle = 30
526
+ A_P_B_direcetion = A_P_B / np.linalg.norm(A_P_B)
527
+ angle_rad = np.arccos(np.clip(np.dot(A_P_B_direcetion, np.array([0,0,-1])), -1.0, 1.0))
528
+ B_is_in_left_A = A_P_B[2] < 0 and angle_rad < max_angle / 180 * np.pi# 在一条线上,且A在B的前面
529
+
530
+ check = B_is_in_left_A
531
+
532
+ question_template = f"Is [B] on the left of [A], from the view of [A]?"
533
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
534
+
535
+ answer = "Yes" if check else "No"
536
+
537
+ score = 0
538
+ if check:
539
+ score = 1
540
+ else:
541
+ score = 1 - 1*np.abs((angle_rad*180/np.pi - max_angle) / (60-max_angle))
542
+ score = 0 if score < 0 or A_P_B[2] > 0 else score
543
+
544
+ return question, answer, check, score
545
+
546
+ def object_right(A, B):
547
+ A_desc, A_cloud = A["caption"], A["pcd"]
548
+ B_desc, B_cloud = B["caption"], B["pcd"]
549
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
550
+
551
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
552
+ A_pos = A_cloud.get_center()
553
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
554
+
555
+ B_pos = B_cloud.get_center()
556
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
557
+
558
+ # A_rotation_matrix = A["rotation_matrix"]
559
+ A_rotation_matrix = A["rotation_matrix"]
560
+ A_P_B = A_rotation_matrix.T @ (B_pos - A_pos) # 在A物体参考系下,B物体的位置
561
+
562
+
563
+ max_angle = 30
564
+ A_P_B_direcetion = A_P_B / np.linalg.norm(A_P_B)
565
+ angle_rad = np.arccos(np.clip(np.dot(A_P_B_direcetion, np.array([0,0,1])), -1.0, 1.0))
566
+ B_is_in_right_A = A_P_B[2] > 0 and angle_rad < max_angle / 180 * np.pi# 在一条线上,且A在B的前面
567
+
568
+ check = B_is_in_right_A
569
+
570
+ question_template = f"Is [B] on the right of [A], from the view of [A]?"
571
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
572
+
573
+ answer = "Yes" if check else "No"
574
+
575
+ score = 0
576
+ if check:
577
+ score = 1
578
+ else:
579
+ score = 1 - 1*np.abs((angle_rad*180/np.pi - max_angle) / (60-max_angle))
580
+ score = 0 if score < 0 or A_P_B[2] < 0 else score
581
+
582
+ return question, answer, check, score
583
+
584
+
585
+
586
+ def camera_two_objects_closer(A,B):
587
+ A_desc, A_cloud = A["caption"], A["pcd"]
588
+ B_desc, B_cloud = B["caption"], B["pcd"]
589
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
590
+
591
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
592
+ A_pos = A_cloud.get_center()
593
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
594
+
595
+ B_pos = B_cloud.get_center()
596
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
597
+
598
+ # 计算距离
599
+ distance_a = np.linalg.norm(A_pos)
600
+ distance_b = np.linalg.norm(B_pos)
601
+
602
+
603
+ check = distance_a < distance_b
604
+
605
+ question_template = f"Is [A] closer to the camera than [B]?"
606
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
607
+
608
+ answer = "Yes" if check else "No"
609
+ score = 1 if check else 0
610
+
611
+ return question, answer, check, score
612
+
613
+ def camera_two_objects_farther(A, B):
614
+ A_desc, A_cloud = A["caption"], A["pcd"]
615
+ B_desc, B_cloud = B["caption"], B["pcd"]
616
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
617
+
618
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
619
+ A_pos = A_cloud.get_center()
620
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
621
+
622
+ B_pos = B_cloud.get_center()
623
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
624
+
625
+ # 计算距离
626
+ distance_a = np.linalg.norm(A_pos)
627
+ distance_b = np.linalg.norm(B_pos)
628
+
629
+ check = distance_a > distance_b
630
+
631
+ question_template = f"Is [A] farther to the camera than [B]?"
632
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
633
+
634
+ answer = "Yes" if check else "No"
635
+ score = 1 if check else 0
636
+
637
+ return question, answer, check, score
638
+
639
+ def camera_two_objects_left(A, B):
640
+ A_desc, A_cloud = A["caption"], A["pcd"]
641
+ B_desc, B_cloud = B["caption"], B["pcd"]
642
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
643
+
644
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
645
+ A_pos = A_cloud.get_center()
646
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
647
+
648
+ B_pos = B_cloud.get_center()
649
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
650
+
651
+
652
+ check = B_pos[0] - A_pos[0] > 0
653
+
654
+ question_template = f"Is [A] on the left of [B], from the view of the camera?"
655
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
656
+
657
+ answer = "Yes" if check else "No"
658
+
659
+ score = 1 if check else 0
660
+
661
+ return question, answer, check, score
662
+
663
+ def camera_two_objects_right(A, B):
664
+ A_desc, A_cloud = A["caption"], A["pcd"]
665
+ B_desc, B_cloud = B["caption"], B["pcd"]
666
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
667
+
668
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
669
+ A_pos = A_cloud.get_center()
670
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
671
+
672
+ B_pos = B_cloud.get_center()
673
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
674
+
675
+
676
+ check = B_pos[0] - A_pos[0] < 0
677
+
678
+ question_template = f"Is [A] on the right of [B], from the view of the camera?"
679
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
680
+
681
+ answer = "Yes" if check else "No"
682
+
683
+ score = 1 if check else 0
684
+
685
+ return question, answer, check, score
686
+
687
+
688
+
689
+ def object_apart_0_5meter(A, B):
690
+ A_desc, A_cloud = A["caption"], A["pcd"]
691
+ B_desc, B_cloud = B["caption"], B["pcd"]
692
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
693
+
694
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
695
+ A_pos = A_cloud.get_center()
696
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
697
+
698
+ B_pos = B_cloud.get_center()
699
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
700
+
701
+ # 计算距离
702
+ distance = np.linalg.norm(A_pos - B_pos)
703
+
704
+ delta = 1.0/3
705
+ gt_distance = 0.5
706
+
707
+ check = (1-delta)*gt_distance < distance and distance < (1+delta)*gt_distance
708
+
709
+ question_template = f"Is [A] apart from [B] about 0.5 meter?"
710
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
711
+
712
+ answer = "Yes" if check else "No"
713
+
714
+ score = 0
715
+ if check:
716
+ score = 1
717
+ else:
718
+ score = 1 - 1*np.abs(((distance - gt_distance) / gt_distance)- delta)/delta
719
+ score = 0 if score < 0 else score
720
+
721
+ return question, answer, check, score
722
+
723
+ def object_apart_1meter(A, B):
724
+ A_desc, A_cloud = A["caption"], A["pcd"]
725
+ B_desc, B_cloud = B["caption"], B["pcd"]
726
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
727
+
728
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
729
+ A_pos = A_cloud.get_center()
730
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
731
+
732
+ B_pos = B_cloud.get_center()
733
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
734
+
735
+ # 计算距离
736
+ distance = np.linalg.norm(A_pos - B_pos)
737
+
738
+ delta = 1.0/3
739
+ gt_distance = 1
740
+
741
+ check = (1-delta)*gt_distance < distance and distance < (1+delta)*gt_distance
742
+
743
+ question_template = f"Is [A] apart from [B] about 1 meter?"
744
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
745
+
746
+ answer = "Yes" if check else "No"
747
+
748
+ score = 0
749
+ if check:
750
+ score = 1
751
+ else:
752
+ score = 1 - 1*np.abs(((distance - gt_distance) / gt_distance)- delta)/delta
753
+ score = 0 if score < 0 else score
754
+
755
+ return question, answer, check, score
756
+
757
+ def object_apart_1_5meter(A, B):
758
+ A_desc, A_cloud = A["caption"], A["pcd"]
759
+ B_desc, B_cloud = B["caption"], B["pcd"]
760
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
761
+
762
+ # 从PyTorch3D的坐标��转换到OpenCV的坐标系
763
+ A_pos = A_cloud.get_center()
764
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
765
+
766
+ B_pos = B_cloud.get_center()
767
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
768
+
769
+ # 计算距离
770
+ distance = np.linalg.norm(A_pos - B_pos)
771
+
772
+ delta = 1.0/3
773
+ gt_distance = 1.5
774
+
775
+ check = (1-delta)*gt_distance < distance and distance < (1+delta)*gt_distance
776
+
777
+ question_template = f"Is [A] apart from [B] about 0.5 meter?"
778
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
779
+
780
+ answer = "Yes" if check else "No"
781
+
782
+ score = 0
783
+ if check:
784
+ score = 1
785
+ else:
786
+ score = 1 - 1*np.abs(((distance - gt_distance) / gt_distance)- delta)/delta
787
+ score = 0 if score < 0 else score
788
+
789
+ return question, answer, check, score
790
+
791
+ def object_apart_2meter(A, B):
792
+ A_desc, A_cloud = A["caption"], A["pcd"]
793
+ B_desc, B_cloud = B["caption"], B["pcd"]
794
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
795
+
796
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
797
+ A_pos = A_cloud.get_center()
798
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
799
+
800
+ B_pos = B_cloud.get_center()
801
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
802
+
803
+ # 计算距离
804
+ distance = np.linalg.norm(A_pos - B_pos)
805
+
806
+ delta = 1.0/3
807
+ gt_distance = 2
808
+
809
+ check = (1-delta)*gt_distance < distance and distance < (1+delta)*gt_distance
810
+
811
+ question_template = f"Is [A] apart from [B] about 2 meters?"
812
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
813
+
814
+ answer = "Yes" if check else "No"
815
+
816
+ score = 0
817
+ if check:
818
+ score = 1
819
+ else:
820
+ score = 1 - 1*np.abs(((distance - gt_distance) / gt_distance)- delta)/delta
821
+ score = 0 if score < 0 else score
822
+
823
+ return question, answer, check, score
824
+
825
+
826
+ def camera_1meter_away(A):
827
+ A_desc, A_cloud = A["caption"], A["pcd"]
828
+ A_desc = A_desc.lower()
829
+
830
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
831
+ A_pos = A_cloud.get_center()
832
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
833
+
834
+ delta = 1.0/3
835
+ gt_distance = 1
836
+
837
+ distance = np.linalg.norm(A_pos)
838
+
839
+ check = (1-delta)*gt_distance < distance and distance < (1+delta)*gt_distance
840
+
841
+ question_template = f"Is the camera about 1 meter away from [A]?"
842
+ question = question_template.replace("[A]", A_desc)
843
+ answer = "Yes" if check else "No"
844
+
845
+ score = 0
846
+ if check:
847
+ score = 1
848
+ else:
849
+ score = 1 - 1*np.abs(((distance - gt_distance) / gt_distance)- delta)/delta
850
+ score = 0 if score < 0 else score
851
+
852
+ return question, answer, check, score
853
+
854
+ def camera_2meter_away(A):
855
+ A_desc, A_cloud = A["caption"], A["pcd"]
856
+ A_desc = A_desc.lower()
857
+
858
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
859
+ A_pos = A_cloud.get_center()
860
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
861
+
862
+ delta = 1.0/3
863
+ gt_distance = 2
864
+
865
+ distance = np.linalg.norm(A_pos)
866
+
867
+ check = (1-delta)*gt_distance < distance and distance < (1+delta)*gt_distance
868
+
869
+ question_template = f"Is the camera about 2 meter away from [A]?"
870
+ question = question_template.replace("[A]", A_desc)
871
+ answer = "Yes" if check else "No"
872
+
873
+ score = 0
874
+ if check:
875
+ score = 1
876
+ else:
877
+ score = 1 - 1*np.abs(((distance - gt_distance) / gt_distance)- delta)/delta
878
+ score = 0 if score < 0 else score
879
+
880
+ return question, answer, check, score
881
+
882
+ def camera_3meter_away(A):
883
+ A_desc, A_cloud = A["caption"], A["pcd"]
884
+ A_desc = A_desc.lower()
885
+
886
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
887
+ A_pos = A_cloud.get_center()
888
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
889
+
890
+ delta = 0.3
891
+ gt_distance = 3
892
+
893
+ distance = np.linalg.norm(A_pos)
894
+
895
+ check = (1-delta)*gt_distance < distance and distance < (1+delta)*gt_distance
896
+
897
+ question_template = f"Is the camera about 3 meter away from [A]?"
898
+ question = question_template.replace("[A]", A_desc)
899
+ answer = "Yes" if check else "No"
900
+
901
+ score = 0
902
+ if check:
903
+ score = 1
904
+ else:
905
+ score = 1 - 1*np.abs(((distance - gt_distance) / gt_distance)- delta)/delta
906
+ score = 0 if score < 0 else score
907
+
908
+ return question, answer, check, score
909
+
910
+ def camera_4meter_away(A):
911
+ A_desc, A_cloud = A["caption"], A["pcd"]
912
+ A_desc = A_desc.lower()
913
+
914
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
915
+ A_pos = A_cloud.get_center()
916
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
917
+
918
+ delta = 0.2
919
+ gt_distance = 4
920
+
921
+ distance = np.linalg.norm(A_pos)
922
+
923
+ check = (1-delta)*gt_distance < distance and distance < (1+delta)*gt_distance
924
+
925
+ question_template = f"Is the camera about 4 meter away from [A]?"
926
+ question = question_template.replace("[A]", A_desc)
927
+ answer = "Yes" if check else "No"
928
+
929
+ score = 0
930
+ if check:
931
+ score = 1
932
+ else:
933
+ score = 1 - 1*np.abs(((distance - gt_distance) / gt_distance)- delta)/delta
934
+ score = 0 if score < 0 else score
935
+
936
+ return question, answer, check, score
937
+
938
+
939
+
940
+ def object_bigger_than1_2(A, B):
941
+ A_desc, A_cloud = A["caption"], A["pcd"]
942
+ B_desc, B_cloud = B["caption"], B["pcd"]
943
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
944
+
945
+ # 计算距离
946
+ A_rotation_matrix = A["rotation_matrix"]
947
+ theta_A = np.arctan2(A_rotation_matrix.T[0][2], A_rotation_matrix.T[0][0])
948
+ A_center = A["pcd"].get_center()
949
+ R = A["pcd"].get_rotation_matrix_from_xyz((0, 0, theta_A))
950
+ A["pcd"] = A["pcd"].rotate(R)
951
+ A_length = A["pcd"].get_axis_aligned_bounding_box().get_extent()[0]
952
+ A_height = A["pcd"].get_axis_aligned_bounding_box().get_extent()[1]
953
+ A_width = A["pcd"].get_axis_aligned_bounding_box().get_extent()[2]
954
+ A_volume = A_length * A_height * A_width
955
+
956
+ B_rotation_matrix = B["rotation_matrix"]
957
+ theta_B = np.arctan2(B_rotation_matrix.T[0][2], B_rotation_matrix.T[0][0])
958
+ B_center = B["pcd"].get_center()
959
+ R = B["pcd"].get_rotation_matrix_from_xyz((0, 0, theta_B))
960
+ B["pcd"] = B["pcd"].rotate(R)
961
+ B_length = B["pcd"].get_axis_aligned_bounding_box().get_extent()[0]
962
+ B_height = B["pcd"].get_axis_aligned_bounding_box().get_extent()[1]
963
+ B_width = B["pcd"].get_axis_aligned_bounding_box().get_extent()[2]
964
+ B_volume = B_length * B_height * B_width
965
+
966
+ if A_volume > B_volume:
967
+ distance = A_volume / B_volume
968
+ else:
969
+ distance = B_volume / A_volume
970
+
971
+ delta = 1.0/3
972
+ gt_distance = 1.2
973
+
974
+ check = (1-delta)*gt_distance < distance and distance < (1+delta)*gt_distance
975
+
976
+ question_template = f"Is [A] bigger than [B] about 0.2 times?"
977
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
978
+
979
+ answer = "Yes" if check else "No"
980
+
981
+ score = 0
982
+ if check:
983
+ score = 1
984
+ else:
985
+ score = 1 - 1*np.abs(((distance - gt_distance) / gt_distance)- delta)/delta
986
+ score = 0 if score < 0 else score
987
+
988
+ return question, answer, check, score
989
+
990
+ def object_higher_20cm(A, B):
991
+ A_desc, A_cloud = A["caption"], A["pcd"]
992
+ B_desc, B_cloud = B["caption"], B["pcd"]
993
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
994
+
995
+ # 计算距离
996
+
997
+ A_height = A["pcd"].get_axis_aligned_bounding_box().get_extent()[1]
998
+ B_height = B["pcd"].get_axis_aligned_bounding_box().get_extent()[1]
999
+ distance = np.abs(A_height-B_height)
1000
+
1001
+ delta = 1.0/3
1002
+ gt_distance = 0.2
1003
+
1004
+ check = (1-delta)*gt_distance < distance and distance < (1+delta)*gt_distance
1005
+
1006
+ question_template = f"Is [A] higher 20cm than [B]?"
1007
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
1008
+
1009
+ answer = "Yes" if check else "No"
1010
+
1011
+ score = 0
1012
+ if check:
1013
+ score = 1
1014
+ else:
1015
+ score = 1 - 1*np.abs(((distance - gt_distance) / gt_distance)- delta)/delta
1016
+ score = 0 if score < 0 else score
1017
+
1018
+ return question, answer, check, score
1019
+
1020
+ def object_longer_50cm(A, B):
1021
+ A_desc, A_cloud = A["caption"], A["pcd"]
1022
+ B_desc, B_cloud = B["caption"], B["pcd"]
1023
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
1024
+
1025
+ # 计算距离
1026
+
1027
+ A_rotation_matrix = A["rotation_matrix"]
1028
+ theta_A = np.arctan2(A_rotation_matrix.T[0][2], A_rotation_matrix.T[0][0])
1029
+ A_center = A["pcd"].get_center()
1030
+ R = A["pcd"].get_rotation_matrix_from_xyz((0, 0, theta_A))
1031
+ A["pcd"] = A["pcd"].rotate(R)
1032
+ A_length = A["pcd"].get_axis_aligned_bounding_box().get_extent()[0]
1033
+
1034
+ B_rotation_matrix = B["rotation_matrix"]
1035
+ theta_B = np.arctan2(B_rotation_matrix.T[0][2], B_rotation_matrix.T[0][0])
1036
+ B_center = B["pcd"].get_center()
1037
+ R = B["pcd"].get_rotation_matrix_from_xyz((0, 0, theta_B))
1038
+ B["pcd"] = B["pcd"].rotate(R)
1039
+ B_length = B["pcd"].get_axis_aligned_bounding_box().get_extent()[0]
1040
+
1041
+ distance = np.abs(A_length-B_length)
1042
+
1043
+ delta = 1.0/3
1044
+ gt_distance = 0.5
1045
+
1046
+ check = (1-delta)*gt_distance < distance and distance < (1+delta)*gt_distance
1047
+
1048
+ question_template = f"Is [A] longer 50cm than [B]?"
1049
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
1050
+
1051
+ answer = "Yes" if check else "No"
1052
+
1053
+ score = 0
1054
+ if check:
1055
+ score = 1
1056
+ else:
1057
+ score = 1 - 1*np.abs(((distance - gt_distance) / gt_distance)- delta)/delta
1058
+ score = 0 if score < 0 else score
1059
+
1060
+ return question, answer, check, score
1061
+
1062
+ def object_wider_30cm(A, B):
1063
+ A_desc, A_cloud = A["caption"], A["pcd"]
1064
+ B_desc, B_cloud = B["caption"], B["pcd"]
1065
+ A_desc, B_desc = A_desc.lower(), B_desc.lower()
1066
+
1067
+ # 计算距离
1068
+
1069
+ A_rotation_matrix = A["rotation_matrix"]
1070
+ theta_A = np.arctan2(A_rotation_matrix.T[0][2], A_rotation_matrix.T[0][0])
1071
+ A_center = A["pcd"].get_center()
1072
+ R = A["pcd"].get_rotation_matrix_from_xyz((0, 0, theta_A))
1073
+ A["pcd"] = A["pcd"].rotate(R)
1074
+ A_width = A["pcd"].get_axis_aligned_bounding_box().get_extent()[2]
1075
+
1076
+ B_rotation_matrix = B["rotation_matrix"]
1077
+ theta_B = np.arctan2(B_rotation_matrix.T[0][2], B_rotation_matrix.T[0][0])
1078
+ B_center = B["pcd"].get_center()
1079
+ R = B["pcd"].get_rotation_matrix_from_xyz((0, 0, theta_B))
1080
+ B["pcd"] = B["pcd"].rotate(R)
1081
+ B_width = B["pcd"].get_axis_aligned_bounding_box().get_extent()[2]
1082
+
1083
+ distance = np.abs(A_width-B_width)
1084
+
1085
+ delta = 1.0/3
1086
+ gt_distance = 0.3
1087
+
1088
+ check = (1-delta)*gt_distance < distance and distance < (1+delta)*gt_distance
1089
+
1090
+ question_template = f"Is [A] wider 30cm than [B]?"
1091
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
1092
+
1093
+ answer = "Yes" if check else "No"
1094
+
1095
+ score = 0
1096
+ if check:
1097
+ score = 1
1098
+ else:
1099
+ score = 1 - 1*np.abs(((distance - gt_distance) / gt_distance)- delta)/delta
1100
+ score = 0 if score < 0 else score
1101
+
1102
+ return question, answer, check, score
1103
+
1104
+
1105
+ def side_by_side_front(A, B):
1106
+ A_desc, A_cloud = A["caption"], A["pcd"]
1107
+ A_desc = A_desc.lower()
1108
+ B_desc, B_cloud = B["caption"], B["pcd"]
1109
+ B_desc = B_desc.lower()
1110
+
1111
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
1112
+ A_pos = A_cloud.get_center()
1113
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
1114
+ B_pos = B_cloud.get_center()
1115
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
1116
+
1117
+
1118
+ A_rotation_matrix = A["rotation_matrix"]
1119
+ B_rotation_matrix = B["rotation_matrix"]
1120
+
1121
+ B_rotation_matrix = A_rotation_matrix.T @ B_rotation_matrix # 在A的坐标系下,B的旋转矩阵
1122
+
1123
+ max_angle = 30
1124
+
1125
+ A_P_B = A_rotation_matrix.T @ (B_pos - A_pos) # 在A的坐标系下,B相对于A的位置
1126
+ side_by_side_radius = np.abs(np.arctan(A_P_B[2]/ A_P_B[0]))
1127
+ is_side_by_side = side_by_side_radius > (90 - max_angle) * np.pi / 180
1128
+
1129
+ same_direction_radius = np.arccos(np.clip(np.dot(B_rotation_matrix.T[0], np.array([1,0,0])), -1.0, 1.0))
1130
+ is_same_direction = same_direction_radius < max_angle * np.pi / 180 # 30度的阈值
1131
+
1132
+ front_radius = np.arccos(np.clip(np.dot(A_rotation_matrix.T[0], np.array([0,0,-1])), -1.0, 1.0))
1133
+ is_front = front_radius < max_angle * np.pi / 180 # 30度的阈值
1134
+
1135
+ check = is_side_by_side and is_same_direction and is_front
1136
+
1137
+ question_template = f"Is [A] and [B] side-by-side and same-orientation with viewed from the front of [A]?"
1138
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
1139
+
1140
+ answer = "Yes" if check else "No"
1141
+
1142
+ score = 0
1143
+ if check:
1144
+ score = 1
1145
+ else:
1146
+ w1 = 1 - np.abs(side_by_side_radius - (90 - max_angle) / 180 * np.pi) / (np.pi / 12) # 15度的阈值
1147
+ w2 = 1 - np.abs(same_direction_radius - max_angle / 180 * np.pi) / (np.pi / 12) # 15度的阈值
1148
+ w3 = 1 - np.abs(front_radius - max_angle / 180 * np.pi) / (np.pi / 12) # 15度的阈值
1149
+ score = 0 if w1<0 or w2<0 or w3<0 else w1 * w2 * w3
1150
+
1151
+ return question, answer, check, score
1152
+
1153
+ def side_by_side_left(A, B):
1154
+ A_desc, A_cloud = A["caption"], A["pcd"]
1155
+ A_desc = A_desc.lower()
1156
+ B_desc, B_cloud = B["caption"], B["pcd"]
1157
+ B_desc = B_desc.lower()
1158
+
1159
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
1160
+ A_pos = A_cloud.get_center()
1161
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
1162
+ B_pos = B_cloud.get_center()
1163
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
1164
+
1165
+
1166
+ A_rotation_matrix = A["rotation_matrix"]
1167
+ B_rotation_matrix = B["rotation_matrix"]
1168
+
1169
+ B_rotation_matrix = A_rotation_matrix.T @ B_rotation_matrix # 在A的坐标系下,B的旋转矩阵
1170
+
1171
+ max_angle = 30
1172
+
1173
+ A_P_B = A_rotation_matrix.T @ (B_pos - A_pos) # 在A的坐标系下,B相对于A的位置
1174
+ side_by_side_radius = np.abs(np.arctan(A_P_B[2]/ A_P_B[0]))
1175
+ is_side_by_side = side_by_side_radius > (90 - max_angle) * np.pi / 180
1176
+
1177
+ same_direction_radius = np.arccos(np.clip(np.dot(B_rotation_matrix.T[0], np.array([1,0,0])), -1.0, 1.0))
1178
+ is_same_direction = same_direction_radius < max_angle * np.pi / 180 # 30度的阈值
1179
+
1180
+ left_radius = np.arccos(np.clip(np.dot(A_rotation_matrix.T[0], np.array([-1,0,0])), -1.0, 1.0))
1181
+ is_left = left_radius < max_angle * np.pi / 180 # 30度的阈值
1182
+
1183
+ check = is_side_by_side and is_same_direction and is_left
1184
+
1185
+ question_template = f"Is [A] and [B] side-by-side and same-orientation with viewed from the left of [A]?"
1186
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
1187
+
1188
+ answer = "Yes" if check else "No"
1189
+
1190
+ score = 0
1191
+ if check:
1192
+ score = 1
1193
+ else:
1194
+ w1 = 1 - np.abs(side_by_side_radius - (90 - max_angle) / 180 * np.pi) / (np.pi / 12) # 15度的阈值
1195
+ w2 = 1 - np.abs(same_direction_radius - max_angle / 180 * np.pi) / (np.pi / 12) # 15度的阈值
1196
+ w3 = 1 - np.abs(left_radius - max_angle / 180 * np.pi) / (np.pi / 6) # 30度的阈值
1197
+ score = 0 if w1<0 or w2<0 or w3<0 else w1 * w2 * w3
1198
+
1199
+ return question, answer, check, score
1200
+
1201
+ def side_by_side_right(A, B):
1202
+ A_desc, A_cloud = A["caption"], A["pcd"]
1203
+ A_desc = A_desc.lower()
1204
+ B_desc, B_cloud = B["caption"], B["pcd"]
1205
+ B_desc = B_desc.lower()
1206
+
1207
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
1208
+ A_pos = A_cloud.get_center()
1209
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
1210
+ B_pos = B_cloud.get_center()
1211
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
1212
+
1213
+
1214
+ A_rotation_matrix = A["rotation_matrix"]
1215
+ B_rotation_matrix = B["rotation_matrix"]
1216
+
1217
+ B_rotation_matrix = A_rotation_matrix.T @ B_rotation_matrix # 在A的坐标系下,B的旋转矩阵
1218
+
1219
+ max_angle = 30
1220
+
1221
+ A_P_B = A_rotation_matrix.T @ (B_pos - A_pos) # 在A的坐标系下,B相对于A的位置
1222
+ side_by_side_radius = np.abs(np.arctan(A_P_B[2]/ A_P_B[0]))
1223
+ is_side_by_side = side_by_side_radius > (90 - max_angle) * np.pi / 180
1224
+
1225
+ same_direction_radius = np.arccos(np.clip(np.dot(B_rotation_matrix.T[0], np.array([1,0,0])), -1.0, 1.0))
1226
+ is_same_direction = same_direction_radius < max_angle * np.pi / 180 # 30度的阈值
1227
+
1228
+ right_radius = np.arccos(np.clip(np.dot(A_rotation_matrix.T[0], np.array([1,0,0])), -1.0, 1.0))
1229
+ is_right = right_radius < max_angle * np.pi / 180 # 30度的阈值
1230
+
1231
+ check = is_side_by_side and is_same_direction and is_right
1232
+
1233
+ question_template = f"Is [A] and [B] side-by-side and same-orientation with viewed from the right of [A]?"
1234
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
1235
+
1236
+ answer = "Yes" if check else "No"
1237
+
1238
+ score = 0
1239
+ if check:
1240
+ score = 1
1241
+ else:
1242
+ w1 = 1 - np.abs(side_by_side_radius - (90 - max_angle) / 180 * np.pi) / (np.pi / 12) # 15度的阈值
1243
+ w2 = 1 - np.abs(same_direction_radius - max_angle / 180 * np.pi) / (np.pi / 12) # 15度的阈值
1244
+ w3 = 1 - np.abs(right_radius - max_angle / 180 * np.pi) / (np.pi / 6) # 30度的阈值
1245
+ score = 0 if w1<0 or w2<0 or w3<0 else w1 * w2 * w3
1246
+
1247
+ return question, answer, check, score
1248
+
1249
+
1250
+ def side_by_side_back(A, B):
1251
+ A_desc, A_cloud = A["caption"], A["pcd"]
1252
+ A_desc = A_desc.lower()
1253
+ B_desc, B_cloud = B["caption"], B["pcd"]
1254
+ B_desc = B_desc.lower()
1255
+
1256
+ # 从PyTorch3D的坐标系转换到OpenCV的坐标系
1257
+ A_pos = A_cloud.get_center()
1258
+ A_pos[0] = -A_pos[0]; A_pos[1] = -A_pos[1]
1259
+ B_pos = B_cloud.get_center()
1260
+ B_pos[0] = -B_pos[0]; B_pos[1] = -B_pos[1]
1261
+
1262
+
1263
+ A_rotation_matrix = A["rotation_matrix"]
1264
+ B_rotation_matrix = B["rotation_matrix"]
1265
+
1266
+ B_rotation_matrix = A_rotation_matrix.T @ B_rotation_matrix # 在A的坐标系下,B的旋转矩阵
1267
+
1268
+ max_angle = 30
1269
+
1270
+ A_P_B = A_rotation_matrix.T @ (B_pos - A_pos) # 在A的坐标系下,B相对于A的位置
1271
+ side_by_side_radius = np.abs(np.arctan(A_P_B[2]/ A_P_B[0]))
1272
+ is_side_by_side = side_by_side_radius > (90 - max_angle) * np.pi / 180
1273
+
1274
+ same_direction_radius = np.arccos(np.clip(np.dot(B_rotation_matrix.T[0], np.array([1,0,0])), -1.0, 1.0))
1275
+ is_same_direction = same_direction_radius < max_angle * np.pi / 180 # 30度的阈值
1276
+
1277
+ back_radius = np.arccos(np.clip(np.dot(A_rotation_matrix.T[0], np.array([0,0,1])), -1.0, 1.0))
1278
+ is_back = back_radius < max_angle * np.pi / 180 # 30度的阈值
1279
+
1280
+ check = is_side_by_side and is_same_direction and is_back
1281
+
1282
+ question_template = f"Is [A] and [B] side-by-side and same-orientation with viewed from the back of [A]?"
1283
+ question = question_template.replace("[A]", A_desc).replace("[B]", B_desc)
1284
+
1285
+ answer = "Yes" if check else "No"
1286
+
1287
+ score = 0
1288
+ if check:
1289
+ score = 1
1290
+ else:
1291
+ w1 = 1 - np.abs(side_by_side_radius - (90 - max_angle) / 180 * np.pi) / (np.pi / 12) # 15度的阈值
1292
+ w2 = 1 - np.abs(same_direction_radius - max_angle / 180 * np.pi) / (np.pi / 12) # 15度的阈值
1293
+ w3 = 1 - np.abs(back_radius - max_angle / 180 * np.pi) / (np.pi / 12) # 15度的阈值
1294
+ score = 0 if w1<0 or w2<0 or w3<0 else w1 * w2 * w3
1295
+
1296
+ return question, answer, check, score
processor/prompt_utils.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import random
3
+ import string
4
+
5
+ import numpy as np
6
+
7
+
8
+ def generate_random_string(length):
9
+ letters = string.ascii_letters + string.digits
10
+ return "".join(random.choice(letters) for _ in range(length))
11
+
12
+
13
+ def calculate_angle_clockwise(A_pos, B_pos, x_right=False):
14
+ # Vector from A to B
15
+ if x_right:
16
+ vector_A_to_B = (A_pos[0] - B_pos[0], B_pos[1] - A_pos[1])
17
+ else:
18
+ vector_A_to_B = (B_pos[0] - A_pos[0], B_pos[1] - A_pos[1])
19
+
20
+ # Angle of this vector w.r.t. positive z-axis
21
+ angle_rad = math.atan2(vector_A_to_B[0], vector_A_to_B[1]) # atan2 handles all quadrants
22
+ angle_deg = math.degrees(angle_rad)
23
+
24
+ # Convert angle to clock position, 360 degrees => 12 hours, so 1 hour = 30 degrees
25
+ # We adjust the angle to be positive and then calculate the clock position
26
+ angle_deg = (angle_deg + 360) % 360
27
+ clock_position = 12 - angle_deg // 30
28
+ clock_position = clock_position if clock_position > 0 else 12 + clock_position
29
+
30
+ return clock_position
31
+
32
+
33
+ def is_aligned_vertically(A, B):
34
+ # Convert Open3D point cloud to NumPy array
35
+ A_points = np.asarray(A["pcd"].points)
36
+ B_points = np.asarray(B["pcd"].points)
37
+
38
+ # Calculate vertical (y) extents for A
39
+ A_min, A_max = np.min(A_points[:, 1]), np.max(A_points[:, 1])
40
+ # Calculate vertical (y) extents for B
41
+ B_min, B_max = np.min(B_points[:, 1]), np.max(B_points[:, 1])
42
+
43
+ # Determine vertical overlap
44
+ overlap = max(0, min(A_max, B_max) - max(A_min, B_min))
45
+ A_overlap_percentage = overlap / (A_max - A_min) if A_max != A_min else 0
46
+ B_overlap_percentage = overlap / (B_max - B_min) if B_max != B_min else 0
47
+
48
+ # Return True if both overlaps are greater than 50%
49
+ return A_overlap_percentage > 0.5 and B_overlap_percentage > 0.5
50
+
51
+
52
+ def is_aligned_horizontally(A, B):
53
+ # The high level logic is to check if the x-axis of one object is fully contained by the x-axis of the other object
54
+
55
+ # Extract the bounding boxes for both A and B
56
+ A_box = A["pcd"].get_axis_aligned_bounding_box()
57
+ B_box = B["pcd"].get_axis_aligned_bounding_box()
58
+
59
+ # Get the min and max x-axis values for both A and B
60
+ A_min_x, A_max_x = A_box.get_min_bound()[0], A_box.get_max_bound()[0]
61
+ B_min_x, B_max_x = B_box.get_min_bound()[0], B_box.get_max_bound()[0]
62
+
63
+ # Check if A and B are almost the same size on the x-axis
64
+ A_width, B_width = A_max_x - A_min_x, B_max_x - B_min_x
65
+ is_almost_same_size = max(A_width, B_width) / min(A_width, B_width) <= 1.5
66
+ if not is_almost_same_size:
67
+ return False
68
+
69
+ overlap_min, overlap_max = max(A_min_x, B_min_x), min(A_max_x, B_max_x)
70
+ overlap_width = max(0, overlap_max - overlap_min)
71
+ overlap_percent = max(overlap_width / A_width, overlap_width / B_width)
72
+
73
+ return overlap_percent > 0.95
74
+
75
+
76
+ def is_y_axis_overlapped(A, B):
77
+ # Extract the y-axis values (height) of the bounding boxes
78
+ A_box = A["pcd"].get_axis_aligned_bounding_box()
79
+ B_box = B["pcd"].get_axis_aligned_bounding_box()
80
+
81
+ # Get the min and max y-axis values for both A and B
82
+ A_min_y, A_max_y = A_box.get_min_bound()[1], A_box.get_max_bound()[1]
83
+ B_min_y, B_max_y = B_box.get_min_bound()[1], B_box.get_max_bound()[1]
84
+
85
+ # Check if there's any overlap in the y-axis values
86
+ # There are four possible scenarios for overlap, but we can check them with a simpler logic:
87
+ # If one box's minimum is between the other's min and max, or one box's max is.
88
+ overlap = (A_min_y <= B_max_y and A_max_y >= B_min_y) or (B_min_y <= A_max_y and B_max_y >= A_min_y)
89
+
90
+ return overlap
91
+
92
+
93
+ def is_supporting(A, B):
94
+ # Extract bounding boxes
95
+ A_box = A["pcd"].get_axis_aligned_bounding_box()
96
+ B_box = B["pcd"].get_axis_aligned_bounding_box()
97
+
98
+ # Get the corners of the bounding boxes
99
+ A_min, A_max = A_box.get_min_bound(), A_box.get_max_bound()
100
+ B_min, B_max = B_box.get_min_bound(), B_box.get_max_bound()
101
+
102
+ # Check vertical contact:
103
+ # The bottom of the upper object is at or above the top of the lower object
104
+ vertical_contact = (A_min[2] <= B_max[2] and A_min[2] >= B_min[2]) or (
105
+ B_min[2] <= A_max[2] and B_min[2] >= A_min[2]
106
+ )
107
+
108
+ if not vertical_contact:
109
+ # If there's no vertical contact, they are not supporting each other
110
+ return False
111
+
112
+ # Determine which object is on top and which is on bottom
113
+ if A_min[2] < B_min[2]:
114
+ top, bottom = B, A
115
+ top_min, top_max = B_min, B_max
116
+ bottom_min, bottom_max = A_min, A_max
117
+ else:
118
+ top, bottom = A, B
119
+ top_min, top_max = A_min, A_max
120
+ bottom_min, bottom_max = B_min, B_max
121
+
122
+ # Check horizontal coverage:
123
+ # The larger (top) object's bounding box completely covers the smaller (bottom) object's bounding box
124
+ horizontal_coverage = (
125
+ top_min[0] <= bottom_min[0]
126
+ and top_max[0] >= bottom_max[0]
127
+ and top_min[1] <= bottom_min[1]
128
+ and top_max[1] >= bottom_max[1]
129
+ )
130
+
131
+ return horizontal_coverage
processor/segment.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import torch
3
+ import torchvision
4
+ from osdsynth.processor.wrappers.grounding_dino import get_grounding_dino_model
5
+ from osdsynth.processor.wrappers.ram import get_tagging_model, run_tagging_model
6
+ from osdsynth.processor.wrappers.sam import (
7
+ convert_detections_to_dict,
8
+ convert_detections_to_list,
9
+ crop_detections_with_xyxy,
10
+ filter_detections,
11
+ get_sam_predictor,
12
+ get_sam_segmentation_from_xyxy,
13
+ mask_subtract_contained,
14
+ post_process_mask,
15
+ sort_detections_by_area,
16
+ )
17
+ from osdsynth.utils.logger import SkipImageException
18
+ from osdsynth.visualizer.som import draw_som_on_image
19
+ from PIL import Image
20
+ import numpy as np
21
+
22
+ class SegmentImage:
23
+ """Class to segment the image."""
24
+
25
+ def __init__(self, cfg, logger, device, init_gdino=True, init_tagging=True, init_sam=True):
26
+ self.cfg = cfg
27
+ self.logger = logger
28
+ self.device = device
29
+
30
+ if init_gdino:
31
+ # Initialize the Grounding Dino Model
32
+ self.grounding_dino_model = get_grounding_dino_model(cfg, device)
33
+ else:
34
+ self.grounding_dino_model = None
35
+
36
+ if init_tagging:
37
+ # Initialize the tagging Model
38
+ self.tagging_transform, self.tagging_model = get_tagging_model(cfg, device)
39
+ else:
40
+ self.tagging_transform = self.tagging_model = None
41
+
42
+ if init_sam:
43
+ # Initialize the SAM Model
44
+ self.sam_predictor = get_sam_predictor(cfg.sam_variant, device)
45
+ else:
46
+ self.sam_predictor = None
47
+
48
+ pass
49
+
50
+ def process(self, image_bgr, two_class ,plot_som=True):
51
+ """Segment the image."""
52
+
53
+ image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
54
+ image_rgb_pil = Image.fromarray(image_rgb)
55
+
56
+ # image_rgb_pil.save('tmp.png')
57
+
58
+ img_tagging = image_rgb_pil.resize((384, 384))
59
+ img_tagging = self.tagging_transform(img_tagging).unsqueeze(0).to(self.device)
60
+
61
+ # Tag2Text
62
+ if two_class is None:
63
+ classes = run_tagging_model(self.cfg, img_tagging, self.tagging_model)
64
+ else:
65
+ classes = two_class
66
+
67
+ if len(classes) == 0:
68
+ raise SkipImageException("No foreground objects detected by tagging model.")
69
+
70
+ # Using GroundingDINO to detect and SAM to segment
71
+ detections = self.grounding_dino_model.predict_with_classes(
72
+ image=image_bgr, # This function expects a BGR image...
73
+ classes=classes,
74
+ box_threshold=self.cfg.box_threshold,
75
+ text_threshold=self.cfg.text_threshold,
76
+ )
77
+
78
+
79
+ if len(detections.class_id) < 1:
80
+ raise SkipImageException("No object detected.")
81
+
82
+
83
+
84
+ # Non-maximum suppression
85
+ nms_idx = (
86
+ torchvision.ops.nms(
87
+ torch.from_numpy(detections.xyxy),
88
+ torch.from_numpy(detections.confidence),
89
+ self.cfg.nms_threshold,
90
+ )
91
+ .numpy()
92
+ .tolist()
93
+ )
94
+
95
+ print(f"Before NMS: {len(detections.xyxy)} detections")
96
+ detections.xyxy = detections.xyxy[nms_idx]
97
+ detections.confidence = detections.confidence[nms_idx]
98
+ detections.class_id = detections.class_id[nms_idx]
99
+ print(f"After NMS: {len(detections.xyxy)} detections")
100
+
101
+ # Somehow some detections will have class_id=-1, remove them
102
+ valid_idx = detections.class_id != -1
103
+ detections.xyxy = detections.xyxy[valid_idx]
104
+ detections.confidence = detections.confidence[valid_idx]
105
+ detections.class_id = detections.class_id[valid_idx]
106
+
107
+ # Segment Anything
108
+ detections.mask = get_sam_segmentation_from_xyxy(
109
+ sam_predictor=self.sam_predictor, image=image_rgb, xyxy=detections.xyxy
110
+ )
111
+
112
+ # Convert the detection to a dict. Elements are np.ndarray
113
+ detections_dict = convert_detections_to_dict(detections, classes)
114
+
115
+ # Filter out the objects based on various criteria
116
+ detections_dict = filter_detections(self.cfg, detections_dict, image_rgb)
117
+
118
+ if len(detections_dict["xyxy"]) < 1:
119
+ raise SkipImageException("No object detected after filtering.")
120
+
121
+ # Subtract the mask of bounding boxes that are contained by it
122
+ detections_dict["subtracted_mask"], mask_contained = mask_subtract_contained(
123
+ detections_dict["xyxy"], detections_dict["mask"], th1=0.05, th2=0.05
124
+ )
125
+
126
+ # Sort the dets by area
127
+ detections_dict = sort_detections_by_area(detections_dict)
128
+
129
+ # Add RLE to dict
130
+ detections_dict = post_process_mask(detections_dict)
131
+
132
+ # Convert the detection to a list. Each element is a dict
133
+ detections_list = convert_detections_to_list(detections_dict, classes)
134
+
135
+ # Skip objects with confidence lower than 0.4
136
+ # detections_list = skipbyconfidence(detections_list)
137
+
138
+ detections_list = crop_detections_with_xyxy(self.cfg, image_rgb_pil, detections_list)
139
+
140
+ detections_list = segmentImage(detections_list, image_rgb_pil)
141
+
142
+ detections_list = add_index_to_class(detections_list)
143
+
144
+ if two_class is not None:
145
+ if len(two_class)==2 and len(detections_list) != 2:
146
+ raise SkipImageException("Not all objects detected.")
147
+
148
+ if len(two_class)==1 and len(detections_list) != 1:
149
+ raise SkipImageException("Not all objects detected.")
150
+
151
+ if len(two_class)==3 and len(detections_list) != 3:
152
+ raise SkipImageException("Not all objects detected.")
153
+
154
+ if len(two_class)==2:
155
+ detections_two_class = [detections_list[0]['class_name'][:-1], detections_list[1]['class_name'][:-1]]
156
+ if two_class[0] not in detections_two_class or two_class[1] not in detections_two_class:
157
+ raise SkipImageException("Not all objects detected.")
158
+
159
+ if len(two_class)==3:
160
+ detections_two_class = [detections_list[0]['class_name'][:-1], detections_list[1]['class_name'][:-1], detections_list[2]['class_name'][:-1]]
161
+ if two_class[0] not in detections_two_class or two_class[1] not in detections_two_class or two_class[2] not in detections_two_class:
162
+ raise SkipImageException("Not all objects detected.")
163
+
164
+
165
+
166
+ if plot_som:
167
+ # Visualize with SoM
168
+ vis_som = draw_som_on_image(
169
+ detections_dict,
170
+ image_rgb,
171
+ label_mode="1",
172
+ alpha=0.4,
173
+ anno_mode=["Mask", "Mark", "Box"],
174
+ )
175
+ else:
176
+ vis_som = None
177
+
178
+
179
+
180
+ return vis_som, detections_list
181
+
182
+ # Copy the object area from the original image to a transparent background
183
+ def segmentImage(detections_list, image_rgb_pil):
184
+
185
+ for i in range(len(detections_list)):
186
+ image_pil = detections_list[i]['image_crop']
187
+ mask_pil = Image.fromarray(detections_list[i]['mask_crop'])
188
+
189
+ image_rgba = image_pil.convert("RGBA")
190
+
191
+ transparent_bg = Image.new("RGBA", image_rgba.size, (0, 0, 0, 0))
192
+
193
+ # Copy the object area from the original image to a transparent background using a mask
194
+ segmented_image = Image.composite(
195
+ image_rgba,
196
+ transparent_bg,
197
+ mask_pil
198
+ )
199
+
200
+ detections_list[i]['image_segment'] = segmented_image
201
+
202
+ return detections_list
203
+
204
+ def skipbyconfidence(detections_list):
205
+ skip_index = []
206
+ for i in range(len(detections_list)):
207
+ if detections_list[i]['confidence'] < 0.3:
208
+ skip_index.append(i)
209
+
210
+ for i in skip_index[::-1]:
211
+ del detections_list[i]
212
+
213
+ return detections_list
214
+
215
+ def add_bbox_and_taggingtext_to_image(image, detections_list):
216
+ for i in range(len(detections_list)):
217
+ bbox = detections_list[i]['xyxy']
218
+ label = detections_list[i]['class_name']
219
+ confidence = detections_list[i]['confidence']
220
+
221
+ cv2.rectangle(image, (int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3])), (0, 255, 0), 2)
222
+ cv2.putText(image, f"{label} {confidence:.2f}", (int(bbox[0]), int((bbox[1]+bbox[3])/2)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
223
+
224
+ return image
225
+
226
+ def add_index_to_class(detections_list):
227
+ # If a class appears for the first time, add 0 to the object's class_name, add 1 to the second appearance, and so on
228
+ class_index = {}
229
+ for detection in detections_list:
230
+ class_name = detection['class_name']
231
+ if class_name not in class_index:
232
+ class_index[class_name] = 0
233
+ else:
234
+ class_index[class_name] += 1
235
+
236
+ detection['class_name'] = f"{class_name}{class_index[class_name]}"
237
+ return detections_list
238
+
utils/__init__.py ADDED
File without changes
utils/logger.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import atexit
2
+ import json
3
+ import logging
4
+ import os
5
+ import sys
6
+
7
+ import numpy as np
8
+ import open3d as o3d
9
+ from termcolor import colored
10
+
11
+ __all__ = [
12
+ "setup_logger",
13
+ ]
14
+
15
+
16
+ def save_detection_list_to_json(detection_list, output_file):
17
+ def serialize_numpy(obj):
18
+ if isinstance(obj, np.ndarray):
19
+ return obj.tolist()
20
+ return obj
21
+
22
+ def serialize_open3d(obj):
23
+ if isinstance(obj, o3d.geometry.AxisAlignedBoundingBox):
24
+ return {
25
+ "type": "AxisAlignedBoundingBox",
26
+ "min_bound": obj.min_bound.tolist(),
27
+ "max_bound": obj.max_bound.tolist(),
28
+ }
29
+ elif isinstance(obj, o3d.geometry.OrientedBoundingBox):
30
+ return {
31
+ "type": "OrientedBoundingBox",
32
+ "center": obj.center.tolist(),
33
+ "extent": obj.extent.tolist(),
34
+ "R": obj.R.tolist(),
35
+ }
36
+ elif isinstance(obj, o3d.geometry.PointCloud):
37
+ return {
38
+ "type": "PointCloud",
39
+ "points": np.asarray(obj.points).tolist(),
40
+ "colors": np.asarray(obj.colors).tolist() if obj.has_colors() else None,
41
+ "normals": np.asarray(obj.normals).tolist() if obj.has_normals() else None,
42
+ }
43
+ return obj
44
+
45
+ def serialize_detection(detection):
46
+ serialized = {}
47
+ for key, value in detection.items():
48
+ if key in ["axis_aligned_bbox", "oriented_bbox", "pcd"]:
49
+ serialized[key] = serialize_open3d(value)
50
+ elif isinstance(value, np.ndarray):
51
+ serialized[key] = serialize_numpy(value)
52
+ elif isinstance(value, (list, dict, str, int, float, bool, type(None))):
53
+ serialized[key] = value
54
+ else:
55
+ serialized[key] = str(value) # Convert other types to string
56
+ return serialized
57
+
58
+ serialized_list = [serialize_detection(detection) for detection in detection_list]
59
+
60
+ with open(output_file, "w") as f:
61
+ json.dump(serialized_list, f, indent=2)
62
+
63
+ print(f"Detection list saved to {output_file}")
64
+
65
+
66
+ class SkipImageException(Exception):
67
+ def __init__(self, message="Known exception, skip the image."):
68
+ # Call the base class constructor with the parameters it needs
69
+ super().__init__(message)
70
+
71
+
72
+ class _ColorfulFormatter(logging.Formatter):
73
+ def __init__(self, *args, **kwargs):
74
+ self._root_name = kwargs.pop("root_name") + "."
75
+ self._abbrev_name = kwargs.pop("abbrev_name", "")
76
+ if len(self._abbrev_name):
77
+ self._abbrev_name = self._abbrev_name + "."
78
+ super().__init__(*args, **kwargs)
79
+
80
+ def formatMessage(self, record):
81
+ record.name = record.name.replace(self._root_name, self._abbrev_name)
82
+ log = super().formatMessage(record)
83
+ if record.levelno == logging.WARNING:
84
+ prefix = colored("WARNING", "red", attrs=["blink"])
85
+ elif record.levelno == logging.ERROR or record.levelno == logging.CRITICAL:
86
+ prefix = colored("ERROR", "red", attrs=["blink", "underline"])
87
+ else:
88
+ return log
89
+ return prefix + " " + log
90
+
91
+
92
+ def setup_logger(output=None, distributed_rank=0, *, name="metricdepth", color=True, abbrev_name=None):
93
+ """Initialize the detectron2 logger and set its verbosity level to "DEBUG".
94
+
95
+ Args:
96
+ output (str): a file name or a directory to save log. If None, will not save log file.
97
+ If ends with ".txt" or ".log", assumed to be a file name.
98
+ Otherwise, logs will be saved to `output/log.txt`.
99
+ abbrev_name (str): an abbreviation of the module, to avoid log names in logs.
100
+ Set to "" not log the root module in logs.
101
+ By default, will abbreviate "detectron2" to "d2" and leave other
102
+ modules unchanged.
103
+ Returns:
104
+ logging.Logger: a logger
105
+ """
106
+ logger = logging.getLogger()
107
+ logger.setLevel(logging.INFO) # NOTE: if more detailed, change it to logging.DEBUG
108
+ logger.propagate = False
109
+
110
+ if abbrev_name is None:
111
+ abbrev_name = "d2"
112
+
113
+ plain_formatter = logging.Formatter("[%(asctime)s] %(name)s %(levelname)s %(message)s ", datefmt="%m/%d %H:%M:%S")
114
+ # stdout logging: master only
115
+ if distributed_rank == 0:
116
+ ch = logging.StreamHandler(stream=sys.stdout)
117
+ ch.setLevel(logging.INFO) # NOTE: if more detailed, change it to logging.DEBUG
118
+ if color:
119
+ formatter = _ColorfulFormatter(
120
+ colored("[%(asctime)s %(name)s]: ", "green") + "%(message)s",
121
+ datefmt="%m/%d %H:%M:%S",
122
+ root_name=name,
123
+ abbrev_name=str(abbrev_name),
124
+ )
125
+ else:
126
+ formatter = plain_formatter
127
+ ch.setFormatter(formatter)
128
+ logger.addHandler(ch)
129
+
130
+ # file logging: all workers
131
+ if output is not None:
132
+ if output.endswith(".txt") or output.endswith(".log"):
133
+ filename = output
134
+ else:
135
+ filename = os.path.join(output, "log.txt")
136
+ if distributed_rank > 0:
137
+ filename = filename + f".rank{distributed_rank}"
138
+ os.makedirs(os.path.dirname(filename), exist_ok=True)
139
+
140
+ fh = logging.StreamHandler(_cached_log_stream(filename))
141
+ fh.setLevel(logging.INFO) # NOTE: if more detailed, change it to logging.DEBUG
142
+ fh.setFormatter(plain_formatter)
143
+ logger.addHandler(fh)
144
+
145
+ return logger
146
+
147
+
148
+ from iopath.common.file_io import PathManager as PathManagerBase
149
+
150
+ PathManager = PathManagerBase()
151
+
152
+
153
+ # cache the opened file object, so that different calls to 'setup_logger
154
+ # with the same file name can safely write to the same file.
155
+ def _cached_log_stream(filename):
156
+ # use 1K buffer if writting to cloud storage
157
+ io = PathManager.open(filename, "a", buffering=1024 if "://" in filename else -1)
158
+ atexit.register(io.close)
159
+ return io
visualizer/__pycache__/som.cpython-310.pyc ADDED
Binary file (46.4 kB). View file
 
visualizer/som.py ADDED
@@ -0,0 +1,1429 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ import colorsys
3
+ import logging
4
+ import math
5
+ import random
6
+ from enum import Enum, unique
7
+
8
+ import cv2
9
+ import matplotlib as mpl
10
+ import matplotlib.colors as mplc
11
+ import matplotlib.figure as mplfigure
12
+ import numpy as np
13
+ import pycocotools.mask as mask_util
14
+ import torch
15
+ from detectron2.data import MetadataCatalog
16
+ from detectron2.structures import BitMasks, Boxes, BoxMode, Keypoints, PolygonMasks, RotatedBoxes
17
+ from detectron2.utils.colormap import random_color
18
+ from detectron2.utils.file_io import PathManager
19
+ from matplotlib.backends.backend_agg import FigureCanvasAgg
20
+ from PIL import Image
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+ __all__ = ["ColorMode", "VisImage", "Visualizer"]
25
+
26
+ _SMALL_OBJECT_AREA_THRESH = 1000
27
+ _LARGE_MASK_AREA_THRESH = 120000
28
+ _OFF_WHITE = (1.0, 1.0, 240.0 / 255)
29
+ _BLACK = (0, 0, 0)
30
+ _RED = (1.0, 0, 0)
31
+
32
+ _KEYPOINT_THRESHOLD = 0.05
33
+
34
+ import numpy as np
35
+ from detectron2.data import MetadataCatalog
36
+ from PIL import Image
37
+
38
+ metadata = MetadataCatalog.get("coco_2017_train_panoptic")
39
+
40
+
41
+ def draw_mask_and_number_on_image(image_rgb, masks, labels, label_mode="1", alpha=0.1, anno_mode=["Mask"]):
42
+ img_width, img_height = image_rgb.size
43
+ visual = Visualizer(image_rgb, metadata=metadata)
44
+ for i in range(len(masks)):
45
+ mask = masks[i]
46
+ if mask.shape[0] != img_height or mask.shape[1] != img_width:
47
+ # Resize mask using PIL
48
+ mask_pil = Image.fromarray(mask)
49
+ mask_resized_pil = mask_pil.resize((img_width, img_height), Image.NEAREST)
50
+ mask = np.array(mask_resized_pil)
51
+
52
+ demo = visual.draw_binary_mask_with_number(
53
+ mask,
54
+ text=str(labels[i]),
55
+ label_mode=label_mode,
56
+ alpha=alpha,
57
+ anno_mode=anno_mode,
58
+ )
59
+ im = demo.get_image()
60
+ return im
61
+
62
+
63
+ def draw_som_on_image(detections_dict, image_rgb, label_mode="1", alpha=0.1, anno_mode=["Mask"]):
64
+ # img_width, img_height = image_rgb.size
65
+ visual = Visualizer(image_rgb, metadata=metadata)
66
+ label = 0
67
+ mask_map = np.zeros(image_rgb.shape, dtype=np.uint8)
68
+ for i in range(len(detections_dict["xyxy"])):
69
+ mask = detections_dict["mask"][i]
70
+ demo = visual.draw_binary_mask_with_number(
71
+ mask,
72
+ text=str(label),
73
+ label_mode=label_mode,
74
+ alpha=alpha,
75
+ anno_mode=anno_mode,
76
+ )
77
+ mask_map[mask == 1] = label
78
+ label += 1
79
+ im = demo.get_image()
80
+ return im
81
+
82
+
83
+ @unique
84
+ class ColorMode(Enum):
85
+ """Enum of different color modes to use for instance visualizations."""
86
+
87
+ IMAGE = 0
88
+ """Picks a random color for every instance and overlay segmentations with low opacity."""
89
+ SEGMENTATION = 1
90
+ """Let instances of the same category have similar colors (from metadata.thing_colors), and overlay them with high
91
+ opacity.
92
+
93
+ This provides more attention on the quality of segmentation.
94
+ """
95
+ IMAGE_BW = 2
96
+ """Same as IMAGE, but convert all areas without masks to gray-scale.
97
+
98
+ Only available for drawing per-instance mask predictions.
99
+ """
100
+
101
+
102
+ class GenericMask:
103
+ """
104
+ Attribute:
105
+ polygons (list[ndarray]): list[ndarray]: polygons for this mask.
106
+ Each ndarray has format [x, y, x, y, ...]
107
+ mask (ndarray): a binary mask
108
+ """
109
+
110
+ def __init__(self, mask_or_polygons, height, width):
111
+ self._mask = self._polygons = self._has_holes = None
112
+ self.height = height
113
+ self.width = width
114
+
115
+ m = mask_or_polygons
116
+ if isinstance(m, dict):
117
+ # RLEs
118
+ assert "counts" in m and "size" in m
119
+ if isinstance(m["counts"], list): # uncompressed RLEs
120
+ h, w = m["size"]
121
+ assert h == height and w == width
122
+ m = mask_util.frPyObjects(m, h, w)
123
+ self._mask = mask_util.decode(m)[:, :]
124
+ return
125
+
126
+ if isinstance(m, list): # list[ndarray]
127
+ self._polygons = [np.asarray(x).reshape(-1) for x in m]
128
+ return
129
+
130
+ if isinstance(m, np.ndarray): # assumed to be a binary mask
131
+ assert m.shape[1] != 2, m.shape
132
+ assert m.shape == (
133
+ height,
134
+ width,
135
+ ), f"mask shape: {m.shape}, target dims: {height}, {width}"
136
+ self._mask = m.astype("uint8")
137
+ return
138
+
139
+ raise ValueError(f"GenericMask cannot handle object {m} of type '{type(m)}'")
140
+
141
+ @property
142
+ def mask(self):
143
+ if self._mask is None:
144
+ self._mask = self.polygons_to_mask(self._polygons)
145
+ return self._mask
146
+
147
+ @property
148
+ def polygons(self):
149
+ if self._polygons is None:
150
+ self._polygons, self._has_holes = self.mask_to_polygons(self._mask)
151
+ return self._polygons
152
+
153
+ @property
154
+ def has_holes(self):
155
+ if self._has_holes is None:
156
+ if self._mask is not None:
157
+ self._polygons, self._has_holes = self.mask_to_polygons(self._mask)
158
+ else:
159
+ self._has_holes = False # if original format is polygon, does not have holes
160
+ return self._has_holes
161
+
162
+ def mask_to_polygons(self, mask):
163
+ # cv2.RETR_CCOMP flag retrieves all the contours and arranges them to a 2-level
164
+ # hierarchy. External contours (boundary) of the object are placed in hierarchy-1.
165
+ # Internal contours (holes) are placed in hierarchy-2.
166
+ # cv2.CHAIN_APPROX_NONE flag gets vertices of polygons from contours.
167
+ mask = np.ascontiguousarray(mask) # some versions of cv2 does not support incontiguous arr
168
+ res = cv2.findContours(mask.astype("uint8"), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
169
+ hierarchy = res[-1]
170
+ if hierarchy is None: # empty mask
171
+ return [], False
172
+ has_holes = (hierarchy.reshape(-1, 4)[:, 3] >= 0).sum() > 0
173
+ res = res[-2]
174
+ res = [x.flatten() for x in res]
175
+ # These coordinates from OpenCV are integers in range [0, W-1 or H-1].
176
+ # We add 0.5 to turn them into real-value coordinate space. A better solution
177
+ # would be to first +0.5 and then dilate the returned polygon by 0.5.
178
+ res = [x + 0.5 for x in res if len(x) >= 6]
179
+ return res, has_holes
180
+
181
+ def polygons_to_mask(self, polygons):
182
+ rle = mask_util.frPyObjects(polygons, self.height, self.width)
183
+ rle = mask_util.merge(rle)
184
+ return mask_util.decode(rle)[:, :]
185
+
186
+ def area(self):
187
+ return self.mask.sum()
188
+
189
+ def bbox(self):
190
+ p = mask_util.frPyObjects(self.polygons, self.height, self.width)
191
+ p = mask_util.merge(p)
192
+ bbox = mask_util.toBbox(p)
193
+ bbox[2] += bbox[0]
194
+ bbox[3] += bbox[1]
195
+ return bbox
196
+
197
+
198
+ class _PanopticPrediction:
199
+ """Unify different panoptic annotation/prediction formats."""
200
+
201
+ def __init__(self, panoptic_seg, segments_info, metadata=None):
202
+ if segments_info is None:
203
+ assert metadata is not None
204
+ # If "segments_info" is None, we assume "panoptic_img" is a
205
+ # H*W int32 image storing the panoptic_id in the format of
206
+ # category_id * label_divisor + instance_id. We reserve -1 for
207
+ # VOID label.
208
+ label_divisor = metadata.label_divisor
209
+ segments_info = []
210
+ for panoptic_label in np.unique(panoptic_seg.numpy()):
211
+ if panoptic_label == -1:
212
+ # VOID region.
213
+ continue
214
+ pred_class = panoptic_label // label_divisor
215
+ isthing = pred_class in metadata.thing_dataset_id_to_contiguous_id.values()
216
+ segments_info.append(
217
+ {
218
+ "id": int(panoptic_label),
219
+ "category_id": int(pred_class),
220
+ "isthing": bool(isthing),
221
+ }
222
+ )
223
+ del metadata
224
+
225
+ self._seg = panoptic_seg
226
+
227
+ self._sinfo = {s["id"]: s for s in segments_info} # seg id -> seg info
228
+ segment_ids, areas = torch.unique(panoptic_seg, sorted=True, return_counts=True)
229
+ areas = areas.numpy()
230
+ sorted_idxs = np.argsort(-areas)
231
+ self._seg_ids, self._seg_areas = segment_ids[sorted_idxs], areas[sorted_idxs]
232
+ self._seg_ids = self._seg_ids.tolist()
233
+ for sid, area in zip(self._seg_ids, self._seg_areas):
234
+ if sid in self._sinfo:
235
+ self._sinfo[sid]["area"] = float(area)
236
+
237
+ def non_empty_mask(self):
238
+ """
239
+ Returns:
240
+ (H, W) array, a mask for all pixels that have a prediction
241
+ """
242
+ empty_ids = []
243
+ for id in self._seg_ids:
244
+ if id not in self._sinfo:
245
+ empty_ids.append(id)
246
+ if len(empty_ids) == 0:
247
+ return np.zeros(self._seg.shape, dtype=np.uint8)
248
+ assert len(empty_ids) == 1, ">1 ids corresponds to no labels. This is currently not supported"
249
+ return (self._seg != empty_ids[0]).numpy().astype(np.bool)
250
+
251
+ def semantic_masks(self):
252
+ for sid in self._seg_ids:
253
+ sinfo = self._sinfo.get(sid)
254
+ if sinfo is None or sinfo["isthing"]:
255
+ # Some pixels (e.g. id 0 in PanopticFPN) have no instance or semantic predictions.
256
+ continue
257
+ yield (self._seg == sid).numpy().astype(np.bool), sinfo
258
+
259
+ def instance_masks(self):
260
+ for sid in self._seg_ids:
261
+ sinfo = self._sinfo.get(sid)
262
+ if sinfo is None or not sinfo["isthing"]:
263
+ continue
264
+ mask = (self._seg == sid).numpy().astype(np.bool)
265
+ if mask.sum() > 0:
266
+ yield mask, sinfo
267
+
268
+
269
+ def _create_text_labels(classes, scores, class_names, is_crowd=None):
270
+ """
271
+ Args:
272
+ classes (list[int] or None):
273
+ scores (list[float] or None):
274
+ class_names (list[str] or None):
275
+ is_crowd (list[bool] or None):
276
+
277
+ Returns:
278
+ list[str] or None
279
+ """
280
+ labels = None
281
+ if classes is not None:
282
+ if class_names is not None and len(class_names) > 0:
283
+ labels = [class_names[i] for i in classes]
284
+ else:
285
+ labels = [str(i) for i in classes]
286
+ if scores is not None:
287
+ if labels is None:
288
+ labels = [f"{s * 100:.0f}%" for s in scores]
289
+ else:
290
+ labels = [f"{l} {s * 100:.0f}%" for l, s in zip(labels, scores)]
291
+ if labels is not None and is_crowd is not None:
292
+ labels = [l + ("|crowd" if crowd else "") for l, crowd in zip(labels, is_crowd)]
293
+ return labels
294
+
295
+
296
+ class VisImage:
297
+ def __init__(self, img, scale=1.0):
298
+ """
299
+ Args:
300
+ img (ndarray): an RGB image of shape (H, W, 3) in range [0, 255].
301
+ scale (float): scale the input image
302
+ """
303
+ self.img = img
304
+ self.scale = scale
305
+ self.width, self.height = img.shape[1], img.shape[0]
306
+ self._setup_figure(img)
307
+
308
+ def _setup_figure(self, img):
309
+ """
310
+ Args:
311
+ Same as in :meth:`__init__()`.
312
+
313
+ Returns:
314
+ fig (matplotlib.pyplot.figure): top level container for all the image plot elements.
315
+ ax (matplotlib.pyplot.Axes): contains figure elements and sets the coordinate system.
316
+ """
317
+ fig = mplfigure.Figure(frameon=False)
318
+ self.dpi = fig.get_dpi()
319
+ # add a small 1e-2 to avoid precision lost due to matplotlib's truncation
320
+ # (https://github.com/matplotlib/matplotlib/issues/15363)
321
+ fig.set_size_inches(
322
+ (self.width * self.scale + 1e-2) / self.dpi,
323
+ (self.height * self.scale + 1e-2) / self.dpi,
324
+ )
325
+ self.canvas = FigureCanvasAgg(fig)
326
+ # self.canvas = mpl.backends.backend_cairo.FigureCanvasCairo(fig)
327
+ ax = fig.add_axes([0.0, 0.0, 1.0, 1.0])
328
+ ax.axis("off")
329
+ self.fig = fig
330
+ self.ax = ax
331
+ self.reset_image(img)
332
+
333
+ def reset_image(self, img):
334
+ """
335
+ Args:
336
+ img: same as in __init__
337
+ """
338
+ img = img.astype("uint8")
339
+ self.ax.imshow(img, extent=(0, self.width, self.height, 0), interpolation="nearest")
340
+
341
+ def save(self, filepath):
342
+ """
343
+ Args:
344
+ filepath (str): a string that contains the absolute path, including the file name, where
345
+ the visualized image will be saved.
346
+ """
347
+ self.fig.savefig(filepath)
348
+
349
+ def get_image(self):
350
+ """
351
+ Returns:
352
+ ndarray:
353
+ the visualized image of shape (H, W, 3) (RGB) in uint8 type.
354
+ The shape is scaled w.r.t the input image using the given `scale` argument.
355
+ """
356
+ canvas = self.canvas
357
+ s, (width, height) = canvas.print_to_buffer()
358
+ # buf = io.BytesIO() # works for cairo backend
359
+ # canvas.print_rgba(buf)
360
+ # width, height = self.width, self.height
361
+ # s = buf.getvalue()
362
+
363
+ buffer = np.frombuffer(s, dtype="uint8")
364
+
365
+ img_rgba = buffer.reshape(height, width, 4)
366
+ rgb, alpha = np.split(img_rgba, [3], axis=2)
367
+ return rgb.astype("uint8")
368
+
369
+
370
+ class Visualizer:
371
+ """Visualizer that draws data about detection/segmentation on images.
372
+
373
+ It contains methods like `draw_{text,box,circle,line,binary_mask,polygon}`
374
+ that draw primitive objects to images, as well as high-level wrappers like
375
+ `draw_{instance_predictions,sem_seg,panoptic_seg_predictions,dataset_dict}`
376
+ that draw composite data in some pre-defined style.
377
+
378
+ Note that the exact visualization style for the high-level wrappers are subject to change.
379
+ Style such as color, opacity, label contents, visibility of labels, or even the visibility
380
+ of objects themselves (e.g. when the object is too small) may change according
381
+ to different heuristics, as long as the results still look visually reasonable.
382
+
383
+ To obtain a consistent style, you can implement custom drawing functions with the
384
+ abovementioned primitive methods instead. If you need more customized visualization
385
+ styles, you can process the data yourself following their format documented in
386
+ tutorials (:doc:`/tutorials/models`, :doc:`/tutorials/datasets`). This class does not
387
+ intend to satisfy everyone's preference on drawing styles.
388
+
389
+ This visualizer focuses on high rendering quality rather than performance. It is not
390
+ designed to be used for real-time applications.
391
+ """
392
+
393
+ # TODO implement a fast, rasterized version using OpenCV
394
+
395
+ def __init__(self, img_rgb, metadata=None, scale=1.0, instance_mode=ColorMode.IMAGE):
396
+ """
397
+ Args:
398
+ img_rgb: a numpy array of shape (H, W, C), where H and W correspond to
399
+ the height and width of the image respectively. C is the number of
400
+ color channels. The image is required to be in RGB format since that
401
+ is a requirement of the Matplotlib library. The image is also expected
402
+ to be in the range [0, 255].
403
+ metadata (Metadata): dataset metadata (e.g. class names and colors)
404
+ instance_mode (ColorMode): defines one of the pre-defined style for drawing
405
+ instances on an image.
406
+ """
407
+ self.img = np.asarray(img_rgb).clip(0, 255).astype(np.uint8)
408
+ if metadata is None:
409
+ metadata = MetadataCatalog.get("__nonexist__")
410
+ self.metadata = metadata
411
+ self.output = VisImage(self.img, scale=scale)
412
+ self.cpu_device = torch.device("cpu")
413
+
414
+ # too small texts are useless, therefore clamp to 9
415
+ self._default_font_size = max(np.sqrt(self.output.height * self.output.width) // 90, 10 // scale)
416
+ self._default_font_size = 18
417
+ self._instance_mode = instance_mode
418
+ self.keypoint_threshold = _KEYPOINT_THRESHOLD
419
+
420
+ import matplotlib.colors as mcolors
421
+
422
+ css4_colors = mcolors.CSS4_COLORS
423
+ self.color_proposals = [list(mcolors.hex2color(color)) for color in css4_colors.values()]
424
+
425
+ def draw_instance_predictions(self, predictions):
426
+ """Draw instance-level prediction results on an image.
427
+
428
+ Args:
429
+ predictions (Instances): the output of an instance detection/segmentation
430
+ model. Following fields will be used to draw:
431
+ "pred_boxes", "pred_classes", "scores", "pred_masks" (or "pred_masks_rle").
432
+
433
+ Returns:
434
+ output (VisImage): image object with visualizations.
435
+ """
436
+ boxes = predictions.pred_boxes if predictions.has("pred_boxes") else None
437
+ scores = predictions.scores if predictions.has("scores") else None
438
+ classes = predictions.pred_classes.tolist() if predictions.has("pred_classes") else None
439
+ labels = _create_text_labels(classes, scores, self.metadata.get("thing_classes", None))
440
+ keypoints = predictions.pred_keypoints if predictions.has("pred_keypoints") else None
441
+
442
+ keep = (scores > 0.5).cpu()
443
+ boxes = boxes[keep]
444
+ scores = scores[keep]
445
+ classes = np.array(classes)
446
+ classes = classes[np.array(keep)]
447
+ labels = np.array(labels)
448
+ labels = labels[np.array(keep)]
449
+
450
+ if predictions.has("pred_masks"):
451
+ masks = np.asarray(predictions.pred_masks)
452
+ masks = masks[np.array(keep)]
453
+ masks = [GenericMask(x, self.output.height, self.output.width) for x in masks]
454
+ else:
455
+ masks = None
456
+
457
+ if self._instance_mode == ColorMode.SEGMENTATION and self.metadata.get("thing_colors"):
458
+ # if self.metadata.get("thing_colors"):
459
+ colors = [self._jitter([x / 255 for x in self.metadata.thing_colors[c]]) for c in classes]
460
+ alpha = 0.4
461
+ else:
462
+ colors = None
463
+ alpha = 0.4
464
+
465
+ if self._instance_mode == ColorMode.IMAGE_BW:
466
+ self.output.reset_image(
467
+ self._create_grayscale_image(
468
+ (predictions.pred_masks.any(dim=0) > 0).numpy() if predictions.has("pred_masks") else None
469
+ )
470
+ )
471
+ alpha = 0.3
472
+
473
+ self.overlay_instances(
474
+ masks=masks,
475
+ boxes=boxes,
476
+ labels=labels,
477
+ keypoints=keypoints,
478
+ assigned_colors=colors,
479
+ alpha=alpha,
480
+ )
481
+ return self.output
482
+
483
+ def draw_sem_seg(self, sem_seg, area_threshold=None, alpha=0.7):
484
+ """Draw semantic segmentation predictions/labels.
485
+
486
+ Args:
487
+ sem_seg (Tensor or ndarray): the segmentation of shape (H, W).
488
+ Each value is the integer label of the pixel.
489
+ area_threshold (int): segments with less than `area_threshold` are not drawn.
490
+ alpha (float): the larger it is, the more opaque the segmentations are.
491
+
492
+ Returns:
493
+ output (VisImage): image object with visualizations.
494
+ """
495
+ if isinstance(sem_seg, torch.Tensor):
496
+ sem_seg = sem_seg.numpy()
497
+ labels, areas = np.unique(sem_seg, return_counts=True)
498
+ sorted_idxs = np.argsort(-areas).tolist()
499
+ labels = labels[sorted_idxs]
500
+ for label in filter(lambda l: l < len(self.metadata.stuff_classes), labels):
501
+ try:
502
+ mask_color = [x / 255 for x in self.metadata.stuff_colors[label]]
503
+ except (AttributeError, IndexError):
504
+ mask_color = None
505
+
506
+ binary_mask = (sem_seg == label).astype(np.uint8)
507
+ text = self.metadata.stuff_classes[label]
508
+ self.draw_binary_mask(
509
+ binary_mask,
510
+ color=mask_color,
511
+ edge_color=_OFF_WHITE,
512
+ text=text,
513
+ alpha=alpha,
514
+ area_threshold=area_threshold,
515
+ )
516
+ return self.output
517
+
518
+ def draw_panoptic_seg(self, panoptic_seg, segments_info, area_threshold=None, alpha=0.7):
519
+ """Draw panoptic prediction annotations or results.
520
+
521
+ Args:
522
+ panoptic_seg (Tensor): of shape (height, width) where the values are ids for each
523
+ segment.
524
+ segments_info (list[dict] or None): Describe each segment in `panoptic_seg`.
525
+ If it is a ``list[dict]``, each dict contains keys "id", "category_id".
526
+ If None, category id of each pixel is computed by
527
+ ``pixel // metadata.label_divisor``.
528
+ area_threshold (int): stuff segments with less than `area_threshold` are not drawn.
529
+
530
+ Returns:
531
+ output (VisImage): image object with visualizations.
532
+ """
533
+ pred = _PanopticPrediction(panoptic_seg, segments_info, self.metadata)
534
+
535
+ if self._instance_mode == ColorMode.IMAGE_BW:
536
+ self.output.reset_image(self._create_grayscale_image(pred.non_empty_mask()))
537
+
538
+ # draw mask for all semantic segments first i.e. "stuff"
539
+ for mask, sinfo in pred.semantic_masks():
540
+ category_idx = sinfo["category_id"]
541
+ try:
542
+ mask_color = [x / 255 for x in self.metadata.stuff_colors[category_idx]]
543
+ except AttributeError:
544
+ mask_color = None
545
+
546
+ text = self.metadata.stuff_classes[category_idx].replace("-other", "").replace("-merged", "")
547
+ self.draw_binary_mask(
548
+ mask,
549
+ color=mask_color,
550
+ edge_color=_OFF_WHITE,
551
+ text=text,
552
+ alpha=alpha,
553
+ area_threshold=area_threshold,
554
+ )
555
+
556
+ # draw mask for all instances second
557
+ all_instances = list(pred.instance_masks())
558
+ if len(all_instances) == 0:
559
+ return self.output
560
+ masks, sinfo = list(zip(*all_instances))
561
+ category_ids = [x["category_id"] for x in sinfo]
562
+
563
+ try:
564
+ scores = [x["score"] for x in sinfo]
565
+ except KeyError:
566
+ scores = None
567
+ class_names = [name.replace("-other", "").replace("-merged", "") for name in self.metadata.thing_classes]
568
+ labels = _create_text_labels(category_ids, scores, class_names, [x.get("iscrowd", 0) for x in sinfo])
569
+
570
+ try:
571
+ colors = [self._jitter([x / 255 for x in self.metadata.thing_colors[c]]) for c in category_ids]
572
+ except AttributeError:
573
+ colors = None
574
+ self.overlay_instances(masks=masks, labels=labels, assigned_colors=colors, alpha=alpha)
575
+
576
+ return self.output
577
+
578
+ draw_panoptic_seg_predictions = draw_panoptic_seg # backward compatibility
579
+
580
+ def draw_dataset_dict(self, dic):
581
+ """Draw annotations/segmentaions in Detectron2 Dataset format.
582
+
583
+ Args:
584
+ dic (dict): annotation/segmentation data of one image, in Detectron2 Dataset format.
585
+
586
+ Returns:
587
+ output (VisImage): image object with visualizations.
588
+ """
589
+ annos = dic.get("annotations", None)
590
+ if annos:
591
+ if "segmentation" in annos[0]:
592
+ masks = [x["segmentation"] for x in annos]
593
+ else:
594
+ masks = None
595
+ if "keypoints" in annos[0]:
596
+ keypts = [x["keypoints"] for x in annos]
597
+ keypts = np.array(keypts).reshape(len(annos), -1, 3)
598
+ else:
599
+ keypts = None
600
+
601
+ boxes = [
602
+ BoxMode.convert(x["bbox"], x["bbox_mode"], BoxMode.XYXY_ABS) if len(x["bbox"]) == 4 else x["bbox"]
603
+ for x in annos
604
+ ]
605
+
606
+ colors = None
607
+ category_ids = [x["category_id"] for x in annos]
608
+ if self._instance_mode == ColorMode.SEGMENTATION and self.metadata.get("thing_colors"):
609
+ colors = [self._jitter([x / 255 for x in self.metadata.thing_colors[c]]) for c in category_ids]
610
+ names = self.metadata.get("thing_classes", None)
611
+ labels = _create_text_labels(
612
+ category_ids,
613
+ scores=None,
614
+ class_names=names,
615
+ is_crowd=[x.get("iscrowd", 0) for x in annos],
616
+ )
617
+ self.overlay_instances(
618
+ labels=labels,
619
+ boxes=boxes,
620
+ masks=masks,
621
+ keypoints=keypts,
622
+ assigned_colors=colors,
623
+ )
624
+
625
+ sem_seg = dic.get("sem_seg", None)
626
+ if sem_seg is None and "sem_seg_file_name" in dic:
627
+ with PathManager.open(dic["sem_seg_file_name"], "rb") as f:
628
+ sem_seg = Image.open(f)
629
+ sem_seg = np.asarray(sem_seg, dtype="uint8")
630
+ if sem_seg is not None:
631
+ self.draw_sem_seg(sem_seg, area_threshold=0, alpha=0.4)
632
+
633
+ pan_seg = dic.get("pan_seg", None)
634
+ if pan_seg is None and "pan_seg_file_name" in dic:
635
+ with PathManager.open(dic["pan_seg_file_name"], "rb") as f:
636
+ pan_seg = Image.open(f)
637
+ pan_seg = np.asarray(pan_seg)
638
+ from panopticapi.utils import rgb2id
639
+
640
+ pan_seg = rgb2id(pan_seg)
641
+ if pan_seg is not None:
642
+ segments_info = dic["segments_info"]
643
+ pan_seg = torch.tensor(pan_seg)
644
+ self.draw_panoptic_seg(pan_seg, segments_info, area_threshold=0, alpha=0.7)
645
+ return self.output
646
+
647
+ def overlay_instances(
648
+ self,
649
+ *,
650
+ boxes=None,
651
+ labels=None,
652
+ masks=None,
653
+ keypoints=None,
654
+ assigned_colors=None,
655
+ alpha=0.5,
656
+ ):
657
+ """
658
+ Args:
659
+ boxes (Boxes, RotatedBoxes or ndarray): either a :class:`Boxes`,
660
+ or an Nx4 numpy array of XYXY_ABS format for the N objects in a single image,
661
+ or a :class:`RotatedBoxes`,
662
+ or an Nx5 numpy array of (x_center, y_center, width, height, angle_degrees) format
663
+ for the N objects in a single image,
664
+ labels (list[str]): the text to be displayed for each instance.
665
+ masks (masks-like object): Supported types are:
666
+
667
+ * :class:`detectron2.structures.PolygonMasks`,
668
+ :class:`detectron2.structures.BitMasks`.
669
+ * list[list[ndarray]]: contains the segmentation masks for all objects in one image.
670
+ The first level of the list corresponds to individual instances. The second
671
+ level to all the polygon that compose the instance, and the third level
672
+ to the polygon coordinates. The third level should have the format of
673
+ [x0, y0, x1, y1, ..., xn, yn] (n >= 3).
674
+ * list[ndarray]: each ndarray is a binary mask of shape (H, W).
675
+ * list[dict]: each dict is a COCO-style RLE.
676
+ keypoints (Keypoint or array like): an array-like object of shape (N, K, 3),
677
+ where the N is the number of instances and K is the number of keypoints.
678
+ The last dimension corresponds to (x, y, visibility or score).
679
+ assigned_colors (list[matplotlib.colors]): a list of colors, where each color
680
+ corresponds to each mask or box in the image. Refer to 'matplotlib.colors'
681
+ for full list of formats that the colors are accepted in.
682
+ Returns:
683
+ output (VisImage): image object with visualizations.
684
+ """
685
+ num_instances = 0
686
+ if boxes is not None:
687
+ boxes = self._convert_boxes(boxes)
688
+ num_instances = len(boxes)
689
+ if masks is not None:
690
+ masks = self._convert_masks(masks)
691
+ if num_instances:
692
+ assert len(masks) == num_instances
693
+ else:
694
+ num_instances = len(masks)
695
+ if keypoints is not None:
696
+ if num_instances:
697
+ assert len(keypoints) == num_instances
698
+ else:
699
+ num_instances = len(keypoints)
700
+ keypoints = self._convert_keypoints(keypoints)
701
+ if labels is not None:
702
+ assert len(labels) == num_instances
703
+ if assigned_colors is None:
704
+ assigned_colors = [random_color(rgb=True, maximum=1) for _ in range(num_instances)]
705
+ if num_instances == 0:
706
+ return self.output
707
+ if boxes is not None and boxes.shape[1] == 5:
708
+ return self.overlay_rotated_instances(boxes=boxes, labels=labels, assigned_colors=assigned_colors)
709
+
710
+ # Display in largest to smallest order to reduce occlusion.
711
+ areas = None
712
+ if boxes is not None:
713
+ areas = np.prod(boxes[:, 2:] - boxes[:, :2], axis=1)
714
+ elif masks is not None:
715
+ areas = np.asarray([x.area() for x in masks])
716
+
717
+ if areas is not None:
718
+ sorted_idxs = np.argsort(-areas).tolist()
719
+ # Re-order overlapped instances in descending order.
720
+ boxes = boxes[sorted_idxs] if boxes is not None else None
721
+ labels = [labels[k] for k in sorted_idxs] if labels is not None else None
722
+ masks = [masks[idx] for idx in sorted_idxs] if masks is not None else None
723
+ assigned_colors = [assigned_colors[idx] for idx in sorted_idxs]
724
+ keypoints = keypoints[sorted_idxs] if keypoints is not None else None
725
+
726
+ for i in range(num_instances):
727
+ color = assigned_colors[i]
728
+ if boxes is not None:
729
+ self.draw_box(boxes[i], edge_color=color)
730
+
731
+ if masks is not None:
732
+ for segment in masks[i].polygons:
733
+ self.draw_polygon(segment.reshape(-1, 2), color, alpha=alpha)
734
+
735
+ if labels is not None:
736
+ # first get a box
737
+ if boxes is not None:
738
+ x0, y0, x1, y1 = boxes[i]
739
+ text_pos = (x0, y0) # if drawing boxes, put text on the box corner.
740
+ horiz_align = "left"
741
+ elif masks is not None:
742
+ # skip small mask without polygon
743
+ if len(masks[i].polygons) == 0:
744
+ continue
745
+
746
+ x0, y0, x1, y1 = masks[i].bbox()
747
+
748
+ # draw text in the center (defined by median) when box is not drawn
749
+ # median is less sensitive to outliers.
750
+ text_pos = np.median(masks[i].mask.nonzero(), axis=1)[::-1]
751
+ horiz_align = "center"
752
+ else:
753
+ continue # drawing the box confidence for keypoints isn't very useful.
754
+ # for small objects, draw text at the side to avoid occlusion
755
+ instance_area = (y1 - y0) * (x1 - x0)
756
+ if instance_area < _SMALL_OBJECT_AREA_THRESH * self.output.scale or y1 - y0 < 40 * self.output.scale:
757
+ if y1 >= self.output.height - 5:
758
+ text_pos = (x1, y0)
759
+ else:
760
+ text_pos = (x0, y1)
761
+
762
+ height_ratio = (y1 - y0) / np.sqrt(self.output.height * self.output.width)
763
+ lighter_color = self._change_color_brightness(color, brightness_factor=0.7)
764
+ font_size = np.clip((height_ratio - 0.02) / 0.08 + 1, 1.2, 2) * 0.5 * self._default_font_size
765
+ self.draw_text(
766
+ labels[i],
767
+ text_pos,
768
+ color=lighter_color,
769
+ horizontal_alignment=horiz_align,
770
+ font_size=font_size,
771
+ )
772
+
773
+ # draw keypoints
774
+ if keypoints is not None:
775
+ for keypoints_per_instance in keypoints:
776
+ self.draw_and_connect_keypoints(keypoints_per_instance)
777
+
778
+ return self.output
779
+
780
+ def overlay_rotated_instances(self, boxes=None, labels=None, assigned_colors=None):
781
+ """
782
+ Args:
783
+ boxes (ndarray): an Nx5 numpy array of
784
+ (x_center, y_center, width, height, angle_degrees) format
785
+ for the N objects in a single image.
786
+ labels (list[str]): the text to be displayed for each instance.
787
+ assigned_colors (list[matplotlib.colors]): a list of colors, where each color
788
+ corresponds to each mask or box in the image. Refer to 'matplotlib.colors'
789
+ for full list of formats that the colors are accepted in.
790
+
791
+ Returns:
792
+ output (VisImage): image object with visualizations.
793
+ """
794
+ num_instances = len(boxes)
795
+
796
+ if assigned_colors is None:
797
+ assigned_colors = [random_color(rgb=True, maximum=1) for _ in range(num_instances)]
798
+ if num_instances == 0:
799
+ return self.output
800
+
801
+ # Display in largest to smallest order to reduce occlusion.
802
+ if boxes is not None:
803
+ areas = boxes[:, 2] * boxes[:, 3]
804
+
805
+ sorted_idxs = np.argsort(-areas).tolist()
806
+ # Re-order overlapped instances in descending order.
807
+ boxes = boxes[sorted_idxs]
808
+ labels = [labels[k] for k in sorted_idxs] if labels is not None else None
809
+ colors = [assigned_colors[idx] for idx in sorted_idxs]
810
+
811
+ for i in range(num_instances):
812
+ self.draw_rotated_box_with_label(
813
+ boxes[i],
814
+ edge_color=colors[i],
815
+ label=labels[i] if labels is not None else None,
816
+ )
817
+
818
+ return self.output
819
+
820
+ def draw_and_connect_keypoints(self, keypoints):
821
+ """Draws keypoints of an instance and follows the rules for keypoint connections to draw lines between
822
+ appropriate keypoints. This follows color heuristics for line color.
823
+
824
+ Args:
825
+ keypoints (Tensor): a tensor of shape (K, 3), where K is the number of keypoints
826
+ and the last dimension corresponds to (x, y, probability).
827
+
828
+ Returns:
829
+ output (VisImage): image object with visualizations.
830
+ """
831
+ visible = {}
832
+ keypoint_names = self.metadata.get("keypoint_names")
833
+ for idx, keypoint in enumerate(keypoints):
834
+ # draw keypoint
835
+ x, y, prob = keypoint
836
+ if prob > self.keypoint_threshold:
837
+ self.draw_circle((x, y), color=_RED)
838
+ if keypoint_names:
839
+ keypoint_name = keypoint_names[idx]
840
+ visible[keypoint_name] = (x, y)
841
+
842
+ if self.metadata.get("keypoint_connection_rules"):
843
+ for kp0, kp1, color in self.metadata.keypoint_connection_rules:
844
+ if kp0 in visible and kp1 in visible:
845
+ x0, y0 = visible[kp0]
846
+ x1, y1 = visible[kp1]
847
+ color = tuple(x / 255.0 for x in color)
848
+ self.draw_line([x0, x1], [y0, y1], color=color)
849
+
850
+ # draw lines from nose to mid-shoulder and mid-shoulder to mid-hip
851
+ # Note that this strategy is specific to person keypoints.
852
+ # For other keypoints, it should just do nothing
853
+ try:
854
+ ls_x, ls_y = visible["left_shoulder"]
855
+ rs_x, rs_y = visible["right_shoulder"]
856
+ mid_shoulder_x, mid_shoulder_y = (ls_x + rs_x) / 2, (ls_y + rs_y) / 2
857
+ except KeyError:
858
+ pass
859
+ else:
860
+ # draw line from nose to mid-shoulder
861
+ nose_x, nose_y = visible.get("nose", (None, None))
862
+ if nose_x is not None:
863
+ self.draw_line([nose_x, mid_shoulder_x], [nose_y, mid_shoulder_y], color=_RED)
864
+
865
+ try:
866
+ # draw line from mid-shoulder to mid-hip
867
+ lh_x, lh_y = visible["left_hip"]
868
+ rh_x, rh_y = visible["right_hip"]
869
+ except KeyError:
870
+ pass
871
+ else:
872
+ mid_hip_x, mid_hip_y = (lh_x + rh_x) / 2, (lh_y + rh_y) / 2
873
+ self.draw_line([mid_hip_x, mid_shoulder_x], [mid_hip_y, mid_shoulder_y], color=_RED)
874
+ return self.output
875
+
876
+ """
877
+ Primitive drawing functions:
878
+ """
879
+
880
+ def draw_text(
881
+ self,
882
+ text,
883
+ position,
884
+ *,
885
+ font_size=None,
886
+ color="g",
887
+ horizontal_alignment="center",
888
+ rotation=0,
889
+ ):
890
+ """
891
+ Args:
892
+ text (str): class label
893
+ position (tuple): a tuple of the x and y coordinates to place text on image.
894
+ font_size (int, optional): font of the text. If not provided, a font size
895
+ proportional to the image width is calculated and used.
896
+ color: color of the text. Refer to `matplotlib.colors` for full list
897
+ of formats that are accepted.
898
+ horizontal_alignment (str): see `matplotlib.text.Text`
899
+ rotation: rotation angle in degrees CCW
900
+
901
+ Returns:
902
+ output (VisImage): image object with text drawn.
903
+ """
904
+ if not font_size:
905
+ font_size = self._default_font_size
906
+
907
+ # since the text background is dark, we don't want the text to be dark
908
+ color = np.maximum(list(mplc.to_rgb(color)), 0.15)
909
+ color[np.argmax(color)] = max(0.8, np.max(color))
910
+
911
+ def contrasting_color(rgb):
912
+ """Returns 'white' or 'black' depending on which color contrasts more with the given RGB value."""
913
+
914
+ # Decompose the RGB tuple
915
+ R, G, B = rgb
916
+
917
+ # Calculate the Y value
918
+ Y = 0.299 * R + 0.587 * G + 0.114 * B
919
+
920
+ # If Y value is greater than 128, it's closer to white so return black. Otherwise, return white.
921
+ return "black" if Y > 128 else "white"
922
+
923
+ bbox_background = contrasting_color(color * 255)
924
+
925
+ x, y = position
926
+ self.output.ax.text(
927
+ x,
928
+ y,
929
+ text,
930
+ size=font_size * self.output.scale,
931
+ family="sans-serif",
932
+ bbox={
933
+ "facecolor": bbox_background,
934
+ "alpha": 0.8,
935
+ "pad": 0.7,
936
+ "edgecolor": "none",
937
+ },
938
+ verticalalignment="top",
939
+ horizontalalignment=horizontal_alignment,
940
+ color=color,
941
+ zorder=10,
942
+ rotation=rotation,
943
+ )
944
+ return self.output
945
+
946
+ def draw_box(self, box_coord, alpha=0.5, edge_color="g", line_style="-"):
947
+ """
948
+ Args:
949
+ box_coord (tuple): a tuple containing x0, y0, x1, y1 coordinates, where x0 and y0
950
+ are the coordinates of the image's top left corner. x1 and y1 are the
951
+ coordinates of the image's bottom right corner.
952
+ alpha (float): blending efficient. Smaller values lead to more transparent masks.
953
+ edge_color: color of the outline of the box. Refer to `matplotlib.colors`
954
+ for full list of formats that are accepted.
955
+ line_style (string): the string to use to create the outline of the boxes.
956
+
957
+ Returns:
958
+ output (VisImage): image object with box drawn.
959
+ """
960
+ x0, y0, x1, y1 = box_coord
961
+ width = x1 - x0
962
+ height = y1 - y0
963
+
964
+ linewidth = max(self._default_font_size / 12, 1)
965
+
966
+ self.output.ax.add_patch(
967
+ mpl.patches.Rectangle(
968
+ (x0, y0),
969
+ width,
970
+ height,
971
+ fill=False,
972
+ edgecolor=edge_color,
973
+ linewidth=linewidth * self.output.scale,
974
+ alpha=alpha,
975
+ linestyle=line_style,
976
+ )
977
+ )
978
+ return self.output
979
+
980
+ def draw_rotated_box_with_label(self, rotated_box, alpha=0.5, edge_color="g", line_style="-", label=None):
981
+ """Draw a rotated box with label on its top-left corner.
982
+
983
+ Args:
984
+ rotated_box (tuple): a tuple containing (cnt_x, cnt_y, w, h, angle),
985
+ where cnt_x and cnt_y are the center coordinates of the box.
986
+ w and h are the width and height of the box. angle represents how
987
+ many degrees the box is rotated CCW with regard to the 0-degree box.
988
+ alpha (float): blending efficient. Smaller values lead to more transparent masks.
989
+ edge_color: color of the outline of the box. Refer to `matplotlib.colors`
990
+ for full list of formats that are accepted.
991
+ line_style (string): the string to use to create the outline of the boxes.
992
+ label (string): label for rotated box. It will not be rendered when set to None.
993
+
994
+ Returns:
995
+ output (VisImage): image object with box drawn.
996
+ """
997
+ cnt_x, cnt_y, w, h, angle = rotated_box
998
+ area = w * h
999
+ # use thinner lines when the box is small
1000
+ linewidth = self._default_font_size / (6 if area < _SMALL_OBJECT_AREA_THRESH * self.output.scale else 3)
1001
+
1002
+ theta = angle * math.pi / 180.0
1003
+ c = math.cos(theta)
1004
+ s = math.sin(theta)
1005
+ rect = [(-w / 2, h / 2), (-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, h / 2)]
1006
+ # x: left->right ; y: top->down
1007
+ rotated_rect = [(s * yy + c * xx + cnt_x, c * yy - s * xx + cnt_y) for (xx, yy) in rect]
1008
+ for k in range(4):
1009
+ j = (k + 1) % 4
1010
+ self.draw_line(
1011
+ [rotated_rect[k][0], rotated_rect[j][0]],
1012
+ [rotated_rect[k][1], rotated_rect[j][1]],
1013
+ color=edge_color,
1014
+ linestyle="--" if k == 1 else line_style,
1015
+ linewidth=linewidth,
1016
+ )
1017
+
1018
+ if label is not None:
1019
+ text_pos = rotated_rect[1] # topleft corner
1020
+
1021
+ height_ratio = h / np.sqrt(self.output.height * self.output.width)
1022
+ label_color = self._change_color_brightness(edge_color, brightness_factor=0.7)
1023
+ font_size = np.clip((height_ratio - 0.02) / 0.08 + 1, 1.2, 2) * 0.5 * self._default_font_size
1024
+ self.draw_text(label, text_pos, color=label_color, font_size=font_size, rotation=angle)
1025
+
1026
+ return self.output
1027
+
1028
+ def draw_circle(self, circle_coord, color, radius=3):
1029
+ """
1030
+ Args:
1031
+ circle_coord (list(int) or tuple(int)): contains the x and y coordinates
1032
+ of the center of the circle.
1033
+ color: color of the polygon. Refer to `matplotlib.colors` for a full list of
1034
+ formats that are accepted.
1035
+ radius (int): radius of the circle.
1036
+
1037
+ Returns:
1038
+ output (VisImage): image object with box drawn.
1039
+ """
1040
+ x, y = circle_coord
1041
+ self.output.ax.add_patch(mpl.patches.Circle(circle_coord, radius=radius, fill=True, color=color))
1042
+ return self.output
1043
+
1044
+ def draw_line(self, x_data, y_data, color, linestyle="-", linewidth=None):
1045
+ """
1046
+ Args:
1047
+ x_data (list[int]): a list containing x values of all the points being drawn.
1048
+ Length of list should match the length of y_data.
1049
+ y_data (list[int]): a list containing y values of all the points being drawn.
1050
+ Length of list should match the length of x_data.
1051
+ color: color of the line. Refer to `matplotlib.colors` for a full list of
1052
+ formats that are accepted.
1053
+ linestyle: style of the line. Refer to `matplotlib.lines.Line2D`
1054
+ for a full list of formats that are accepted.
1055
+ linewidth (float or None): width of the line. When it's None,
1056
+ a default value will be computed and used.
1057
+
1058
+ Returns:
1059
+ output (VisImage): image object with line drawn.
1060
+ """
1061
+ if linewidth is None:
1062
+ linewidth = self._default_font_size / 3
1063
+ linewidth = max(linewidth, 1)
1064
+ self.output.ax.add_line(
1065
+ mpl.lines.Line2D(
1066
+ x_data,
1067
+ y_data,
1068
+ linewidth=linewidth * self.output.scale,
1069
+ color=color,
1070
+ linestyle=linestyle,
1071
+ )
1072
+ )
1073
+ return self.output
1074
+
1075
+ def draw_binary_mask(
1076
+ self,
1077
+ binary_mask,
1078
+ color=None,
1079
+ *,
1080
+ edge_color=None,
1081
+ text=None,
1082
+ alpha=0.7,
1083
+ area_threshold=10,
1084
+ ):
1085
+ """
1086
+ Args:
1087
+ binary_mask (ndarray): numpy array of shape (H, W), where H is the image height and
1088
+ W is the image width. Each value in the array is either a 0 or 1 value of uint8
1089
+ type.
1090
+ color: color of the mask. Refer to `matplotlib.colors` for a full list of
1091
+ formats that are accepted. If None, will pick a random color.
1092
+ edge_color: color of the polygon edges. Refer to `matplotlib.colors` for a
1093
+ full list of formats that are accepted.
1094
+ text (str): if None, will be drawn on the object
1095
+ alpha (float): blending efficient. Smaller values lead to more transparent masks.
1096
+ area_threshold (float): a connected component smaller than this area will not be shown.
1097
+
1098
+ Returns:
1099
+ output (VisImage): image object with mask drawn.
1100
+ """
1101
+ if color is None:
1102
+ color = random_color(rgb=True, maximum=1)
1103
+ color = mplc.to_rgb(color)
1104
+
1105
+ has_valid_segment = False
1106
+ binary_mask = binary_mask.astype("uint8") # opencv needs uint8
1107
+ mask = GenericMask(binary_mask, self.output.height, self.output.width)
1108
+ shape2d = (binary_mask.shape[0], binary_mask.shape[1])
1109
+
1110
+ if not mask.has_holes:
1111
+ # draw polygons for regular masks
1112
+ for segment in mask.polygons:
1113
+ area = mask_util.area(mask_util.frPyObjects([segment], shape2d[0], shape2d[1]))
1114
+ if area < (area_threshold or 0):
1115
+ continue
1116
+ has_valid_segment = True
1117
+ segment = segment.reshape(-1, 2)
1118
+ self.draw_polygon(segment, color=color, edge_color=edge_color, alpha=alpha)
1119
+ else:
1120
+ # TODO: Use Path/PathPatch to draw vector graphics:
1121
+ # https://stackoverflow.com/questions/8919719/how-to-plot-a-complex-polygon
1122
+ rgba = np.zeros(shape2d + (4,), dtype="float32")
1123
+ rgba[:, :, :3] = color
1124
+ rgba[:, :, 3] = (mask.mask == 1).astype("float32") * alpha
1125
+ has_valid_segment = True
1126
+ self.output.ax.imshow(rgba, extent=(0, self.output.width, self.output.height, 0))
1127
+
1128
+ if text is not None and has_valid_segment:
1129
+ lighter_color = self._change_color_brightness(color, brightness_factor=0.7)
1130
+ self._draw_text_in_mask(binary_mask, text, lighter_color)
1131
+ return self.output
1132
+
1133
+ def draw_binary_mask_with_number(
1134
+ self,
1135
+ binary_mask,
1136
+ color=None,
1137
+ *,
1138
+ edge_color=None,
1139
+ text=None,
1140
+ label_mode="1",
1141
+ alpha=0.1,
1142
+ anno_mode=["Mask"],
1143
+ area_threshold=10,
1144
+ ):
1145
+ """
1146
+ Args:
1147
+ binary_mask (ndarray): numpy array of shape (H, W), where H is the image height and
1148
+ W is the image width. Each value in the array is either a 0 or 1 value of uint8
1149
+ type.
1150
+ color: color of the mask. Refer to `matplotlib.colors` for a full list of
1151
+ formats that are accepted. If None, will pick a random color.
1152
+ edge_color: color of the polygon edges. Refer to `matplotlib.colors` for a
1153
+ full list of formats that are accepted.
1154
+ text (str): if None, will be drawn on the object
1155
+ alpha (float): blending efficient. Smaller values lead to more transparent masks.
1156
+ area_threshold (float): a connected component smaller than this area will not be shown.
1157
+
1158
+ Returns:
1159
+ output (VisImage): image object with mask drawn.
1160
+ """
1161
+ if color is None:
1162
+ randint = random.randint(0, len(self.color_proposals) - 1)
1163
+ color = self.color_proposals[randint]
1164
+ color = mplc.to_rgb(color)
1165
+
1166
+ has_valid_segment = True
1167
+ binary_mask = binary_mask.astype("uint8") # opencv needs uint8
1168
+ mask = GenericMask(binary_mask, self.output.height, self.output.width)
1169
+ shape2d = (binary_mask.shape[0], binary_mask.shape[1])
1170
+ bbox = mask.bbox()
1171
+
1172
+ if "Mask" in anno_mode:
1173
+ if not mask.has_holes:
1174
+ # draw polygons for regular masks
1175
+ for segment in mask.polygons:
1176
+ area = mask_util.area(mask_util.frPyObjects([segment], shape2d[0], shape2d[1]))
1177
+ if area < (area_threshold or 0):
1178
+ continue
1179
+ has_valid_segment = True
1180
+ segment = segment.reshape(-1, 2)
1181
+ self.draw_polygon(segment, color=color, edge_color=edge_color, alpha=alpha)
1182
+ else:
1183
+ # TODO: Use Path/PathPatch to draw vector graphics:
1184
+ # https://stackoverflow.com/questions/8919719/how-to-plot-a-complex-polygon
1185
+ rgba = np.zeros(shape2d + (4,), dtype="float32")
1186
+ rgba[:, :, :3] = color
1187
+ rgba[:, :, 3] = (mask.mask == 1).astype("float32") * alpha
1188
+ has_valid_segment = True
1189
+ self.output.ax.imshow(rgba, extent=(0, self.output.width, self.output.height, 0))
1190
+
1191
+ if "Box" in anno_mode:
1192
+ self.draw_box(bbox, edge_color=color, alpha=0.75)
1193
+
1194
+ if "Mark" in anno_mode:
1195
+ has_valid_segment = True
1196
+ else:
1197
+ has_valid_segment = False
1198
+
1199
+ if text is not None and has_valid_segment:
1200
+ # lighter_color = tuple([x*0.2 for x in color])
1201
+ lighter_color = [
1202
+ 1,
1203
+ 1,
1204
+ 1,
1205
+ ] # self._change_color_brightness(color, brightness_factor=0.7)
1206
+ self._draw_number_in_mask(binary_mask, text, lighter_color, label_mode)
1207
+ return self.output
1208
+
1209
+ def draw_soft_mask(self, soft_mask, color=None, *, text=None, alpha=0.5):
1210
+ """
1211
+ Args:
1212
+ soft_mask (ndarray): float array of shape (H, W), each value in [0, 1].
1213
+ color: color of the mask. Refer to `matplotlib.colors` for a full list of
1214
+ formats that are accepted. If None, will pick a random color.
1215
+ text (str): if None, will be drawn on the object
1216
+ alpha (float): blending efficient. Smaller values lead to more transparent masks.
1217
+
1218
+ Returns:
1219
+ output (VisImage): image object with mask drawn.
1220
+ """
1221
+ if color is None:
1222
+ color = random_color(rgb=True, maximum=1)
1223
+ color = mplc.to_rgb(color)
1224
+
1225
+ shape2d = (soft_mask.shape[0], soft_mask.shape[1])
1226
+ rgba = np.zeros(shape2d + (4,), dtype="float32")
1227
+ rgba[:, :, :3] = color
1228
+ rgba[:, :, 3] = soft_mask * alpha
1229
+ self.output.ax.imshow(rgba, extent=(0, self.output.width, self.output.height, 0))
1230
+
1231
+ if text is not None:
1232
+ lighter_color = self._change_color_brightness(color, brightness_factor=0.7)
1233
+ binary_mask = (soft_mask > 0.5).astype("uint8")
1234
+ self._draw_text_in_mask(binary_mask, text, lighter_color)
1235
+ return self.output
1236
+
1237
+ def draw_polygon(self, segment, color, edge_color=None, alpha=0.5):
1238
+ """
1239
+ Args:
1240
+ segment: numpy array of shape Nx2, containing all the points in the polygon.
1241
+ color: color of the polygon. Refer to `matplotlib.colors` for a full list of
1242
+ formats that are accepted.
1243
+ edge_color: color of the polygon edges. Refer to `matplotlib.colors` for a
1244
+ full list of formats that are accepted. If not provided, a darker shade
1245
+ of the polygon color will be used instead.
1246
+ alpha (float): blending efficient. Smaller values lead to more transparent masks.
1247
+
1248
+ Returns:
1249
+ output (VisImage): image object with polygon drawn.
1250
+ """
1251
+ if edge_color is None:
1252
+ # make edge color darker than the polygon color
1253
+ if alpha > 0.8:
1254
+ edge_color = self._change_color_brightness(color, brightness_factor=-0.7)
1255
+ else:
1256
+ edge_color = color
1257
+ edge_color = mplc.to_rgb(edge_color) + (1,)
1258
+
1259
+ polygon = mpl.patches.Polygon(
1260
+ segment,
1261
+ fill=True,
1262
+ facecolor=mplc.to_rgb(color) + (alpha,),
1263
+ edgecolor=edge_color,
1264
+ linewidth=max(self._default_font_size // 15 * self.output.scale, 1),
1265
+ )
1266
+ self.output.ax.add_patch(polygon)
1267
+ return self.output
1268
+
1269
+ """
1270
+ Internal methods:
1271
+ """
1272
+
1273
+ def _jitter(self, color):
1274
+ """Randomly modifies given color to produce a slightly different color than the color given.
1275
+
1276
+ Args:
1277
+ color (tuple[double]): a tuple of 3 elements, containing the RGB values of the color
1278
+ picked. The values in the list are in the [0.0, 1.0] range.
1279
+
1280
+ Returns:
1281
+ jittered_color (tuple[double]): a tuple of 3 elements, containing the RGB values of the
1282
+ color after being jittered. The values in the list are in the [0.0, 1.0] range.
1283
+ """
1284
+ color = mplc.to_rgb(color)
1285
+ # np.random.seed(0)
1286
+ vec = np.random.rand(3)
1287
+ # better to do it in another color space
1288
+ vec = vec / np.linalg.norm(vec) * 0.5
1289
+ res = np.clip(vec + color, 0, 1)
1290
+ return tuple(res)
1291
+
1292
+ def _create_grayscale_image(self, mask=None):
1293
+ """Create a grayscale version of the original image.
1294
+
1295
+ The colors in masked area, if given, will be kept.
1296
+ """
1297
+ img_bw = self.img.astype("f4").mean(axis=2)
1298
+ img_bw = np.stack([img_bw] * 3, axis=2)
1299
+ if mask is not None:
1300
+ img_bw[mask] = self.img[mask]
1301
+ return img_bw
1302
+
1303
+ def _change_color_brightness(self, color, brightness_factor):
1304
+ """Depending on the brightness_factor, gives a lighter or darker color i.e. a color with less or more saturation
1305
+ than the original color.
1306
+
1307
+ Args:
1308
+ color: color of the polygon. Refer to `matplotlib.colors` for a full list of
1309
+ formats that are accepted.
1310
+ brightness_factor (float): a value in [-1.0, 1.0] range. A lightness factor of
1311
+ 0 will correspond to no change, a factor in [-1.0, 0) range will result in
1312
+ a darker color and a factor in (0, 1.0] range will result in a lighter color.
1313
+
1314
+ Returns:
1315
+ modified_color (tuple[double]): a tuple containing the RGB values of the
1316
+ modified color. Each value in the tuple is in the [0.0, 1.0] range.
1317
+ """
1318
+ assert brightness_factor >= -1.0 and brightness_factor <= 1.0
1319
+ color = mplc.to_rgb(color)
1320
+ polygon_color = colorsys.rgb_to_hls(*mplc.to_rgb(color))
1321
+ modified_lightness = polygon_color[1] + (brightness_factor * polygon_color[1])
1322
+ modified_lightness = 0.0 if modified_lightness < 0.0 else modified_lightness
1323
+ modified_lightness = 1.0 if modified_lightness > 1.0 else modified_lightness
1324
+ modified_color = colorsys.hls_to_rgb(polygon_color[0], modified_lightness, polygon_color[2])
1325
+ return modified_color
1326
+
1327
+ def _convert_boxes(self, boxes):
1328
+ """Convert different format of boxes to an NxB array, where B = 4 or 5 is the box dimension."""
1329
+ if isinstance(boxes, Boxes) or isinstance(boxes, RotatedBoxes):
1330
+ return boxes.tensor.detach().numpy()
1331
+ else:
1332
+ return np.asarray(boxes)
1333
+
1334
+ def _convert_masks(self, masks_or_polygons):
1335
+ """Convert different format of masks or polygons to a tuple of masks and polygons.
1336
+
1337
+ Returns:
1338
+ list[GenericMask]:
1339
+ """
1340
+
1341
+ m = masks_or_polygons
1342
+ if isinstance(m, PolygonMasks):
1343
+ m = m.polygons
1344
+ if isinstance(m, BitMasks):
1345
+ m = m.tensor.numpy()
1346
+ if isinstance(m, torch.Tensor):
1347
+ m = m.numpy()
1348
+ ret = []
1349
+ for x in m:
1350
+ if isinstance(x, GenericMask):
1351
+ ret.append(x)
1352
+ else:
1353
+ ret.append(GenericMask(x, self.output.height, self.output.width))
1354
+ return ret
1355
+
1356
+ def _draw_number_in_mask(self, binary_mask, text, color, label_mode="1"):
1357
+ """Find proper places to draw text given a binary mask."""
1358
+
1359
+ def number_to_string(n):
1360
+ chars = []
1361
+ while n:
1362
+ n, remainder = divmod(n - 1, 26)
1363
+ chars.append(chr(97 + remainder))
1364
+ return "".join(reversed(chars))
1365
+
1366
+ binary_mask = np.pad(binary_mask, ((1, 1), (1, 1)), "constant")
1367
+ mask_dt = cv2.distanceTransform(binary_mask, cv2.DIST_L2, 0)
1368
+ mask_dt = mask_dt[1:-1, 1:-1]
1369
+ max_dist = np.max(mask_dt)
1370
+ coords_y, coords_x = np.where(mask_dt == max_dist) # coords is [y, x]
1371
+
1372
+ if label_mode == "a":
1373
+ text = number_to_string(int(text))
1374
+ else:
1375
+ text = text
1376
+
1377
+ self.draw_text(
1378
+ text,
1379
+ (coords_x[len(coords_x) // 2] + 2, coords_y[len(coords_y) // 2] - 6),
1380
+ color=color,
1381
+ )
1382
+
1383
+ # TODO sometimes drawn on wrong objects. the heuristics here can improve.
1384
+ # _num_cc, cc_labels, stats, centroids = cv2.connectedComponentsWithStats(binary_mask, 8)
1385
+ # if stats[1:, -1].size == 0:
1386
+ # return
1387
+ # largest_component_id = np.argmax(stats[1:, -1]) + 1
1388
+
1389
+ # # draw text on the largest component, as well as other very large components.
1390
+ # for cid in range(1, _num_cc):
1391
+ # if cid == largest_component_id or stats[cid, -1] > _LARGE_MASK_AREA_THRESH:
1392
+ # # median is more stable than centroid
1393
+ # # center = centroids[largest_component_id]
1394
+ # center = np.median((cc_labels == cid).nonzero(), axis=1)[::-1]
1395
+ # # bottom=np.max((cc_labels == cid).nonzero(), axis=1)[::-1]
1396
+ # # center[1]=bottom[1]+2
1397
+ # self.draw_text(text, center, color=color)
1398
+
1399
+ def _draw_text_in_mask(self, binary_mask, text, color):
1400
+ """Find proper places to draw text given a binary mask."""
1401
+ # TODO sometimes drawn on wrong objects. the heuristics here can improve.
1402
+ _num_cc, cc_labels, stats, centroids = cv2.connectedComponentsWithStats(binary_mask, 8)
1403
+ if stats[1:, -1].size == 0:
1404
+ return
1405
+ largest_component_id = np.argmax(stats[1:, -1]) + 1
1406
+
1407
+ # draw text on the largest component, as well as other very large components.
1408
+ for cid in range(1, _num_cc):
1409
+ if cid == largest_component_id or stats[cid, -1] > _LARGE_MASK_AREA_THRESH:
1410
+ # median is more stable than centroid
1411
+ # center = centroids[largest_component_id]
1412
+ center = np.median((cc_labels == cid).nonzero(), axis=1)[::-1]
1413
+ bottom = np.max((cc_labels == cid).nonzero(), axis=1)[::-1]
1414
+ center[1] = bottom[1] + 2
1415
+ self.draw_text(text, center, color=color)
1416
+
1417
+ def _convert_keypoints(self, keypoints):
1418
+ if isinstance(keypoints, Keypoints):
1419
+ keypoints = keypoints.tensor
1420
+ keypoints = np.asarray(keypoints)
1421
+ return keypoints
1422
+
1423
+ def get_output(self):
1424
+ """
1425
+ Returns:
1426
+ output (VisImage): the image output containing the visualizations added
1427
+ to the image.
1428
+ """
1429
+ return self.output