enotkrutoy commited on
Commit
e5ba844
Β·
verified Β·
1 Parent(s): 5ff6f84

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes. Β  See raw diff
Files changed (50) hide show
  1. .DS_Store +0 -0
  2. .gitattributes +20 -0
  3. .github/workflows/pylint.yml +23 -0
  4. .gitignore +29 -0
  5. LICENSE +201 -0
  6. README.md +152 -12
  7. client/.DS_Store +0 -0
  8. client/__pycache__/forward.cpython-38.pyc +0 -0
  9. client/data.json +8 -0
  10. client/software/.$beauty.drawio.bkp +0 -0
  11. client/software/.$flow of mian with deepface.drawio.bkp +51 -0
  12. client/software/.$flow.drawio.bkp +0 -0
  13. client/software/.$flow.drawio.dtmp +0 -0
  14. client/software/FaceBoxes/.gitignore +3 -0
  15. client/software/FaceBoxes/FaceBoxes.py +167 -0
  16. client/software/FaceBoxes/__init__.py +1 -0
  17. client/software/FaceBoxes/build_cpu_nms.sh +3 -0
  18. client/software/FaceBoxes/models/faceboxes.py +158 -0
  19. client/software/FaceBoxes/readme.md +18 -0
  20. client/software/FaceBoxes/utils/.gitignore +4 -0
  21. client/software/FaceBoxes/utils/__init__.py +0 -0
  22. client/software/FaceBoxes/utils/align_trans.py +297 -0
  23. client/software/FaceBoxes/utils/box_utils.py +277 -0
  24. client/software/FaceBoxes/utils/build.py +57 -0
  25. client/software/FaceBoxes/utils/config.py +9 -0
  26. client/software/FaceBoxes/utils/eval.py +27 -0
  27. client/software/FaceBoxes/utils/functions.py +48 -0
  28. client/software/FaceBoxes/utils/images/test.py +9 -0
  29. client/software/FaceBoxes/utils/logger.py +134 -0
  30. client/software/FaceBoxes/utils/matlab_cp2tform.py +334 -0
  31. client/software/FaceBoxes/utils/misc.py +79 -0
  32. client/software/FaceBoxes/utils/nms/.gitignore +2 -0
  33. client/software/FaceBoxes/utils/nms/__init__.py +0 -0
  34. client/software/FaceBoxes/utils/nms/cpu_nms.cp38-win_amd64.pyd +3 -0
  35. client/software/FaceBoxes/utils/nms/cpu_nms.pyd +3 -0
  36. client/software/FaceBoxes/utils/nms/cpu_nms.pyx +163 -0
  37. client/software/FaceBoxes/utils/nms/py_cpu_nms.py +39 -0
  38. client/software/FaceBoxes/utils/nms/pyx2pyd.py +14 -0
  39. client/software/FaceBoxes/utils/nms/ζ–°ε»Ί Bitmap image.bmp +0 -0
  40. client/software/FaceBoxes/utils/nms_wrapper.py +19 -0
  41. client/software/FaceBoxes/utils/osutils.py +24 -0
  42. client/software/FaceBoxes/utils/prior_box.py +51 -0
  43. client/software/FaceBoxes/utils/progress/.gitignore +4 -0
  44. client/software/FaceBoxes/utils/progress/LICENSE +13 -0
  45. client/software/FaceBoxes/utils/progress/MANIFEST.in +1 -0
  46. client/software/FaceBoxes/utils/progress/README.rst +131 -0
  47. client/software/FaceBoxes/utils/progress/demo.gif +3 -0
  48. client/software/FaceBoxes/utils/progress/progress/__init__.py +127 -0
  49. client/software/FaceBoxes/utils/progress/progress/bar.py +88 -0
  50. client/software/FaceBoxes/utils/progress/progress/counter.py +48 -0
.DS_Store ADDED
Binary file (6.15 kB). View file
 
.gitattributes CHANGED
@@ -33,3 +33,23 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ client/software/FaceBoxes/utils/nms/cpu_nms.cp38-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
37
+ client/software/FaceBoxes/utils/nms/cpu_nms.pyd filter=lfs diff=lfs merge=lfs -text
38
+ client/software/FaceBoxes/utils/progress/demo.gif filter=lfs diff=lfs merge=lfs -text
39
+ client/software/checkpoint/utils/nms/cpu_nms.pyd filter=lfs diff=lfs merge=lfs -text
40
+ client/software/checkpoint/utils/progress/demo.gif filter=lfs diff=lfs merge=lfs -text
41
+ client/software/library/OIP-C.jpg filter=lfs diff=lfs merge=lfs -text
42
+ client/software/library/upload_button.png filter=lfs diff=lfs merge=lfs -text
43
+ client/software/output/myvideo_another.mp4 filter=lfs diff=lfs merge=lfs -text
44
+ client/software/utils/nms/cpu_nms.pyd filter=lfs diff=lfs merge=lfs -text
45
+ client/software/utils/progress/demo.gif filter=lfs diff=lfs merge=lfs -text
46
+ server/FaceBoxes/utils/progress/demo.gif filter=lfs diff=lfs merge=lfs -text
47
+ server/checkpoint/utils/nms/cpu_nms.pyd filter=lfs diff=lfs merge=lfs -text
48
+ server/checkpoint/utils/progress/demo.gif filter=lfs diff=lfs merge=lfs -text
49
+ server/test/1237187643.mp4 filter=lfs diff=lfs merge=lfs -text
50
+ server/test/1711629152.mp4 filter=lfs diff=lfs merge=lfs -text
51
+ server/test/416918082.mp4 filter=lfs diff=lfs merge=lfs -text
52
+ server/test/928067867.mp4 filter=lfs diff=lfs merge=lfs -text
53
+ server/test/myvideo-new.mp4 filter=lfs diff=lfs merge=lfs -text
54
+ server/utils/nms/cpu_nms.pyd filter=lfs diff=lfs merge=lfs -text
55
+ server/utils/progress/demo.gif filter=lfs diff=lfs merge=lfs -text
.github/workflows/pylint.yml ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Pylint
2
+
3
+ on: [push]
4
+
5
+ jobs:
6
+ build:
7
+ runs-on: ubuntu-latest
8
+ strategy:
9
+ matrix:
10
+ python-version: ["3.8", "3.9", "3.10"]
11
+ steps:
12
+ - uses: actions/checkout@v4
13
+ - name: Set up Python ${{ matrix.python-version }}
14
+ uses: actions/setup-python@v3
15
+ with:
16
+ python-version: ${{ matrix.python-version }}
17
+ - name: Install dependencies
18
+ run: |
19
+ python -m pip install --upgrade pip
20
+ pip install pylint
21
+ - name: Analysing the code with pylint
22
+ run: |
23
+ pylint $(git ls-files '*.py')
.gitignore ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ client/software/library/server.json
2
+ client/software/test.json
3
+ /server/service
4
+ client.zip
5
+ client/software/error_log.txt
6
+ client/software/commissure.png
7
+ client/software/library.rar
8
+ client/software/library/__pycache__/aws_connection.cpython-38.pyc
9
+ client/software/library/__pycache__/cat.cpython-38.pyc
10
+ client/software/commissure.png
11
+ client/software/myvideo.mp4
12
+ client/software/myvideo_another.mp4
13
+ tree.txt
14
+ client/software/commissure.png
15
+ client/software/library/cross.png
16
+ client/software/library/SavitzkyGolayFilter.py
17
+ client/software/myvideo.mp4
18
+ client/software/myvideo_another.mp4
19
+ tree.txt
20
+ client/software/commissure.png
21
+ client/software/library/server.json
22
+ client/software/myvideo.mp4
23
+ client/software/myvideo_another.mp4
24
+ /venv
25
+ client/software/output/error_log.txt
26
+ client/software/output/error_log.txt
27
+ client/software/output/error_log.txt
28
+ guideorunning.mp4
29
+ guide for running.mp4
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.
README.md CHANGED
@@ -1,12 +1,152 @@
1
- ---
2
- title: Dynasmile
3
- emoji: 🏒
4
- colorFrom: purple
5
- colorTo: yellow
6
- sdk: gradio
7
- sdk_version: 6.3.0
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ⭐ Star Dynasmile on GitHub β€” it motivates us a lot!
2
+
3
+ [![Share](https://img.shields.io/badge/share-000000?logo=x&logoColor=white)](https://x.com/intent/tweet?text=Check%20out%20this%20project%20on%20GitHub:%20https://github.com/dentistfrankchen/dynasmile%20%23Orthodontics%20%23Dentistry%20%23SmileAnalysis)
4
+ [![Share](https://img.shields.io/badge/share-1877F2?logo=facebook&logoColor=white)](https://www.facebook.com/sharer/sharer.php?u=https://github.com/dentistfrankchen/dynasmile)
5
+ [![Share](https://img.shields.io/badge/share-0A66C2?logo=linkedin&logoColor=white)](https://www.linkedin.com/sharing/share-offsite/?url=https://github.com/dentistfrankchen/dynasmile)
6
+ [![Share](https://img.shields.io/badge/share-FF4500?logo=reddit&logoColor=white)](https://www.reddit.com/submit?title=Check%20out%20this%20project%20on%20GitHub:%20https://github.com/dentistfrankchen/dynasmile)
7
+ [![Share](https://img.shields.io/badge/share-0088CC?logo=telegram&logoColor=white)](https://t.me/share/url?url=https://github.com/dentistfrankchen/dynasmile&text=Check%20out%20this%20project%20on%20GitHub)
8
+
9
+ ## Table of Contents
10
+ - [Features highlight](#-features-highlight)
11
+ - [Functionality](#-functionality)
12
+ - [How to Install](#-how-to-install)
13
+ - [How to run the program](#-how-to-run-the-program)
14
+ - [Feedback and Contributions](#-feedback-and-contributions)
15
+ - [License](#-license)
16
+ - [Contacts](#%EF%B8%8F-contacts)
17
+
18
+ ## πŸš€ Features highlight
19
+
20
+ **Dynasmile** is a Python-based AI-driven dynamic smile analysis tool for dental research. It uses computer vision techniques to analyze smile process. As a dental application, it features:
21
+
22
+ - **Smile intensity estimation**: Dynasmile automatically analyzes the smile intensity across different frames of the video. It plots the smile intensity, which helps the dentist to locate the frame where the smile reaches its peak.
23
+
24
+ - **Landmark detecion and display**: Dynasmile detects dentofacial landmarks on patients' faces and overlays the result to the selected frame, providing a user-friendly interface for dental specialists.
25
+
26
+ - **Low cost**: Dynasmile do not rely on local graphical card. The special architecture of this software relies on EC2 server, which can be rent at low cost and used at any time.
27
+
28
+ ## πŸŽ“ Functionality
29
+
30
+ Dynasmile processes the video uploaded by the user. It performs smile analysis on the selected frame, which includes detection of 13 dentofacial landmarks and performing 8 smile measurements.
31
+
32
+ For convenience, all the information is provided in the tables below:
33
+
34
+ ### Dentofacial landmarks
35
+ |Number|Landmark name|
36
+ |:-|:-|
37
+ |1|Subnasale|
38
+ |2|Inferior upper lip border|
39
+ |3|Superior lower lip border|
40
+ |4|Right outer canthus|
41
+ |5|Left outer canthus|
42
+ |6|Right outer smile commissure|
43
+ |7|Left outer smile sommissure|
44
+ |8|Soft tissue nasion|
45
+ |9|Soft tissue pogonion|
46
+ |10|Incisor edge|
47
+ |11|Left upper cuspid tip|
48
+ |12|Right upper cuspid tip|
49
+ |13|Cervical part of incisor|
50
+ |**In total 13 landmarks**|
51
+
52
+ ### Smile measurements
53
+ |Number|Measurement name|
54
+ |:-|:-|
55
+ |1|Intercommissure width|
56
+ |2|Interlabial gap|
57
+ |3|Gingival display|
58
+ |4|Philtrum height|
59
+ |5|Transverse symmetry|
60
+ |6|Vertical symmetry|
61
+ |7|Dental angulation|
62
+ |8|Canthus and smile commissure deviation|
63
+ |**In total 8 measurements**|
64
+
65
+
66
+ ## πŸ“ How to Install
67
+ > [!IMPORTANT]
68
+ > This program relies on AWS EC2 GPU web instance to run, if you are new to EC2, please refer to this website https://aws.amazon.com/ec2/getting-started/
69
+
70
+ ### Dependency: Using our pre-configured EC2 instance
71
+ > [!IMPORTANT]
72
+ > Since our computing resource is limited, the instance might be temporarily stopped anytime.
73
+
74
+ ```shell
75
+ # Ensure Git is installed
76
+ # Visit https://git-scm.com to download and install console Git if not already installed
77
+ # Clone the repository to local computer
78
+ git clone https://github.com/dentistfrankchen/dynasmile.git
79
+
80
+ # Navigate to the project directory(.../dynasmile-master)
81
+ cd Path/to/dynasmile-master
82
+
83
+ # Activate the virtual environment
84
+ .\venv\Scripts\activate
85
+
86
+ # Install the requirements for the local interface.
87
+ pip install -r requirements.txt
88
+
89
+ ```
90
+
91
+
92
+
93
+ ## πŸ“š How to run the program
94
+
95
+ ### Step 1: Start main.py and connect to the EC2 instance.
96
+ ```shell
97
+ # Open Command Prompt.
98
+
99
+ # Assuming you have activated the virtual environment.
100
+
101
+ # You can start the main interface now.
102
+ python .\client\software\main.py
103
+
104
+ ```
105
+
106
+ ### Step 2: Wait for the main.py to connect to EC2 instance.
107
+ During this process, the mian.py will open command prompt windows to automatically connect to
108
+ the EC2 instance.
109
+
110
+ **Then you need to wait for the connection.**
111
+ **Please do not close the windows of command prompt.**
112
+
113
+ When the connection is finished, the mian interface would pop up.
114
+
115
+ ### Step 3: Use the interface to conduct smile analysis.
116
+ 1. Upload a video by clicking **Drag and Drop panel**.
117
+ 2. The program then uploads the video, displaying the process through the **progress bar**.
118
+ 3. When the progress bar reaches 100 percent, frame with greatest smile intensity will be automatically displayed.
119
+ 4. The landmarks and measurements will be automatically displayed.
120
+ 5. The user clicks the **'Save csv'** button, and the coordinates of the landmarks as well as the measurements will be saved in CSV files.
121
+
122
+ For a real-time view, here's a video for how to run this program:
123
+
124
+ https://github.com/user-attachments/assets/79f666d3-ec7a-4db0-8ec4-c57b7f8d55bb
125
+
126
+ ## 🀝 Feedback and Contributions
127
+
128
+ We've made a lot of effort to implement many aspects of dynamic smile analysis in this software. However, the development journey doesn't end now, and your feedback is crucial for our further improvement.
129
+
130
+ > [!IMPORTANT]
131
+ > Whether you have feedback on improvements, have encountered any bugs, or have suggestions for features, we cannot wait to hear from you. Your insights help us get our software more robust and user-friendly.
132
+
133
+ Please feel free to contribute by [submitting an issue](https://github.com/dentistfrankchen/dynasmile/issues). Each contribution helps us get better and improve.
134
+
135
+ We appreciate your kindly support and look forward to build our product even better with your help!
136
+
137
+ ## πŸ“ƒ License
138
+
139
+ This product is distributed under Apache license.
140
+
141
+ For non-commercial use, this product is available for free.
142
+
143
+ ## πŸ—¨οΈ Contacts
144
+
145
+ For more details about our products, services, or any general information regarding the Amazon EC2 server, feel free to contact us. We are here to provide needed support and answer any questions you have. Below are the best ways to contact our team:
146
+
147
+ - **Email**: Send us your inquiries or support requests at [dentistfrankchen@outlook.com](mailto:dentistfrankchen@outlook.com).
148
+
149
+
150
+ We look forward to assisting you and keeping your experience with our applicaion being enjoyable!
151
+
152
+ [Back to top](#top)
client/.DS_Store ADDED
Binary file (6.15 kB). View file
 
client/__pycache__/forward.cpython-38.pyc ADDED
Binary file (5.49 kB). View file
 
client/data.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "aws_config_aws_access_key_id":"",
3
+ "aws_config_aws_secret_access_key":"",
4
+ "ec2_config_aws_access_key_id":"",
5
+ "ec2_config_aws_secret_access_key":"",
6
+ "region_name":"",
7
+ "bucket_name":""
8
+ }
client/software/.$beauty.drawio.bkp ADDED
The diff for this file is too large to render. See raw diff
 
client/software/.$flow of mian with deepface.drawio.bkp ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <mxfile host="Electron" modified="2023-12-23T14:47:24.433Z" agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) draw.io/22.1.11 Chrome/114.0.5735.289 Electron/25.9.8 Safari/537.36" etag="9B_JbuzAznRq1-L8Jf-G" version="22.1.11" type="device">
2
+ <diagram id="C5RBs43oDa-KdzZeNtuy" name="Page-1">
3
+ <mxGraphModel dx="363" dy="253" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="827" pageHeight="1169" math="0" shadow="0">
4
+ <root>
5
+ <mxCell id="WIyWlLk6GJQsqaUBKTNV-0" />
6
+ <mxCell id="WIyWlLk6GJQsqaUBKTNV-1" parent="WIyWlLk6GJQsqaUBKTNV-0" />
7
+ <mxCell id="WIyWlLk6GJQsqaUBKTNV-2" value="" style="rounded=0;html=1;jettySize=auto;orthogonalLoop=1;fontSize=11;endArrow=block;endFill=0;endSize=8;strokeWidth=1;shadow=0;labelBackgroundColor=none;edgeStyle=orthogonalEdgeStyle;" parent="WIyWlLk6GJQsqaUBKTNV-1" source="WIyWlLk6GJQsqaUBKTNV-3" target="WIyWlLk6GJQsqaUBKTNV-6" edge="1">
8
+ <mxGeometry relative="1" as="geometry" />
9
+ </mxCell>
10
+ <mxCell id="WIyWlLk6GJQsqaUBKTNV-3" value="ε―Όε…₯视钑" style="rounded=1;whiteSpace=wrap;html=1;fontSize=12;glass=0;strokeWidth=1;shadow=0;" parent="WIyWlLk6GJQsqaUBKTNV-1" vertex="1">
11
+ <mxGeometry x="160" y="80" width="120" height="40" as="geometry" />
12
+ </mxCell>
13
+ <mxCell id="WIyWlLk6GJQsqaUBKTNV-4" value="Yes" style="rounded=0;html=1;jettySize=auto;orthogonalLoop=1;fontSize=11;endArrow=block;endFill=0;endSize=8;strokeWidth=1;shadow=0;labelBackgroundColor=none;edgeStyle=orthogonalEdgeStyle;" parent="WIyWlLk6GJQsqaUBKTNV-1" source="WIyWlLk6GJQsqaUBKTNV-6" target="WIyWlLk6GJQsqaUBKTNV-10" edge="1">
14
+ <mxGeometry y="20" relative="1" as="geometry">
15
+ <mxPoint as="offset" />
16
+ </mxGeometry>
17
+ </mxCell>
18
+ <mxCell id="WIyWlLk6GJQsqaUBKTNV-5" value="No" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;jettySize=auto;orthogonalLoop=1;fontSize=11;endArrow=block;endFill=0;endSize=8;strokeWidth=1;shadow=0;labelBackgroundColor=none;" parent="WIyWlLk6GJQsqaUBKTNV-1" source="WIyWlLk6GJQsqaUBKTNV-6" target="WIyWlLk6GJQsqaUBKTNV-7" edge="1">
19
+ <mxGeometry y="10" relative="1" as="geometry">
20
+ <mxPoint as="offset" />
21
+ </mxGeometry>
22
+ </mxCell>
23
+ <mxCell id="WIyWlLk6GJQsqaUBKTNV-6" value="逐帧情η»ͺεˆ†ζžοΌŒ&lt;br&gt;η”ŸζˆεΏ«δΉε€ΌεΊεˆ—" style="rhombus;whiteSpace=wrap;html=1;shadow=0;fontFamily=Helvetica;fontSize=12;align=center;strokeWidth=1;spacing=6;spacingTop=-4;" parent="WIyWlLk6GJQsqaUBKTNV-1" vertex="1">
24
+ <mxGeometry x="160" y="150" width="120" height="100" as="geometry" />
25
+ </mxCell>
26
+ <mxCell id="WIyWlLk6GJQsqaUBKTNV-7" value="Plug in lamp" style="rounded=1;whiteSpace=wrap;html=1;fontSize=12;glass=0;strokeWidth=1;shadow=0;" parent="WIyWlLk6GJQsqaUBKTNV-1" vertex="1">
27
+ <mxGeometry x="320" y="190" width="120" height="40" as="geometry" />
28
+ </mxCell>
29
+ <mxCell id="WIyWlLk6GJQsqaUBKTNV-8" value="No" style="rounded=0;html=1;jettySize=auto;orthogonalLoop=1;fontSize=11;endArrow=block;endFill=0;endSize=8;strokeWidth=1;shadow=0;labelBackgroundColor=none;edgeStyle=orthogonalEdgeStyle;" parent="WIyWlLk6GJQsqaUBKTNV-1" source="WIyWlLk6GJQsqaUBKTNV-10" target="WIyWlLk6GJQsqaUBKTNV-11" edge="1">
30
+ <mxGeometry x="0.3333" y="20" relative="1" as="geometry">
31
+ <mxPoint as="offset" />
32
+ </mxGeometry>
33
+ </mxCell>
34
+ <mxCell id="WIyWlLk6GJQsqaUBKTNV-9" value="Yes" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;jettySize=auto;orthogonalLoop=1;fontSize=11;endArrow=block;endFill=0;endSize=8;strokeWidth=1;shadow=0;labelBackgroundColor=none;" parent="WIyWlLk6GJQsqaUBKTNV-1" source="WIyWlLk6GJQsqaUBKTNV-10" target="WIyWlLk6GJQsqaUBKTNV-12" edge="1">
35
+ <mxGeometry y="10" relative="1" as="geometry">
36
+ <mxPoint as="offset" />
37
+ </mxGeometry>
38
+ </mxCell>
39
+ <mxCell id="WIyWlLk6GJQsqaUBKTNV-10" value="Bulb&lt;br&gt;burned out?" style="rhombus;whiteSpace=wrap;html=1;shadow=0;fontFamily=Helvetica;fontSize=12;align=center;strokeWidth=1;spacing=6;spacingTop=-4;" parent="WIyWlLk6GJQsqaUBKTNV-1" vertex="1">
40
+ <mxGeometry x="170" y="290" width="100" height="80" as="geometry" />
41
+ </mxCell>
42
+ <mxCell id="WIyWlLk6GJQsqaUBKTNV-11" value="Repair Lamp" style="rounded=1;whiteSpace=wrap;html=1;fontSize=12;glass=0;strokeWidth=1;shadow=0;" parent="WIyWlLk6GJQsqaUBKTNV-1" vertex="1">
43
+ <mxGeometry x="160" y="430" width="120" height="40" as="geometry" />
44
+ </mxCell>
45
+ <mxCell id="WIyWlLk6GJQsqaUBKTNV-12" value="Replace Bulb" style="rounded=1;whiteSpace=wrap;html=1;fontSize=12;glass=0;strokeWidth=1;shadow=0;" parent="WIyWlLk6GJQsqaUBKTNV-1" vertex="1">
46
+ <mxGeometry x="320" y="310" width="120" height="40" as="geometry" />
47
+ </mxCell>
48
+ </root>
49
+ </mxGraphModel>
50
+ </diagram>
51
+ </mxfile>
client/software/.$flow.drawio.bkp ADDED
The diff for this file is too large to render. See raw diff
 
client/software/.$flow.drawio.dtmp ADDED
The diff for this file is too large to render. See raw diff
 
client/software/FaceBoxes/.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ .idea/
2
+ __pycache__
3
+ **/__pycache__
client/software/FaceBoxes/FaceBoxes.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding: utf-8
2
+
3
+ import os.path as osp
4
+
5
+ import torch
6
+ import numpy as np
7
+ import cv2
8
+
9
+ from .utils.prior_box import PriorBox
10
+ from .utils.nms_wrapper import nms
11
+ from .utils.box_utils import decode
12
+ from .utils.timer import Timer
13
+ from .utils.functions import check_keys, remove_prefix, load_model
14
+ from .utils.config import cfg
15
+ from .models.faceboxes import FaceBoxesNet
16
+
17
+ # some global configs
18
+ confidence_threshold = 0.05
19
+ top_k = 5000
20
+ keep_top_k = 750
21
+ nms_threshold = 0.3
22
+ vis_thres = 0.5
23
+ resize = 1
24
+
25
+ scale_flag = True
26
+ HEIGHT, WIDTH = 720, 1080
27
+
28
+
29
+ def make_abs_path(fn): return osp.join(osp.dirname(osp.realpath(__file__)), fn)
30
+
31
+
32
+ pretrained_path = make_abs_path('weights/FaceBoxesProd.pth')
33
+
34
+
35
+ def viz_bbox(img, dets, wfp='out.jpg'):
36
+ # show
37
+ for b in dets:
38
+ if b[4] < vis_thres:
39
+ continue
40
+ text = "{:.4f}".format(b[4])
41
+ b = list(map(int, b))
42
+ cv2.rectangle(img, (b[0], b[1]), (b[2], b[3]), (0, 0, 255), 2)
43
+ cx = b[0]
44
+ cy = b[1] + 12
45
+ cv2.putText(img, text, (cx, cy), cv2.FONT_HERSHEY_DUPLEX,
46
+ 0.5, (255, 255, 255))
47
+ cv2.imwrite(wfp, img)
48
+ print(f'Viz bbox to {wfp}')
49
+
50
+
51
+ class FaceBoxes:
52
+ def __init__(self, timer_flag=False):
53
+ torch.set_grad_enabled(False)
54
+
55
+ net = FaceBoxesNet(phase='test', size=None,
56
+ num_classes=2) # initialize detector
57
+ self.net = load_model(
58
+ net, pretrained_path=pretrained_path, load_to_cpu=True)
59
+ self.net.eval()
60
+ # print('Finished loading model!')
61
+
62
+ self.timer_flag = timer_flag
63
+
64
+ def __call__(self, img_):
65
+ img_raw = img_.copy()
66
+
67
+ # scaling to speed up
68
+ scale = 1
69
+ if scale_flag:
70
+ h, w = img_raw.shape[:2]
71
+ if h > HEIGHT:
72
+ scale = HEIGHT / h
73
+ if w * scale > WIDTH:
74
+ scale *= WIDTH / (w * scale)
75
+ # print(scale)
76
+ if scale == 1:
77
+ img_raw_scale = img_raw
78
+ else:
79
+ h_s = int(scale * h)
80
+ w_s = int(scale * w)
81
+ # print(h_s, w_s)
82
+ img_raw_scale = cv2.resize(img_raw, dsize=(w_s, h_s))
83
+ # print(img_raw_scale.shape)
84
+
85
+ img = np.float32(img_raw_scale)
86
+ else:
87
+ img = np.float32(img_raw)
88
+
89
+ # forward
90
+ _t = {'forward_pass': Timer(), 'misc': Timer()}
91
+ im_height, im_width, _ = img.shape
92
+ scale_bbox = torch.Tensor(
93
+ [img.shape[1], img.shape[0], img.shape[1], img.shape[0]])
94
+ img -= (104, 117, 123)
95
+ img = img.transpose(2, 0, 1)
96
+ img = torch.from_numpy(img).unsqueeze(0)
97
+
98
+ _t['forward_pass'].tic()
99
+ loc, conf = self.net(img) # forward pass
100
+ _t['forward_pass'].toc()
101
+ _t['misc'].tic()
102
+ priorbox = PriorBox(image_size=(im_height, im_width))
103
+ priors = priorbox.forward()
104
+ prior_data = priors.data
105
+ boxes = decode(loc.data.squeeze(0), prior_data, cfg['variance'])
106
+ if scale_flag:
107
+ boxes = boxes * scale_bbox / scale / resize
108
+ else:
109
+ boxes = boxes * scale_bbox / resize
110
+
111
+ boxes = boxes.cpu().numpy()
112
+ scores = conf.squeeze(0).data.cpu().numpy()[:, 1]
113
+
114
+ # ignore low scores
115
+ inds = np.where(scores > confidence_threshold)[0]
116
+ boxes = boxes[inds]
117
+ scores = scores[inds]
118
+
119
+ # keep top-K before NMS
120
+ order = scores.argsort()[::-1][:top_k]
121
+ boxes = boxes[order]
122
+ scores = scores[order]
123
+
124
+ # do NMS
125
+ dets = np.hstack((boxes, scores[:, np.newaxis])).astype(
126
+ np.float32, copy=False)
127
+ # keep = py_cpu_nms(dets, args.nms_threshold)
128
+ keep = nms(dets, nms_threshold)
129
+ dets = dets[keep, :]
130
+
131
+ # keep top-K faster NMS
132
+ dets = dets[:keep_top_k, :]
133
+ _t['misc'].toc()
134
+
135
+ if self.timer_flag:
136
+ print('Detection: {:d}/{:d} forward_pass_time: {:.4f}s misc: {:.4f}s'.format(1, 1, _t[
137
+ 'forward_pass'].average_time, _t['misc'].average_time))
138
+
139
+ # filter using vis_thres
140
+ det_bboxes = []
141
+ for b in dets:
142
+ if b[4] > vis_thres:
143
+ xmin, ymin, xmax, ymax, score = b[0], b[1], b[2], b[3], b[4]
144
+ w = xmax - xmin + 1
145
+ h = ymax - ymin + 1
146
+ bbox = [xmin, ymin, xmax, ymax, score]
147
+ det_bboxes.append(bbox)
148
+
149
+ return det_bboxes
150
+
151
+
152
+ def main():
153
+ face_boxes = FaceBoxes(timer_flag=True)
154
+
155
+ fn = 'trump_hillary.jpg'
156
+ img_fp = f'../examples/inputs/{fn}'
157
+ img = cv2.imread(img_fp)
158
+ dets = face_boxes(img) # xmin, ymin, w, h
159
+ # print(dets)
160
+
161
+ wfn = fn.replace('.jpg', '_det.jpg')
162
+ wfp = osp.join('../examples/results', wfn)
163
+ viz_bbox(img, dets, wfp)
164
+
165
+
166
+ if __name__ == '__main__':
167
+ main()
client/software/FaceBoxes/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .FaceBoxes import FaceBoxes
client/software/FaceBoxes/build_cpu_nms.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ cd utils
2
+ python3 build.py build_ext --inplace
3
+ cd ..
client/software/FaceBoxes/models/faceboxes.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding: utf-8
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+
7
+
8
+ class BasicConv2d(nn.Module):
9
+
10
+ def __init__(self, in_channels, out_channels, **kwargs):
11
+ super(BasicConv2d, self).__init__()
12
+ self.conv = nn.Conv2d(in_channels, out_channels, bias=False, **kwargs)
13
+ self.bn = nn.BatchNorm2d(out_channels, eps=1e-5)
14
+
15
+ def forward(self, x):
16
+ x = self.conv(x)
17
+ x = self.bn(x)
18
+ return F.relu(x, inplace=True)
19
+
20
+
21
+ class Inception(nn.Module):
22
+ def __init__(self):
23
+ super(Inception, self).__init__()
24
+ self.branch1x1 = BasicConv2d(128, 32, kernel_size=1, padding=0)
25
+ self.branch1x1_2 = BasicConv2d(128, 32, kernel_size=1, padding=0)
26
+ self.branch3x3_reduce = BasicConv2d(128, 24, kernel_size=1, padding=0)
27
+ self.branch3x3 = BasicConv2d(24, 32, kernel_size=3, padding=1)
28
+ self.branch3x3_reduce_2 = BasicConv2d(
29
+ 128, 24, kernel_size=1, padding=0)
30
+ self.branch3x3_2 = BasicConv2d(24, 32, kernel_size=3, padding=1)
31
+ self.branch3x3_3 = BasicConv2d(32, 32, kernel_size=3, padding=1)
32
+
33
+ def forward(self, x):
34
+ branch1x1 = self.branch1x1(x)
35
+
36
+ branch1x1_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1)
37
+ branch1x1_2 = self.branch1x1_2(branch1x1_pool)
38
+
39
+ branch3x3_reduce = self.branch3x3_reduce(x)
40
+ branch3x3 = self.branch3x3(branch3x3_reduce)
41
+
42
+ branch3x3_reduce_2 = self.branch3x3_reduce_2(x)
43
+ branch3x3_2 = self.branch3x3_2(branch3x3_reduce_2)
44
+ branch3x3_3 = self.branch3x3_3(branch3x3_2)
45
+
46
+ outputs = [branch1x1, branch1x1_2, branch3x3, branch3x3_3]
47
+ return torch.cat(outputs, 1)
48
+
49
+
50
+ class CRelu(nn.Module):
51
+
52
+ def __init__(self, in_channels, out_channels, **kwargs):
53
+ super(CRelu, self).__init__()
54
+ self.conv = nn.Conv2d(in_channels, out_channels, bias=False, **kwargs)
55
+ self.bn = nn.BatchNorm2d(out_channels, eps=1e-5)
56
+
57
+ def forward(self, x):
58
+ x = self.conv(x)
59
+ x = self.bn(x)
60
+ x = torch.cat([x, -x], 1)
61
+ x = F.relu(x, inplace=True)
62
+ return x
63
+
64
+
65
+ class FaceBoxesNet(nn.Module):
66
+
67
+ def __init__(self, phase, size, num_classes):
68
+ super(FaceBoxesNet, self).__init__()
69
+ self.phase = phase
70
+ self.num_classes = num_classes
71
+ self.size = size
72
+
73
+ self.conv1 = CRelu(3, 24, kernel_size=7, stride=4, padding=3)
74
+ self.conv2 = CRelu(48, 64, kernel_size=5, stride=2, padding=2)
75
+
76
+ self.inception1 = Inception()
77
+ self.inception2 = Inception()
78
+ self.inception3 = Inception()
79
+
80
+ self.conv3_1 = BasicConv2d(
81
+ 128, 128, kernel_size=1, stride=1, padding=0)
82
+ self.conv3_2 = BasicConv2d(
83
+ 128, 256, kernel_size=3, stride=2, padding=1)
84
+
85
+ self.conv4_1 = BasicConv2d(
86
+ 256, 128, kernel_size=1, stride=1, padding=0)
87
+ self.conv4_2 = BasicConv2d(
88
+ 128, 256, kernel_size=3, stride=2, padding=1)
89
+
90
+ self.loc, self.conf = self.multibox(self.num_classes)
91
+
92
+ if self.phase == 'test':
93
+ self.softmax = nn.Softmax(dim=-1)
94
+
95
+ if self.phase == 'train':
96
+ for m in self.modules():
97
+ if isinstance(m, nn.Conv2d):
98
+ if m.bias is not None:
99
+ nn.init.xavier_normal_(m.weight.data)
100
+ m.bias.data.fill_(0.02)
101
+ else:
102
+ m.weight.data.normal_(0, 0.01)
103
+ elif isinstance(m, nn.BatchNorm2d):
104
+ m.weight.data.fill_(1)
105
+ m.bias.data.zero_()
106
+
107
+ def multibox(self, num_classes):
108
+ loc_layers = []
109
+ conf_layers = []
110
+ loc_layers += [nn.Conv2d(128, 21 * 4, kernel_size=3, padding=1)]
111
+ conf_layers += [nn.Conv2d(128, 21 * num_classes,
112
+ kernel_size=3, padding=1)]
113
+ loc_layers += [nn.Conv2d(256, 1 * 4, kernel_size=3, padding=1)]
114
+ conf_layers += [nn.Conv2d(256, 1 * num_classes,
115
+ kernel_size=3, padding=1)]
116
+ loc_layers += [nn.Conv2d(256, 1 * 4, kernel_size=3, padding=1)]
117
+ conf_layers += [nn.Conv2d(256, 1 * num_classes,
118
+ kernel_size=3, padding=1)]
119
+ return nn.Sequential(*loc_layers), nn.Sequential(*conf_layers)
120
+
121
+ def forward(self, x):
122
+
123
+ detection_sources = list()
124
+ loc = list()
125
+ conf = list()
126
+
127
+ x = self.conv1(x)
128
+ x = F.max_pool2d(x, kernel_size=3, stride=2, padding=1)
129
+ x = self.conv2(x)
130
+ x = F.max_pool2d(x, kernel_size=3, stride=2, padding=1)
131
+ x = self.inception1(x)
132
+ x = self.inception2(x)
133
+ x = self.inception3(x)
134
+ detection_sources.append(x)
135
+
136
+ x = self.conv3_1(x)
137
+ x = self.conv3_2(x)
138
+ detection_sources.append(x)
139
+
140
+ x = self.conv4_1(x)
141
+ x = self.conv4_2(x)
142
+ detection_sources.append(x)
143
+
144
+ for (x, l, c) in zip(detection_sources, self.loc, self.conf):
145
+ loc.append(l(x).permute(0, 2, 3, 1).contiguous())
146
+ conf.append(c(x).permute(0, 2, 3, 1).contiguous())
147
+
148
+ loc = torch.cat([o.view(o.size(0), -1) for o in loc], 1)
149
+ conf = torch.cat([o.view(o.size(0), -1) for o in conf], 1)
150
+
151
+ if self.phase == "test":
152
+ output = (loc.view(loc.size(0), -1, 4),
153
+ self.softmax(conf.view(conf.size(0), -1, self.num_classes)))
154
+ else:
155
+ output = (loc.view(loc.size(0), -1, 4),
156
+ conf.view(conf.size(0), -1, self.num_classes))
157
+
158
+ return output
client/software/FaceBoxes/readme.md ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## How to fun FaceBoxes
2
+
3
+ ### Build the cpu version of NMS
4
+ ```shell script
5
+ cd utils
6
+ python3 build.py build_ext --inplace
7
+ ```
8
+
9
+ or just run
10
+
11
+ ```shell script
12
+ sh ./build_cpu_nms.sh
13
+ ```
14
+
15
+ ### Run the demo of face detection
16
+ ```shell script
17
+ python3 FaceBoxes.py
18
+ ```
client/software/FaceBoxes/utils/.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ utils/build
2
+ utils/nms/*.so
3
+ utils/*.c
4
+ build/
client/software/FaceBoxes/utils/__init__.py ADDED
File without changes
client/software/FaceBoxes/utils/align_trans.py ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # https://github.com/ZhaoJ9014/face.evoLVe.PyTorch
2
+ import numpy as np
3
+ import cv2
4
+ from .matlab_cp2tform import get_similarity_transform_for_cv2
5
+
6
+
7
+ # reference facial points, a list of coordinates (x,y)
8
+ REFERENCE_FACIAL_POINTS = [ # default reference facial points for crop_size = (112, 112); should adjust REFERENCE_FACIAL_POINTS accordingly for other crop_size
9
+ [30.29459953, 51.69630051],
10
+ [65.53179932, 51.50139999],
11
+ [48.02519989, 71.73660278],
12
+ [33.54930115, 92.3655014],
13
+ [62.72990036, 92.20410156]
14
+ ]
15
+
16
+ DEFAULT_CROP_SIZE = (96, 112)
17
+
18
+
19
+ class FaceWarpException(Exception):
20
+ def __str__(self):
21
+ return 'In File {}:{}'.format(
22
+ __file__, super.__str__(self))
23
+
24
+
25
+ def get_reference_facial_points(output_size=None,
26
+ inner_padding_factor=0.0,
27
+ outer_padding=(0, 0),
28
+ default_square=False):
29
+ """
30
+ Function:
31
+ ----------
32
+ get reference 5 key points according to crop settings:
33
+ 0. Set default crop_size:
34
+ if default_square:
35
+ crop_size = (112, 112)
36
+ else:
37
+ crop_size = (96, 112)
38
+ 1. Pad the crop_size by inner_padding_factor in each side;
39
+ 2. Resize crop_size into (output_size - outer_padding*2),
40
+ pad into output_size with outer_padding;
41
+ 3. Output reference_5point;
42
+ Parameters:
43
+ ----------
44
+ @output_size: (w, h) or None
45
+ size of aligned face image
46
+ @inner_padding_factor: (w_factor, h_factor)
47
+ padding factor for inner (w, h)
48
+ @outer_padding: (w_pad, h_pad)
49
+ each row is a pair of coordinates (x, y)
50
+ @default_square: True or False
51
+ if True:
52
+ default crop_size = (112, 112)
53
+ else:
54
+ default crop_size = (96, 112);
55
+ !!! make sure, if output_size is not None:
56
+ (output_size - outer_padding)
57
+ = some_scale * (default crop_size * (1.0 + inner_padding_factor))
58
+ Returns:
59
+ ----------
60
+ @reference_5point: 5x2 np.array
61
+ each row is a pair of transformed coordinates (x, y)
62
+ """
63
+ # print('\n===> get_reference_facial_points():')
64
+
65
+ # print('---> Params:')
66
+ # print(' output_size: ', output_size)
67
+ # print(' inner_padding_factor: ', inner_padding_factor)
68
+ # print(' outer_padding:', outer_padding)
69
+ # print(' default_square: ', default_square)
70
+
71
+ tmp_5pts = np.array(REFERENCE_FACIAL_POINTS)
72
+ tmp_crop_size = np.array(DEFAULT_CROP_SIZE)
73
+
74
+ # 0) make the inner region a square
75
+ if default_square:
76
+ size_diff = max(tmp_crop_size) - tmp_crop_size
77
+ tmp_5pts += size_diff / 2
78
+ tmp_crop_size += size_diff
79
+
80
+ # print('---> default:')
81
+ # print(' crop_size = ', tmp_crop_size)
82
+ # print(' reference_5pts = ', tmp_5pts)
83
+
84
+ if (output_size and
85
+ output_size[0] == tmp_crop_size[0] and
86
+ output_size[1] == tmp_crop_size[1]):
87
+ # print('output_size == DEFAULT_CROP_SIZE {}: return default reference points'.format(tmp_crop_size))
88
+ return tmp_5pts
89
+
90
+ if (inner_padding_factor == 0 and
91
+ outer_padding == (0, 0)):
92
+ if output_size is None:
93
+ # print('No paddings to do: return default reference points')
94
+ return tmp_5pts
95
+ else:
96
+ raise FaceWarpException(
97
+ 'No paddings to do, output_size must be None or {}'.format(tmp_crop_size))
98
+
99
+ # check output size
100
+ if not (0 <= inner_padding_factor <= 1.0):
101
+ raise FaceWarpException('Not (0 <= inner_padding_factor <= 1.0)')
102
+
103
+ if ((inner_padding_factor > 0 or outer_padding[0] > 0 or outer_padding[1] > 0)
104
+ and output_size is None):
105
+ output_size = tmp_crop_size * \
106
+ (1 + inner_padding_factor * 2).astype(np.int32)
107
+ output_size += np.array(outer_padding)
108
+ # print(' deduced from paddings, output_size = ', output_size)
109
+
110
+ if not (outer_padding[0] < output_size[0]
111
+ and outer_padding[1] < output_size[1]):
112
+ raise FaceWarpException('Not (outer_padding[0] < output_size[0]'
113
+ 'and outer_padding[1] < output_size[1])')
114
+
115
+ # 1) pad the inner region according inner_padding_factor
116
+ # print('---> STEP1: pad the inner region according inner_padding_factor')
117
+ if inner_padding_factor > 0:
118
+ size_diff = tmp_crop_size * inner_padding_factor * 2
119
+ tmp_5pts += size_diff / 2
120
+ tmp_crop_size += np.round(size_diff).astype(np.int32)
121
+
122
+ # print(' crop_size = ', tmp_crop_size)
123
+ # print(' reference_5pts = ', tmp_5pts)
124
+
125
+ # 2) resize the padded inner region
126
+ # print('---> STEP2: resize the padded inner region')
127
+ size_bf_outer_pad = np.array(output_size) - np.array(outer_padding) * 2
128
+ # print(' crop_size = ', tmp_crop_size)
129
+ # print(' size_bf_outer_pad = ', size_bf_outer_pad)
130
+
131
+ if size_bf_outer_pad[0] * tmp_crop_size[1] != size_bf_outer_pad[1] * tmp_crop_size[0]:
132
+ raise FaceWarpException('Must have (output_size - outer_padding)'
133
+ '= some_scale * (crop_size * (1.0 + inner_padding_factor)')
134
+
135
+ scale_factor = size_bf_outer_pad[0].astype(np.float32) / tmp_crop_size[0]
136
+ # print(' resize scale_factor = ', scale_factor)
137
+ tmp_5pts = tmp_5pts * scale_factor
138
+ # size_diff = tmp_crop_size * (scale_factor - min(scale_factor))
139
+ # tmp_5pts = tmp_5pts + size_diff / 2
140
+ tmp_crop_size = size_bf_outer_pad
141
+ # print(' crop_size = ', tmp_crop_size)
142
+ # print(' reference_5pts = ', tmp_5pts)
143
+
144
+ # 3) add outer_padding to make output_size
145
+ reference_5point = tmp_5pts + np.array(outer_padding)
146
+ tmp_crop_size = output_size
147
+ # print('---> STEP3: add outer_padding to make output_size')
148
+ # print(' crop_size = ', tmp_crop_size)
149
+ # print(' reference_5pts = ', tmp_5pts)
150
+
151
+ # print('===> end get_reference_facial_points\n')
152
+
153
+ return reference_5point
154
+
155
+
156
+ def get_affine_transform_matrix(src_pts, dst_pts):
157
+ """
158
+ Function:
159
+ ----------
160
+ get affine transform matrix 'tfm' from src_pts to dst_pts
161
+ Parameters:
162
+ ----------
163
+ @src_pts: Kx2 np.array
164
+ source points matrix, each row is a pair of coordinates (x, y)
165
+ @dst_pts: Kx2 np.array
166
+ destination points matrix, each row is a pair of coordinates (x, y)
167
+ Returns:
168
+ ----------
169
+ @tfm: 2x3 np.array
170
+ transform matrix from src_pts to dst_pts
171
+ """
172
+
173
+ tfm = np.float32([[1, 0, 0], [0, 1, 0]])
174
+ n_pts = src_pts.shape[0]
175
+ ones = np.ones((n_pts, 1), src_pts.dtype)
176
+ src_pts_ = np.hstack([src_pts, ones])
177
+ dst_pts_ = np.hstack([dst_pts, ones])
178
+
179
+ # #print(('src_pts_:\n' + str(src_pts_))
180
+ # #print(('dst_pts_:\n' + str(dst_pts_))
181
+
182
+ A, res, rank, s = np.linalg.lstsq(src_pts_, dst_pts_)
183
+
184
+ # #print(('np.linalg.lstsq return A: \n' + str(A))
185
+ # #print(('np.linalg.lstsq return res: \n' + str(res))
186
+ # #print(('np.linalg.lstsq return rank: \n' + str(rank))
187
+ # #print(('np.linalg.lstsq return s: \n' + str(s))
188
+
189
+ if rank == 3:
190
+ tfm = np.float32([
191
+ [A[0, 0], A[1, 0], A[2, 0]],
192
+ [A[0, 1], A[1, 1], A[2, 1]]
193
+ ])
194
+ elif rank == 2:
195
+ tfm = np.float32([
196
+ [A[0, 0], A[1, 0], 0],
197
+ [A[0, 1], A[1, 1], 0]
198
+ ])
199
+
200
+ return tfm
201
+
202
+
203
+ def warp_and_crop_face(src_img,
204
+ facial_pts,
205
+ reference_pts=None,
206
+ crop_size=(96, 112),
207
+ align_type='smilarity'):
208
+ """
209
+ Function:
210
+ ----------
211
+ apply affine transform 'trans' to uv
212
+ Parameters:
213
+ ----------
214
+ @src_img: 3x3 np.array
215
+ input image
216
+ @facial_pts: could be
217
+ 1)a list of K coordinates (x,y)
218
+ or
219
+ 2) Kx2 or 2xK np.array
220
+ each row or col is a pair of coordinates (x, y)
221
+ @reference_pts: could be
222
+ 1) a list of K coordinates (x,y)
223
+ or
224
+ 2) Kx2 or 2xK np.array
225
+ each row or col is a pair of coordinates (x, y)
226
+ or
227
+ 3) None
228
+ if None, use default reference facial points
229
+ @crop_size: (w, h)
230
+ output face image size
231
+ @align_type: transform type, could be one of
232
+ 1) 'similarity': use similarity transform
233
+ 2) 'cv2_affine': use the first 3 points to do affine transform,
234
+ by calling cv2.getAffineTransform()
235
+ 3) 'affine': use all points to do affine transform
236
+ Returns:
237
+ ----------
238
+ @face_img: output face image with size (w, h) = @crop_size
239
+ """
240
+
241
+ if reference_pts is None:
242
+ if crop_size[0] == 96 and crop_size[1] == 112:
243
+ reference_pts = REFERENCE_FACIAL_POINTS
244
+ else:
245
+ default_square = False
246
+ inner_padding_factor = 0
247
+ outer_padding = (0, 0)
248
+ output_size = crop_size
249
+
250
+ reference_pts = get_reference_facial_points(output_size,
251
+ inner_padding_factor,
252
+ outer_padding,
253
+ default_square)
254
+
255
+ ref_pts = np.float32(reference_pts)
256
+ ref_pts_shp = ref_pts.shape
257
+ if max(ref_pts_shp) < 3 or min(ref_pts_shp) != 2:
258
+ raise FaceWarpException(
259
+ 'reference_pts.shape must be (K,2) or (2,K) and K>2')
260
+
261
+ if ref_pts_shp[0] == 2:
262
+ ref_pts = ref_pts.T
263
+
264
+ src_pts = np.float32(facial_pts)
265
+ src_pts_shp = src_pts.shape
266
+ if max(src_pts_shp) < 3 or min(src_pts_shp) != 2:
267
+ raise FaceWarpException(
268
+ 'facial_pts.shape must be (K,2) or (2,K) and K>2')
269
+
270
+ if src_pts_shp[0] == 2:
271
+ src_pts = src_pts.T
272
+
273
+ # #print('--->src_pts:\n', src_pts
274
+ # #print('--->ref_pts\n', ref_pts
275
+
276
+ if src_pts.shape != ref_pts.shape:
277
+ raise FaceWarpException(
278
+ 'facial_pts and reference_pts must have the same shape')
279
+
280
+ if align_type is 'cv2_affine':
281
+ tfm = cv2.getAffineTransform(src_pts[0:3], ref_pts[0:3])
282
+ # #print(('cv2.getAffineTransform() returns tfm=\n' + str(tfm))
283
+ elif align_type is 'affine':
284
+ tfm = get_affine_transform_matrix(src_pts, ref_pts)
285
+ # #print(('get_affine_transform_matrix() returns tfm=\n' + str(tfm))
286
+ else:
287
+ tfm = get_similarity_transform_for_cv2(src_pts, ref_pts)
288
+ # #print(('get_similarity_transform_for_cv2() returns tfm=\n' + str(tfm))
289
+
290
+ # #print('--->Transform matrix: '
291
+ # #print(('type(tfm):' + str(type(tfm)))
292
+ # #print(('tfm.dtype:' + str(tfm.dtype))
293
+ # #print( tfm
294
+
295
+ face_img = cv2.warpAffine(src_img, tfm, (crop_size[0], crop_size[1]))
296
+
297
+ return face_img
client/software/FaceBoxes/utils/box_utils.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding: utf-8
2
+
3
+ import torch
4
+ import numpy as np
5
+
6
+
7
+ def point_form(boxes):
8
+ """ Convert prior_boxes to (xmin, ymin, xmax, ymax)
9
+ representation for comparison to point form ground truth data.
10
+ Args:
11
+ boxes: (tensor) center-size default boxes from priorbox layers.
12
+ Return:
13
+ boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes.
14
+ """
15
+ return torch.cat((boxes[:, :2] - boxes[:, 2:] / 2, # xmin, ymin
16
+ boxes[:, :2] + boxes[:, 2:] / 2), 1) # xmax, ymax
17
+
18
+
19
+ def center_size(boxes):
20
+ """ Convert prior_boxes to (cx, cy, w, h)
21
+ representation for comparison to center-size form ground truth data.
22
+ Args:
23
+ boxes: (tensor) point_form boxes
24
+ Return:
25
+ boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes.
26
+ """
27
+ return torch.cat((boxes[:, 2:] + boxes[:, :2]) / 2, # cx, cy
28
+ boxes[:, 2:] - boxes[:, :2], 1) # w, h
29
+
30
+
31
+ def intersect(box_a, box_b):
32
+ """ We resize both tensors to [A,B,2] without new malloc:
33
+ [A,2] -> [A,1,2] -> [A,B,2]
34
+ [B,2] -> [1,B,2] -> [A,B,2]
35
+ Then we compute the area of intersect between box_a and box_b.
36
+ Args:
37
+ box_a: (tensor) bounding boxes, Shape: [A,4].
38
+ box_b: (tensor) bounding boxes, Shape: [B,4].
39
+ Return:
40
+ (tensor) intersection area, Shape: [A,B].
41
+ """
42
+ A = box_a.size(0)
43
+ B = box_b.size(0)
44
+ max_xy = torch.min(box_a[:, 2:].unsqueeze(1).expand(A, B, 2),
45
+ box_b[:, 2:].unsqueeze(0).expand(A, B, 2))
46
+ min_xy = torch.max(box_a[:, :2].unsqueeze(1).expand(A, B, 2),
47
+ box_b[:, :2].unsqueeze(0).expand(A, B, 2))
48
+ inter = torch.clamp((max_xy - min_xy), min=0)
49
+ return inter[:, :, 0] * inter[:, :, 1]
50
+
51
+
52
+ def jaccard(box_a, box_b):
53
+ """Compute the jaccard overlap of two sets of boxes. The jaccard overlap
54
+ is simply the intersection over union of two boxes. Here we operate on
55
+ ground truth boxes and default boxes.
56
+ E.g.:
57
+ A ∩ B / A βˆͺ B = A ∩ B / (area(A) + area(B) - A ∩ B)
58
+ Args:
59
+ box_a: (tensor) Ground truth bounding boxes, Shape: [num_objects,4]
60
+ box_b: (tensor) Prior boxes from priorbox layers, Shape: [num_priors,4]
61
+ Return:
62
+ jaccard overlap: (tensor) Shape: [box_a.size(0), box_b.size(0)]
63
+ """
64
+ inter = intersect(box_a, box_b)
65
+ area_a = ((box_a[:, 2] - box_a[:, 0]) *
66
+ (box_a[:, 3] - box_a[:, 1])).unsqueeze(1).expand_as(inter) # [A,B]
67
+ area_b = ((box_b[:, 2] - box_b[:, 0]) *
68
+ (box_b[:, 3] - box_b[:, 1])).unsqueeze(0).expand_as(inter) # [A,B]
69
+ union = area_a + area_b - inter
70
+ return inter / union # [A,B]
71
+
72
+
73
+ def matrix_iou(a, b):
74
+ """
75
+ return iou of a and b, numpy version for data augenmentation
76
+ """
77
+ lt = np.maximum(a[:, np.newaxis, :2], b[:, :2])
78
+ rb = np.minimum(a[:, np.newaxis, 2:], b[:, 2:])
79
+
80
+ area_i = np.prod(rb - lt, axis=2) * (lt < rb).all(axis=2)
81
+ area_a = np.prod(a[:, 2:] - a[:, :2], axis=1)
82
+ area_b = np.prod(b[:, 2:] - b[:, :2], axis=1)
83
+ return area_i / (area_a[:, np.newaxis] + area_b - area_i)
84
+
85
+
86
+ def matrix_iof(a, b):
87
+ """
88
+ return iof of a and b, numpy version for data augenmentation
89
+ """
90
+ lt = np.maximum(a[:, np.newaxis, :2], b[:, :2])
91
+ rb = np.minimum(a[:, np.newaxis, 2:], b[:, 2:])
92
+
93
+ area_i = np.prod(rb - lt, axis=2) * (lt < rb).all(axis=2)
94
+ area_a = np.prod(a[:, 2:] - a[:, :2], axis=1)
95
+ return area_i / np.maximum(area_a[:, np.newaxis], 1)
96
+
97
+
98
+ def match(threshold, truths, priors, variances, labels, loc_t, conf_t, idx):
99
+ """Match each prior box with the ground truth box of the highest jaccard
100
+ overlap, encode the bounding boxes, then return the matched indices
101
+ corresponding to both confidence and location preds.
102
+ Args:
103
+ threshold: (float) The overlap threshold used when mathing boxes.
104
+ truths: (tensor) Ground truth boxes, Shape: [num_obj, num_priors].
105
+ priors: (tensor) Prior boxes from priorbox layers, Shape: [n_priors,4].
106
+ variances: (tensor) Variances corresponding to each prior coord,
107
+ Shape: [num_priors, 4].
108
+ labels: (tensor) All the class labels for the image, Shape: [num_obj].
109
+ loc_t: (tensor) Tensor to be filled w/ endcoded location targets.
110
+ conf_t: (tensor) Tensor to be filled w/ matched indices for conf preds.
111
+ idx: (int) current batch index
112
+ Return:
113
+ The matched indices corresponding to 1)location and 2)confidence preds.
114
+ """
115
+ # jaccard index
116
+ overlaps = jaccard(
117
+ truths,
118
+ point_form(priors)
119
+ )
120
+ # (Bipartite Matching)
121
+ # [1,num_objects] best prior for each ground truth
122
+ best_prior_overlap, best_prior_idx = overlaps.max(1, keepdim=True)
123
+
124
+ # ignore hard gt
125
+ valid_gt_idx = best_prior_overlap[:, 0] >= 0.2
126
+ best_prior_idx_filter = best_prior_idx[valid_gt_idx, :]
127
+ if best_prior_idx_filter.shape[0] <= 0:
128
+ loc_t[idx] = 0
129
+ conf_t[idx] = 0
130
+ return
131
+
132
+ # [1,num_priors] best ground truth for each prior
133
+ best_truth_overlap, best_truth_idx = overlaps.max(0, keepdim=True)
134
+ best_truth_idx.squeeze_(0)
135
+ best_truth_overlap.squeeze_(0)
136
+ best_prior_idx.squeeze_(1)
137
+ best_prior_idx_filter.squeeze_(1)
138
+ best_prior_overlap.squeeze_(1)
139
+ best_truth_overlap.index_fill_(
140
+ 0, best_prior_idx_filter, 2) # ensure best prior
141
+ # TODO refactor: index best_prior_idx with long tensor
142
+ # ensure every gt matches with its prior of max overlap
143
+ for j in range(best_prior_idx.size(0)):
144
+ best_truth_idx[best_prior_idx[j]] = j
145
+ matches = truths[best_truth_idx] # Shape: [num_priors,4]
146
+ conf = labels[best_truth_idx] # Shape: [num_priors]
147
+ conf[best_truth_overlap < threshold] = 0 # label as background
148
+ loc = encode(matches, priors, variances)
149
+ loc_t[idx] = loc # [num_priors,4] encoded offsets to learn
150
+ conf_t[idx] = conf # [num_priors] top class label for each prior
151
+
152
+
153
+ def encode(matched, priors, variances):
154
+ """Encode the variances from the priorbox layers into the ground truth boxes
155
+ we have matched (based on jaccard overlap) with the prior boxes.
156
+ Args:
157
+ matched: (tensor) Coords of ground truth for each prior in point-form
158
+ Shape: [num_priors, 4].
159
+ priors: (tensor) Prior boxes in center-offset form
160
+ Shape: [num_priors,4].
161
+ variances: (list[float]) Variances of priorboxes
162
+ Return:
163
+ encoded boxes (tensor), Shape: [num_priors, 4]
164
+ """
165
+
166
+ # dist b/t match center and prior's center
167
+ g_cxcy = (matched[:, :2] + matched[:, 2:]) / 2 - priors[:, :2]
168
+ # encode variance
169
+ g_cxcy /= (variances[0] * priors[:, 2:])
170
+ # match wh / prior wh
171
+ g_wh = (matched[:, 2:] - matched[:, :2]) / priors[:, 2:]
172
+ g_wh = torch.log(g_wh) / variances[1]
173
+ # return target for smooth_l1_loss
174
+ return torch.cat([g_cxcy, g_wh], 1) # [num_priors,4]
175
+
176
+
177
+ # Adapted from https://github.com/Hakuyume/chainer-ssd
178
+ def decode(loc, priors, variances):
179
+ """Decode locations from predictions using priors to undo
180
+ the encoding we did for offset regression at train time.
181
+ Args:
182
+ loc (tensor): location predictions for loc layers,
183
+ Shape: [num_priors,4]
184
+ priors (tensor): Prior boxes in center-offset form.
185
+ Shape: [num_priors,4].
186
+ variances: (list[float]) Variances of priorboxes
187
+ Return:
188
+ decoded bounding box predictions
189
+ """
190
+
191
+ boxes = torch.cat((
192
+ priors[:, :2] + loc[:, :2] * variances[0] * priors[:, 2:],
193
+ priors[:, 2:] * torch.exp(loc[:, 2:] * variances[1])), 1)
194
+ boxes[:, :2] -= boxes[:, 2:] / 2
195
+ boxes[:, 2:] += boxes[:, :2]
196
+ return boxes
197
+
198
+
199
+ def log_sum_exp(x):
200
+ """Utility function for computing log_sum_exp while determining
201
+ This will be used to determine unaveraged confidence loss across
202
+ all examples in a batch.
203
+ Args:
204
+ x (Variable(tensor)): conf_preds from conf layers
205
+ """
206
+ x_max = x.data.max()
207
+ return torch.log(torch.sum(torch.exp(x - x_max), 1, keepdim=True)) + x_max
208
+
209
+
210
+ # Original author: Francisco Massa:
211
+ # https://github.com/fmassa/object-detection.torch
212
+ # Ported to PyTorch by Max deGroot (02/01/2017)
213
+ def nms(boxes, scores, overlap=0.5, top_k=200):
214
+ """Apply non-maximum suppression at test time to avoid detecting too many
215
+ overlapping bounding boxes for a given object.
216
+ Args:
217
+ boxes: (tensor) The location preds for the img, Shape: [num_priors,4].
218
+ scores: (tensor) The class predscores for the img, Shape:[num_priors].
219
+ overlap: (float) The overlap thresh for suppressing unnecessary boxes.
220
+ top_k: (int) The Maximum number of box preds to consider.
221
+ Return:
222
+ The indices of the kept boxes with respect to num_priors.
223
+ """
224
+
225
+ keep = torch.Tensor(scores.size(0)).fill_(0).long()
226
+ if boxes.numel() == 0:
227
+ return keep
228
+ x1 = boxes[:, 0]
229
+ y1 = boxes[:, 1]
230
+ x2 = boxes[:, 2]
231
+ y2 = boxes[:, 3]
232
+ area = torch.mul(x2 - x1, y2 - y1)
233
+ v, idx = scores.sort(0) # sort in ascending order
234
+ # I = I[v >= 0.01]
235
+ idx = idx[-top_k:] # indices of the top-k largest vals
236
+ xx1 = boxes.new()
237
+ yy1 = boxes.new()
238
+ xx2 = boxes.new()
239
+ yy2 = boxes.new()
240
+ w = boxes.new()
241
+ h = boxes.new()
242
+
243
+ # keep = torch.Tensor()
244
+ count = 0
245
+ while idx.numel() > 0:
246
+ i = idx[-1] # index of current largest val
247
+ # keep.append(i)
248
+ keep[count] = i
249
+ count += 1
250
+ if idx.size(0) == 1:
251
+ break
252
+ idx = idx[:-1] # remove kept element from view
253
+ # load bboxes of next highest vals
254
+ torch.index_select(x1, 0, idx, out=xx1)
255
+ torch.index_select(y1, 0, idx, out=yy1)
256
+ torch.index_select(x2, 0, idx, out=xx2)
257
+ torch.index_select(y2, 0, idx, out=yy2)
258
+ # store element-wise max with next highest score
259
+ xx1 = torch.clamp(xx1, min=x1[i])
260
+ yy1 = torch.clamp(yy1, min=y1[i])
261
+ xx2 = torch.clamp(xx2, max=x2[i])
262
+ yy2 = torch.clamp(yy2, max=y2[i])
263
+ w.resize_as_(xx2)
264
+ h.resize_as_(yy2)
265
+ w = xx2 - xx1
266
+ h = yy2 - yy1
267
+ # check sizes of xx1 and xx2.. after each iteration
268
+ w = torch.clamp(w, min=0.0)
269
+ h = torch.clamp(h, min=0.0)
270
+ inter = w * h
271
+ # IoU = i / (area(a) + area(b) - i)
272
+ rem_areas = torch.index_select(area, 0, idx) # load remaining areas)
273
+ union = (rem_areas - inter) + area[i]
274
+ IoU = inter / union # store result in iou
275
+ # keep only elements with an IoU <= overlap
276
+ idx = idx[IoU.le(overlap)]
277
+ return keep, count
client/software/FaceBoxes/utils/build.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding: utf-8
2
+
3
+ # --------------------------------------------------------
4
+ # Fast R-CNN
5
+ # Copyright (c) 2015 Microsoft
6
+ # Licensed under The MIT License [see LICENSE for details]
7
+ # Written by Ross Girshick
8
+ # --------------------------------------------------------
9
+
10
+ import os
11
+ from os.path import join as pjoin
12
+ import numpy as np
13
+ from distutils.core import setup
14
+ from distutils.extension import Extension
15
+ from Cython.Distutils import build_ext
16
+
17
+
18
+ def find_in_path(name, path):
19
+ "Find a file in a search path"
20
+ # adapted fom http://code.activestate.com/recipes/52224-find-a-file-given-a-search-path/
21
+ for dir in path.split(os.pathsep):
22
+ binpath = pjoin(dir, name)
23
+ if os.path.exists(binpath):
24
+ return os.path.abspath(binpath)
25
+ return None
26
+
27
+
28
+ # Obtain the numpy include directory. This logic works across numpy versions.
29
+ try:
30
+ numpy_include = np.get_include()
31
+ except AttributeError:
32
+ numpy_include = np.get_numpy_include()
33
+
34
+
35
+ # run the customize_compiler
36
+ class custom_build_ext(build_ext):
37
+ def build_extensions(self):
38
+ # customize_compiler_for_nvcc(self.compiler)
39
+ build_ext.build_extensions(self)
40
+
41
+
42
+ ext_modules = [
43
+ Extension(
44
+ "nms.cpu_nms",
45
+ ["nms/cpu_nms.pyx"],
46
+ # extra_compile_args={'gcc': ["-Wno-cpp", "-Wno-unused-function"]},
47
+ extra_compile_args=[""],
48
+ include_dirs=[numpy_include]
49
+ )
50
+ ]
51
+
52
+ setup(
53
+ name='mot_utils',
54
+ ext_modules=ext_modules,
55
+ # inject our custom trigger
56
+ cmdclass={'build_ext': custom_build_ext},
57
+ )
client/software/FaceBoxes/utils/config.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # coding: utf-8
2
+
3
+ cfg = {
4
+ 'name': 'FaceBoxes',
5
+ 'min_sizes': [[32, 64, 128], [256], [512]],
6
+ 'steps': [32, 64, 128],
7
+ 'variance': [0.1, 0.2],
8
+ 'clip': False
9
+ }
client/software/FaceBoxes/utils/eval.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import print_function, absolute_import
2
+ import numpy as np
3
+
4
+ __all__ = ['accuracy', 'normalizedME']
5
+
6
+
7
+ def accuracy(output, target, topk=(1,)):
8
+ """Computes the precision@k for the specified values of k"""
9
+ maxk = max(topk)
10
+ batch_size = target.size(0)
11
+
12
+ _, pred = output.topk(maxk, 1, True, True)
13
+ pred = pred.t()
14
+ correct = pred.eq(target.view(1, -1).expand_as(pred))
15
+
16
+ res = []
17
+ for k in topk:
18
+ correct_k = correct[:k].view(-1).float().sum(0)
19
+ res.append(correct_k.mul_(100.0 / batch_size))
20
+ return res
21
+
22
+
23
+ def normalizedME(output, target, w, h):
24
+ batch_size = target.size(0)
25
+ diff = output - target
26
+ diff = np.sqrt(diff.T*diff)/(w*h)
27
+ return diff/batch_size
client/software/FaceBoxes/utils/functions.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding: utf-8
2
+
3
+ import sys
4
+ import os.path as osp
5
+ import torch
6
+
7
+
8
+ def check_keys(model, pretrained_state_dict):
9
+ ckpt_keys = set(pretrained_state_dict.keys())
10
+ model_keys = set(model.state_dict().keys())
11
+ used_pretrained_keys = model_keys & ckpt_keys
12
+ unused_pretrained_keys = ckpt_keys - model_keys
13
+ missing_keys = model_keys - ckpt_keys
14
+ # print('Missing keys:{}'.format(len(missing_keys)))
15
+ # print('Unused checkpoint keys:{}'.format(len(unused_pretrained_keys)))
16
+ # print('Used keys:{}'.format(len(used_pretrained_keys)))
17
+ assert len(used_pretrained_keys) > 0, 'load NONE from pretrained checkpoint'
18
+ return True
19
+
20
+
21
+ def remove_prefix(state_dict, prefix):
22
+ ''' Old style model is stored with all names of parameters sharing common prefix 'module.' '''
23
+ # print('remove prefix \'{}\''.format(prefix))
24
+ def f(x): return x.split(prefix, 1)[-1] if x.startswith(prefix) else x
25
+ return {f(key): value for key, value in state_dict.items()}
26
+
27
+
28
+ def load_model(model, pretrained_path, load_to_cpu):
29
+ if not osp.isfile(pretrained_path):
30
+ print(
31
+ f'The pre-trained FaceBoxes model {pretrained_path} does not exist')
32
+ sys.exit('-1')
33
+ # print('Loading pretrained model from {}'.format(pretrained_path))
34
+ if load_to_cpu:
35
+ pretrained_dict = torch.load(
36
+ pretrained_path, map_location=lambda storage, loc: storage)
37
+ else:
38
+ device = torch.cuda.current_device()
39
+ pretrained_dict = torch.load(
40
+ pretrained_path, map_location=lambda storage, loc: storage.cuda(device))
41
+ if "state_dict" in pretrained_dict.keys():
42
+ pretrained_dict = remove_prefix(
43
+ pretrained_dict['state_dict'], 'module.')
44
+ else:
45
+ pretrained_dict = remove_prefix(pretrained_dict, 'module.')
46
+ check_keys(model, pretrained_dict)
47
+ model.load_state_dict(pretrained_dict, strict=False)
48
+ return model
client/software/FaceBoxes/utils/images/test.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image
2
+ import numpy as np
3
+ img = Image.open('cifar.png')
4
+ pic = np.array(img)
5
+ noise = np.random.randint(-10, 10, pic.shape[-1])
6
+ print(noise.shape)
7
+ pic = pic+noise
8
+ pic = pic.astype(np.uint8)
9
+ asd = Image.fromarray(pic)
client/software/FaceBoxes/utils/logger.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # A simple torch style logger
2
+ # (C) Wei YANG 2017
3
+ from __future__ import absolute_import
4
+ import matplotlib.pyplot as plt
5
+ import os
6
+ import sys
7
+ import numpy as np
8
+
9
+ __all__ = ['Logger', 'LoggerMonitor', 'savefig']
10
+
11
+
12
+ def savefig(fname, dpi=None):
13
+ dpi = 150 if dpi == None else dpi
14
+ plt.savefig(fname, dpi=dpi)
15
+
16
+
17
+ def plot_overlap(logger, names=None):
18
+ names = logger.names if names == None else names
19
+ numbers = logger.numbers
20
+ for _, name in enumerate(names):
21
+ x = np.arange(len(numbers[name]))
22
+ plt.plot(x, np.asarray(numbers[name]))
23
+ return [logger.title + '(' + name + ')' for name in names]
24
+
25
+
26
+ class Logger(object):
27
+ '''Save training process to log file with simple plot function.'''
28
+
29
+ def __init__(self, fpath, title=None, resume=False):
30
+ self.file = None
31
+ self.resume = resume
32
+ self.title = '' if title == None else title
33
+ if fpath is not None:
34
+ if resume:
35
+ self.file = open(fpath, 'r')
36
+ name = self.file.readline()
37
+ self.names = name.rstrip().split('\t')
38
+ self.numbers = {}
39
+ for _, name in enumerate(self.names):
40
+ self.numbers[name] = []
41
+
42
+ for numbers in self.file:
43
+ numbers = numbers.rstrip().split('\t')
44
+ for i in range(0, len(numbers)):
45
+ self.numbers[self.names[i]].append(numbers[i])
46
+ self.file.close()
47
+ self.file = open(fpath, 'a')
48
+ else:
49
+ self.file = open(fpath, 'w')
50
+
51
+ def set_names(self, names):
52
+ if self.resume:
53
+ pass
54
+ # initialize numbers as empty list
55
+ self.numbers = {}
56
+ self.names = names
57
+ for _, name in enumerate(self.names):
58
+ self.file.write(name)
59
+ self.file.write('\t')
60
+ self.numbers[name] = []
61
+ self.file.write('\n')
62
+ self.file.flush()
63
+
64
+ def append(self, numbers):
65
+ assert len(self.names) == len(numbers), 'Numbers do not match names'
66
+ for index, num in enumerate(numbers):
67
+ self.file.write("{0:.6f}".format(num))
68
+ self.file.write('\t')
69
+ self.numbers[self.names[index]].append(num)
70
+ self.file.write('\n')
71
+ self.file.flush()
72
+
73
+ def plot(self, names=None):
74
+ names = self.names if names == None else names
75
+ numbers = self.numbers
76
+ for _, name in enumerate(names):
77
+ x = np.arange(len(numbers[name]))
78
+ plt.plot(x, np.asarray(numbers[name]))
79
+ plt.legend([self.title + '(' + name + ')' for name in names])
80
+ plt.grid(True)
81
+
82
+ def close(self):
83
+ if self.file is not None:
84
+ self.file.close()
85
+
86
+
87
+ class LoggerMonitor(object):
88
+ '''Load and visualize multiple logs.'''
89
+
90
+ def __init__(self, paths):
91
+ '''paths is a distionary with {name:filepath} pair'''
92
+ self.loggers = []
93
+ for title, path in paths.items():
94
+ logger = Logger(path, title=title, resume=True)
95
+ self.loggers.append(logger)
96
+
97
+ def plot(self, names=None):
98
+ plt.figure()
99
+ plt.subplot(121)
100
+ legend_text = []
101
+ for logger in self.loggers:
102
+ legend_text += plot_overlap(logger, names)
103
+ plt.legend(legend_text, bbox_to_anchor=(
104
+ 1.05, 1), loc=2, borderaxespad=0.)
105
+ plt.grid(True)
106
+
107
+
108
+ if __name__ == '__main__':
109
+ # # Example
110
+ # logger = Logger('test.txt')
111
+ # logger.set_names(['Train loss', 'Valid loss','Test loss'])
112
+
113
+ # length = 100
114
+ # t = np.arange(length)
115
+ # train_loss = np.exp(-t / 10.0) + np.random.rand(length) * 0.1
116
+ # valid_loss = np.exp(-t / 10.0) + np.random.rand(length) * 0.1
117
+ # test_loss = np.exp(-t / 10.0) + np.random.rand(length) * 0.1
118
+
119
+ # for i in range(0, length):
120
+ # logger.append([train_loss[i], valid_loss[i], test_loss[i]])
121
+ # logger.plot()
122
+
123
+ # Example: logger monitor
124
+ paths = {
125
+ 'resadvnet20': '/home/wyang/code/pytorch-classification/checkpoint/cifar10/resadvnet20/log.txt',
126
+ 'resadvnet32': '/home/wyang/code/pytorch-classification/checkpoint/cifar10/resadvnet32/log.txt',
127
+ 'resadvnet44': '/home/wyang/code/pytorch-classification/checkpoint/cifar10/resadvnet44/log.txt',
128
+ }
129
+
130
+ field = ['Valid Acc.']
131
+
132
+ monitor = LoggerMonitor(paths)
133
+ monitor.plot(names=field)
134
+ savefig('test.eps')
client/software/FaceBoxes/utils/matlab_cp2tform.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from numpy.linalg import inv, norm, lstsq
3
+ from numpy.linalg import matrix_rank as rank
4
+
5
+
6
+ class MatlabCp2tormException(Exception):
7
+ def __str__(self):
8
+ return "In File {}:{}".format(
9
+ __file__, super.__str__(self))
10
+
11
+
12
+ def tformfwd(trans, uv):
13
+ """
14
+ Function:
15
+ ----------
16
+ apply affine transform 'trans' to uv
17
+ Parameters:
18
+ ----------
19
+ @trans: 3x3 np.array
20
+ transform matrix
21
+ @uv: Kx2 np.array
22
+ each row is a pair of coordinates (x, y)
23
+ Returns:
24
+ ----------
25
+ @xy: Kx2 np.array
26
+ each row is a pair of transformed coordinates (x, y)
27
+ """
28
+ uv = np.hstack((
29
+ uv, np.ones((uv.shape[0], 1))
30
+ ))
31
+ xy = np.dot(uv, trans)
32
+ xy = xy[:, 0:-1]
33
+ return xy
34
+
35
+
36
+ def tforminv(trans, uv):
37
+ """
38
+ Function:
39
+ ----------
40
+ apply the inverse of affine transform 'trans' to uv
41
+ Parameters:
42
+ ----------
43
+ @trans: 3x3 np.array
44
+ transform matrix
45
+ @uv: Kx2 np.array
46
+ each row is a pair of coordinates (x, y)
47
+ Returns:
48
+ ----------
49
+ @xy: Kx2 np.array
50
+ each row is a pair of inverse-transformed coordinates (x, y)
51
+ """
52
+ Tinv = inv(trans)
53
+ xy = tformfwd(Tinv, uv)
54
+ return xy
55
+
56
+
57
+ def findNonreflectiveSimilarity(uv, xy, options=None):
58
+
59
+ options = {'K': 2}
60
+
61
+ K = options['K']
62
+ M = xy.shape[0]
63
+ x = xy[:, 0].reshape((-1, 1)) # use reshape to keep a column vector
64
+ y = xy[:, 1].reshape((-1, 1)) # use reshape to keep a column vector
65
+ # print('--->x, y:\n', x, y
66
+
67
+ tmp1 = np.hstack((x, y, np.ones((M, 1)), np.zeros((M, 1))))
68
+ tmp2 = np.hstack((y, -x, np.zeros((M, 1)), np.ones((M, 1))))
69
+ X = np.vstack((tmp1, tmp2))
70
+ # print('--->X.shape: ', X.shape
71
+ # print('X:\n', X
72
+
73
+ u = uv[:, 0].reshape((-1, 1)) # use reshape to keep a column vector
74
+ v = uv[:, 1].reshape((-1, 1)) # use reshape to keep a column vector
75
+ U = np.vstack((u, v))
76
+ # print('--->U.shape: ', U.shape
77
+ # print('U:\n', U
78
+
79
+ # We know that X * r = U
80
+ if rank(X) >= 2 * K:
81
+ r, _, _, _ = lstsq(X, U)
82
+ r = np.squeeze(r)
83
+ else:
84
+ raise Exception("cp2tform: two Unique Points Req")
85
+
86
+ # print('--->r:\n', r
87
+
88
+ sc = r[0]
89
+ ss = r[1]
90
+ tx = r[2]
91
+ ty = r[3]
92
+
93
+ Tinv = np.array([
94
+ [sc, -ss, 0],
95
+ [ss, sc, 0],
96
+ [tx, ty, 1]
97
+ ])
98
+
99
+ # print('--->Tinv:\n', Tinv
100
+
101
+ T = inv(Tinv)
102
+ # print('--->T:\n', T
103
+
104
+ T[:, 2] = np.array([0, 0, 1])
105
+
106
+ return T, Tinv
107
+
108
+
109
+ def findSimilarity(uv, xy, options=None):
110
+
111
+ options = {'K': 2}
112
+
113
+ # uv = np.array(uv)
114
+ # xy = np.array(xy)
115
+
116
+ # Solve for trans1
117
+ trans1, trans1_inv = findNonreflectiveSimilarity(uv, xy, options)
118
+
119
+ # Solve for trans2
120
+
121
+ # manually reflect the xy data across the Y-axis
122
+ xyR = xy
123
+ xyR[:, 0] = -1 * xyR[:, 0]
124
+
125
+ trans2r, trans2r_inv = findNonreflectiveSimilarity(uv, xyR, options)
126
+
127
+ # manually reflect the tform to undo the reflection done on xyR
128
+ TreflectY = np.array([
129
+ [-1, 0, 0],
130
+ [0, 1, 0],
131
+ [0, 0, 1]
132
+ ])
133
+
134
+ trans2 = np.dot(trans2r, TreflectY)
135
+
136
+ # Figure out if trans1 or trans2 is better
137
+ xy1 = tformfwd(trans1, uv)
138
+ norm1 = norm(xy1 - xy)
139
+
140
+ xy2 = tformfwd(trans2, uv)
141
+ norm2 = norm(xy2 - xy)
142
+
143
+ if norm1 <= norm2:
144
+ return trans1, trans1_inv
145
+ else:
146
+ trans2_inv = inv(trans2)
147
+ return trans2, trans2_inv
148
+
149
+
150
+ def get_similarity_transform(src_pts, dst_pts, reflective=True):
151
+ """
152
+ Function:
153
+ ----------
154
+ Find Similarity Transform Matrix 'trans':
155
+ u = src_pts[:, 0]
156
+ v = src_pts[:, 1]
157
+ x = dst_pts[:, 0]
158
+ y = dst_pts[:, 1]
159
+ [x, y, 1] = [u, v, 1] * trans
160
+ Parameters:
161
+ ----------
162
+ @src_pts: Kx2 np.array
163
+ source points, each row is a pair of coordinates (x, y)
164
+ @dst_pts: Kx2 np.array
165
+ destination points, each row is a pair of transformed
166
+ coordinates (x, y)
167
+ @reflective: True or False
168
+ if True:
169
+ use reflective similarity transform
170
+ else:
171
+ use non-reflective similarity transform
172
+ Returns:
173
+ ----------
174
+ @trans: 3x3 np.array
175
+ transform matrix from uv to xy
176
+ trans_inv: 3x3 np.array
177
+ inverse of trans, transform matrix from xy to uv
178
+ """
179
+
180
+ if reflective:
181
+ trans, trans_inv = findSimilarity(src_pts, dst_pts)
182
+ else:
183
+ trans, trans_inv = findNonreflectiveSimilarity(src_pts, dst_pts)
184
+
185
+ return trans, trans_inv
186
+
187
+
188
+ def cvt_tform_mat_for_cv2(trans):
189
+ """
190
+ Function:
191
+ ----------
192
+ Convert Transform Matrix 'trans' into 'cv2_trans' which could be
193
+ directly used by cv2.warpAffine():
194
+ u = src_pts[:, 0]
195
+ v = src_pts[:, 1]
196
+ x = dst_pts[:, 0]
197
+ y = dst_pts[:, 1]
198
+ [x, y].T = cv_trans * [u, v, 1].T
199
+ Parameters:
200
+ ----------
201
+ @trans: 3x3 np.array
202
+ transform matrix from uv to xy
203
+ Returns:
204
+ ----------
205
+ @cv2_trans: 2x3 np.array
206
+ transform matrix from src_pts to dst_pts, could be directly used
207
+ for cv2.warpAffine()
208
+ """
209
+ cv2_trans = trans[:, 0:2].T
210
+
211
+ return cv2_trans
212
+
213
+
214
+ def get_similarity_transform_for_cv2(src_pts, dst_pts, reflective=True):
215
+ """
216
+ Function:
217
+ ----------
218
+ Find Similarity Transform Matrix 'cv2_trans' which could be
219
+ directly used by cv2.warpAffine():
220
+ u = src_pts[:, 0]
221
+ v = src_pts[:, 1]
222
+ x = dst_pts[:, 0]
223
+ y = dst_pts[:, 1]
224
+ [x, y].T = cv_trans * [u, v, 1].T
225
+ Parameters:
226
+ ----------
227
+ @src_pts: Kx2 np.array
228
+ source points, each row is a pair of coordinates (x, y)
229
+ @dst_pts: Kx2 np.array
230
+ destination points, each row is a pair of transformed
231
+ coordinates (x, y)
232
+ reflective: True or False
233
+ if True:
234
+ use reflective similarity transform
235
+ else:
236
+ use non-reflective similarity transform
237
+ Returns:
238
+ ----------
239
+ @cv2_trans: 2x3 np.array
240
+ transform matrix from src_pts to dst_pts, could be directly used
241
+ for cv2.warpAffine()
242
+ """
243
+ trans, trans_inv = get_similarity_transform(src_pts, dst_pts, reflective)
244
+ cv2_trans = cvt_tform_mat_for_cv2(trans)
245
+
246
+ return cv2_trans
247
+
248
+
249
+ if __name__ == '__main__':
250
+ """
251
+ u = [0, 6, -2]
252
+ v = [0, 3, 5]
253
+ x = [-1, 0, 4]
254
+ y = [-1, -10, 4]
255
+ # In Matlab, run:
256
+ #
257
+ # uv = [u'; v'];
258
+ # xy = [x'; y'];
259
+ # tform_sim=cp2tform(uv,xy,'similarity');
260
+ #
261
+ # trans = tform_sim.tdata.T
262
+ # ans =
263
+ # -0.0764 -1.6190 0
264
+ # 1.6190 -0.0764 0
265
+ # -3.2156 0.0290 1.0000
266
+ # trans_inv = tform_sim.tdata.Tinv
267
+ # ans =
268
+ #
269
+ # -0.0291 0.6163 0
270
+ # -0.6163 -0.0291 0
271
+ # -0.0756 1.9826 1.0000
272
+ # xy_m=tformfwd(tform_sim, u,v)
273
+ #
274
+ # xy_m =
275
+ #
276
+ # -3.2156 0.0290
277
+ # 1.1833 -9.9143
278
+ # 5.0323 2.8853
279
+ # uv_m=tforminv(tform_sim, x,y)
280
+ #
281
+ # uv_m =
282
+ #
283
+ # 0.5698 1.3953
284
+ # 6.0872 2.2733
285
+ # -2.6570 4.3314
286
+ """
287
+ u = [0, 6, -2]
288
+ v = [0, 3, 5]
289
+ x = [-1, 0, 4]
290
+ y = [-1, -10, 4]
291
+
292
+ uv = np.array((u, v)).T
293
+ xy = np.array((x, y)).T
294
+
295
+ print("\n--->uv:")
296
+ print(uv)
297
+ print("\n--->xy:")
298
+ print(xy)
299
+
300
+ trans, trans_inv = get_similarity_transform(uv, xy)
301
+
302
+ print("\n--->trans matrix:")
303
+ print(trans)
304
+
305
+ print("\n--->trans_inv matrix:")
306
+ print(trans_inv)
307
+
308
+ print("\n---> apply transform to uv")
309
+ print("\nxy_m = uv_augmented * trans")
310
+ uv_aug = np.hstack((
311
+ uv, np.ones((uv.shape[0], 1))
312
+ ))
313
+ xy_m = np.dot(uv_aug, trans)
314
+ print(xy_m)
315
+
316
+ print("\nxy_m = tformfwd(trans, uv)")
317
+ xy_m = tformfwd(trans, uv)
318
+ print(xy_m)
319
+
320
+ print("\n---> apply inverse transform to xy")
321
+ print("\nuv_m = xy_augmented * trans_inv")
322
+ xy_aug = np.hstack((
323
+ xy, np.ones((xy.shape[0], 1))
324
+ ))
325
+ uv_m = np.dot(xy_aug, trans_inv)
326
+ print(uv_m)
327
+
328
+ print("\nuv_m = tformfwd(trans_inv, xy)")
329
+ uv_m = tformfwd(trans_inv, xy)
330
+ print(uv_m)
331
+
332
+ uv_m = tforminv(trans, xy)
333
+ print("\nuv_m = tforminv(trans, xy)")
334
+ print(uv_m)
client/software/FaceBoxes/utils/misc.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''Some helper functions for PyTorch, including:
2
+ - get_mean_and_std: calculate the mean and std value of dataset.
3
+ - msr_init: net parameter initialization.
4
+ - progress_bar: progress bar mimic xlua.progress.
5
+ '''
6
+ import errno
7
+ import os
8
+ import sys
9
+ import time
10
+ import math
11
+
12
+ import torch.nn as nn
13
+ import torch.nn.init as init
14
+ from torch.autograd import Variable
15
+
16
+ __all__ = ['get_mean_and_std', 'init_params', 'mkdir_p', 'AverageMeter']
17
+
18
+
19
+ def get_mean_and_std(dataset):
20
+ '''Compute the mean and std value of dataset.'''
21
+ dataloader = trainloader = torch.utils.data.DataLoader(
22
+ dataset, batch_size=1, shuffle=True, num_workers=2)
23
+
24
+ mean = torch.zeros(3)
25
+ std = torch.zeros(3)
26
+ print('==> Computing mean and std..')
27
+ for inputs, targets in dataloader:
28
+ for i in range(3):
29
+ mean[i] += inputs[:, i, :, :].mean()
30
+ std[i] += inputs[:, i, :, :].std()
31
+ mean.div_(len(dataset))
32
+ std.div_(len(dataset))
33
+ return mean, std
34
+
35
+
36
+ def init_params(net):
37
+ '''Init layer parameters.'''
38
+ for m in net.modules():
39
+ if isinstance(m, nn.Conv2d):
40
+ init.kaiming_normal(m.weight, mode='fan_out')
41
+ if m.bias:
42
+ init.constant(m.bias, 0)
43
+ elif isinstance(m, nn.BatchNorm2d):
44
+ init.constant(m.weight, 1)
45
+ init.constant(m.bias, 0)
46
+ elif isinstance(m, nn.Linear):
47
+ init.normal(m.weight, std=1e-3)
48
+ if m.bias:
49
+ init.constant(m.bias, 0)
50
+
51
+
52
+ def mkdir_p(path):
53
+ '''make dir if not exist'''
54
+ try:
55
+ os.makedirs(path)
56
+ except OSError as exc: # Python >2.5
57
+ if exc.errno == errno.EEXIST and os.path.isdir(path):
58
+ pass
59
+ else:
60
+ raise
61
+
62
+
63
+ class AverageMeter(object):
64
+ """Computes and stores the average and current value"""
65
+
66
+ def __init__(self):
67
+ self.reset()
68
+
69
+ def reset(self):
70
+ self.val = 0
71
+ self.avg = 0
72
+ self.sum = 0
73
+ self.count = 0
74
+
75
+ def update(self, val, n=1):
76
+ self.val = val
77
+ self.sum += val * n
78
+ self.count += n
79
+ self.avg = self.sum / self.count
client/software/FaceBoxes/utils/nms/.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ *.c
2
+ *.so
client/software/FaceBoxes/utils/nms/__init__.py ADDED
File without changes
client/software/FaceBoxes/utils/nms/cpu_nms.cp38-win_amd64.pyd ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1d69c0f2e32c7c447e6d4a96619e4f262ce12ddc918c463317b6d3dc51b8891e
3
+ size 100864
client/software/FaceBoxes/utils/nms/cpu_nms.pyd ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6af77f6d102a602fea61c5eb6c9bb13bb00d9106ac1a6c4086893ba8ce6aca8d
3
+ size 100864
client/software/FaceBoxes/utils/nms/cpu_nms.pyx ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # Fast R-CNN
3
+ # Copyright (c) 2015 Microsoft
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # Written by Ross Girshick
6
+ # --------------------------------------------------------
7
+
8
+ import numpy as np
9
+ cimport numpy as np
10
+
11
+ cdef inline np.float32_t max(np.float32_t a, np.float32_t b):
12
+ return a if a >= b else b
13
+
14
+ cdef inline np.float32_t min(np.float32_t a, np.float32_t b):
15
+ return a if a <= b else b
16
+
17
+ def cpu_nms(np.ndarray[np.float32_t, ndim=2] dets, np.float thresh):
18
+ cdef np.ndarray[np.float32_t, ndim=1] x1 = dets[:, 0]
19
+ cdef np.ndarray[np.float32_t, ndim=1] y1 = dets[:, 1]
20
+ cdef np.ndarray[np.float32_t, ndim=1] x2 = dets[:, 2]
21
+ cdef np.ndarray[np.float32_t, ndim=1] y2 = dets[:, 3]
22
+ cdef np.ndarray[np.float32_t, ndim=1] scores = dets[:, 4]
23
+
24
+ cdef np.ndarray[np.float32_t, ndim=1] areas = (x2 - x1 + 1) * (y2 - y1 + 1)
25
+ cdef np.ndarray[np.int64_t, ndim=1] order = scores.argsort()[::-1]
26
+
27
+ cdef int ndets = dets.shape[0]
28
+ cdef np.ndarray[np.int64_t, ndim=1] suppressed = \
29
+ np.zeros((ndets), dtype=np.int64)
30
+
31
+ # nominal indices
32
+ cdef int _i, _j
33
+ # sorted indices
34
+ cdef int i, j
35
+ # temp variables for box i's (the box currently under consideration)
36
+ cdef np.float32_t ix1, iy1, ix2, iy2, iarea
37
+ # variables for computing overlap with box j (lower scoring box)
38
+ cdef np.float32_t xx1, yy1, xx2, yy2
39
+ cdef np.float32_t w, h
40
+ cdef np.float32_t inter, ovr
41
+
42
+ keep = []
43
+ for _i in range(ndets):
44
+ i = order[_i]
45
+ if suppressed[i] == 1:
46
+ continue
47
+ keep.append(i)
48
+ ix1 = x1[i]
49
+ iy1 = y1[i]
50
+ ix2 = x2[i]
51
+ iy2 = y2[i]
52
+ iarea = areas[i]
53
+ for _j in range(_i + 1, ndets):
54
+ j = order[_j]
55
+ if suppressed[j] == 1:
56
+ continue
57
+ xx1 = max(ix1, x1[j])
58
+ yy1 = max(iy1, y1[j])
59
+ xx2 = min(ix2, x2[j])
60
+ yy2 = min(iy2, y2[j])
61
+ w = max(0.0, xx2 - xx1 + 1)
62
+ h = max(0.0, yy2 - yy1 + 1)
63
+ inter = w * h
64
+ ovr = inter / (iarea + areas[j] - inter)
65
+ if ovr >= thresh:
66
+ suppressed[j] = 1
67
+
68
+ return keep
69
+
70
+ def cpu_soft_nms(np.ndarray[float, ndim=2] boxes, float sigma=0.5, float Nt=0.3, float threshold=0.001, unsigned int method=0):
71
+ cdef unsigned int N = boxes.shape[0]
72
+ cdef float iw, ih, box_area
73
+ cdef float ua
74
+ cdef int pos = 0
75
+ cdef float maxscore = 0
76
+ cdef int maxpos = 0
77
+ cdef float x1,x2,y1,y2,tx1,tx2,ty1,ty2,ts,area,weight,ov
78
+
79
+ for i in range(N):
80
+ maxscore = boxes[i, 4]
81
+ maxpos = i
82
+
83
+ tx1 = boxes[i,0]
84
+ ty1 = boxes[i,1]
85
+ tx2 = boxes[i,2]
86
+ ty2 = boxes[i,3]
87
+ ts = boxes[i,4]
88
+
89
+ pos = i + 1
90
+ # get max box
91
+ while pos < N:
92
+ if maxscore < boxes[pos, 4]:
93
+ maxscore = boxes[pos, 4]
94
+ maxpos = pos
95
+ pos = pos + 1
96
+
97
+ # add max box as a detection
98
+ boxes[i,0] = boxes[maxpos,0]
99
+ boxes[i,1] = boxes[maxpos,1]
100
+ boxes[i,2] = boxes[maxpos,2]
101
+ boxes[i,3] = boxes[maxpos,3]
102
+ boxes[i,4] = boxes[maxpos,4]
103
+
104
+ # swap ith box with position of max box
105
+ boxes[maxpos,0] = tx1
106
+ boxes[maxpos,1] = ty1
107
+ boxes[maxpos,2] = tx2
108
+ boxes[maxpos,3] = ty2
109
+ boxes[maxpos,4] = ts
110
+
111
+ tx1 = boxes[i,0]
112
+ ty1 = boxes[i,1]
113
+ tx2 = boxes[i,2]
114
+ ty2 = boxes[i,3]
115
+ ts = boxes[i,4]
116
+
117
+ pos = i + 1
118
+ # NMS iterations, note that N changes if detection boxes fall below threshold
119
+ while pos < N:
120
+ x1 = boxes[pos, 0]
121
+ y1 = boxes[pos, 1]
122
+ x2 = boxes[pos, 2]
123
+ y2 = boxes[pos, 3]
124
+ s = boxes[pos, 4]
125
+
126
+ area = (x2 - x1 + 1) * (y2 - y1 + 1)
127
+ iw = (min(tx2, x2) - max(tx1, x1) + 1)
128
+ if iw > 0:
129
+ ih = (min(ty2, y2) - max(ty1, y1) + 1)
130
+ if ih > 0:
131
+ ua = float((tx2 - tx1 + 1) * (ty2 - ty1 + 1) + area - iw * ih)
132
+ ov = iw * ih / ua #iou between max box and detection box
133
+
134
+ if method == 1: # linear
135
+ if ov > Nt:
136
+ weight = 1 - ov
137
+ else:
138
+ weight = 1
139
+ elif method == 2: # gaussian
140
+ weight = np.exp(-(ov * ov)/sigma)
141
+ else: # original NMS
142
+ if ov > Nt:
143
+ weight = 0
144
+ else:
145
+ weight = 1
146
+
147
+ boxes[pos, 4] = weight*boxes[pos, 4]
148
+
149
+ # if box score falls below threshold, discard the box by swapping with last box
150
+ # update N
151
+ if boxes[pos, 4] < threshold:
152
+ boxes[pos,0] = boxes[N-1, 0]
153
+ boxes[pos,1] = boxes[N-1, 1]
154
+ boxes[pos,2] = boxes[N-1, 2]
155
+ boxes[pos,3] = boxes[N-1, 3]
156
+ boxes[pos,4] = boxes[N-1, 4]
157
+ N = N - 1
158
+ pos = pos - 1
159
+
160
+ pos = pos + 1
161
+
162
+ keep = [i for i in range(N)]
163
+ return keep
client/software/FaceBoxes/utils/nms/py_cpu_nms.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # Fast R-CNN
3
+ # Copyright (c) 2015 Microsoft
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # Written by Ross Girshick
6
+ # --------------------------------------------------------
7
+
8
+ import numpy as np
9
+
10
+
11
+ def py_cpu_nms(dets, thresh):
12
+ """Pure Python NMS baseline."""
13
+ x1 = dets[:, 0]
14
+ y1 = dets[:, 1]
15
+ x2 = dets[:, 2]
16
+ y2 = dets[:, 3]
17
+ scores = dets[:, 4]
18
+
19
+ areas = (x2 - x1 + 1) * (y2 - y1 + 1)
20
+ order = scores.argsort()[::-1]
21
+
22
+ keep = []
23
+ while order.size > 0:
24
+ i = order[0]
25
+ keep.append(i)
26
+ xx1 = np.maximum(x1[i], x1[order[1:]])
27
+ yy1 = np.maximum(y1[i], y1[order[1:]])
28
+ xx2 = np.minimum(x2[i], x2[order[1:]])
29
+ yy2 = np.minimum(y2[i], y2[order[1:]])
30
+
31
+ w = np.maximum(0.0, xx2 - xx1 + 1)
32
+ h = np.maximum(0.0, yy2 - yy1 + 1)
33
+ inter = w * h
34
+ ovr = inter / (areas[i] + areas[order[1:]] - inter)
35
+
36
+ inds = np.where(ovr <= thresh)[0]
37
+ order = order[inds + 1]
38
+
39
+ return keep
client/software/FaceBoxes/utils/nms/pyx2pyd.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from Cython.Distutils import build_ext
2
+ from Cython.Build import cythonize
3
+ from distutils.extension import Extension
4
+ from distutils.core import setup
5
+ import sys
6
+ import numpy as np
7
+
8
+ A = sys.path.insert(0, "..")
9
+
10
+ setup(
11
+ ext_modules=cythonize(
12
+ 'C:\\Users\\denti\\Desktop\\cat-ui\\cat-process(sim)\\FaceBoxes\\utils\\nms\\cpu_nms.pyx'),
13
+ include_dirs=[np.get_include()]
14
+ )
client/software/FaceBoxes/utils/nms/ζ–°ε»Ί Bitmap image.bmp ADDED
client/software/FaceBoxes/utils/nms_wrapper.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding: utf-8
2
+
3
+ # --------------------------------------------------------
4
+ # Fast R-CNN
5
+ # Copyright (c) 2015 Microsoft
6
+ # Licensed under The MIT License [see LICENSE for details]
7
+ # Written by Ross Girshick
8
+ # --------------------------------------------------------
9
+
10
+ from .nms.cpu_nms import cpu_nms, cpu_soft_nms
11
+
12
+
13
+ def nms(dets, thresh):
14
+ """Dispatch to either CPU or GPU NMS implementations."""
15
+
16
+ if dets.shape[0] == 0:
17
+ return []
18
+ return cpu_nms(dets, thresh)
19
+ # return gpu_nms(dets, thresh)
client/software/FaceBoxes/utils/osutils.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ import os
4
+ import errno
5
+
6
+
7
+ def mkdir_p(dir_path):
8
+ try:
9
+ os.makedirs(dir_path)
10
+ except OSError as e:
11
+ if e.errno != errno.EEXIST:
12
+ raise
13
+
14
+
15
+ def isfile(fname):
16
+ return os.path.isfile(fname)
17
+
18
+
19
+ def isdir(dirname):
20
+ return os.path.isdir(dirname)
21
+
22
+
23
+ def join(path, *paths):
24
+ return os.path.join(path, *paths)
client/software/FaceBoxes/utils/prior_box.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding: utf-8
2
+
3
+ from .config import cfg
4
+
5
+ import torch
6
+ from itertools import product as product
7
+ from math import ceil
8
+
9
+
10
+ class PriorBox(object):
11
+ def __init__(self, image_size=None):
12
+ super(PriorBox, self).__init__()
13
+ # self.aspect_ratios = cfg['aspect_ratios']
14
+ self.min_sizes = cfg['min_sizes']
15
+ self.steps = cfg['steps']
16
+ self.clip = cfg['clip']
17
+ self.image_size = image_size
18
+ self.feature_maps = [
19
+ [ceil(self.image_size[0] / step), ceil(self.image_size[1] / step)] for step in self.steps]
20
+
21
+ def forward(self):
22
+ anchors = []
23
+ for k, f in enumerate(self.feature_maps):
24
+ min_sizes = self.min_sizes[k]
25
+ for i, j in product(range(f[0]), range(f[1])):
26
+ for min_size in min_sizes:
27
+ s_kx = min_size / self.image_size[1]
28
+ s_ky = min_size / self.image_size[0]
29
+ if min_size == 32:
30
+ dense_cx = [x * self.steps[k] / self.image_size[1] for x in
31
+ [j + 0, j + 0.25, j + 0.5, j + 0.75]]
32
+ dense_cy = [y * self.steps[k] / self.image_size[0] for y in
33
+ [i + 0, i + 0.25, i + 0.5, i + 0.75]]
34
+ for cy, cx in product(dense_cy, dense_cx):
35
+ anchors += [cx, cy, s_kx, s_ky]
36
+ elif min_size == 64:
37
+ dense_cx = [x * self.steps[k] / self.image_size[1]
38
+ for x in [j + 0, j + 0.5]]
39
+ dense_cy = [y * self.steps[k] / self.image_size[0]
40
+ for y in [i + 0, i + 0.5]]
41
+ for cy, cx in product(dense_cy, dense_cx):
42
+ anchors += [cx, cy, s_kx, s_ky]
43
+ else:
44
+ cx = (j + 0.5) * self.steps[k] / self.image_size[1]
45
+ cy = (i + 0.5) * self.steps[k] / self.image_size[0]
46
+ anchors += [cx, cy, s_kx, s_ky]
47
+ # back to torch land
48
+ output = torch.Tensor(anchors).view(-1, 4)
49
+ if self.clip:
50
+ output.clamp_(max=1, min=0)
51
+ return output
client/software/FaceBoxes/utils/progress/.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ *.pyc
2
+ *.egg-info
3
+ build/
4
+ dist/
client/software/FaceBoxes/utils/progress/LICENSE ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2012 Giorgos Verigakis <verigak@gmail.com>
2
+ #
3
+ # Permission to use, copy, modify, and distribute this software for any
4
+ # purpose with or without fee is hereby granted, provided that the above
5
+ # copyright notice and this permission notice appear in all copies.
6
+ #
7
+ # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8
+ # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9
+ # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
10
+ # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11
+ # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
12
+ # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
13
+ # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
client/software/FaceBoxes/utils/progress/MANIFEST.in ADDED
@@ -0,0 +1 @@
 
 
1
+ include README.rst LICENSE
client/software/FaceBoxes/utils/progress/README.rst ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Easy progress reporting for Python
2
+ ==================================
3
+
4
+ |pypi|
5
+
6
+ |demo|
7
+
8
+ .. |pypi| image:: https://img.shields.io/pypi/v/progress.svg
9
+ .. |demo| image:: https://raw.github.com/verigak/progress/master/demo.gif
10
+ :alt: Demo
11
+
12
+ Bars
13
+ ----
14
+
15
+ There are 7 progress bars to choose from:
16
+
17
+ - ``Bar``
18
+ - ``ChargingBar``
19
+ - ``FillingSquaresBar``
20
+ - ``FillingCirclesBar``
21
+ - ``IncrementalBar``
22
+ - ``PixelBar``
23
+ - ``ShadyBar``
24
+
25
+ To use them, just call ``next`` to advance and ``finish`` to finish:
26
+
27
+ .. code-block:: python
28
+
29
+ from progress.bar import Bar
30
+
31
+ bar = Bar('Processing', max=20)
32
+ for i in range(20):
33
+ # Do some work
34
+ bar.next()
35
+ bar.finish()
36
+
37
+ The result will be a bar like the following: ::
38
+
39
+ Processing |############# | 42/100
40
+
41
+ To simplify the common case where the work is done in an iterator, you can
42
+ use the ``iter`` method:
43
+
44
+ .. code-block:: python
45
+
46
+ for i in Bar('Processing').iter(it):
47
+ # Do some work
48
+
49
+ Progress bars are very customizable, you can change their width, their fill
50
+ character, their suffix and more:
51
+
52
+ .. code-block:: python
53
+
54
+ bar = Bar('Loading', fill='@', suffix='%(percent)d%%')
55
+
56
+ This will produce a bar like the following: ::
57
+
58
+ Loading |@@@@@@@@@@@@@ | 42%
59
+
60
+ You can use a number of template arguments in ``message`` and ``suffix``:
61
+
62
+ ========== ================================
63
+ Name Value
64
+ ========== ================================
65
+ index current value
66
+ max maximum value
67
+ remaining max - index
68
+ progress index / max
69
+ percent progress * 100
70
+ avg simple moving average time per item (in seconds)
71
+ elapsed elapsed time in seconds
72
+ elapsed_td elapsed as a timedelta (useful for printing as a string)
73
+ eta avg * remaining
74
+ eta_td eta as a timedelta (useful for printing as a string)
75
+ ========== ================================
76
+
77
+ Instead of passing all configuration options on instatiation, you can create
78
+ your custom subclass:
79
+
80
+ .. code-block:: python
81
+
82
+ class FancyBar(Bar):
83
+ message = 'Loading'
84
+ fill = '*'
85
+ suffix = '%(percent).1f%% - %(eta)ds'
86
+
87
+ You can also override any of the arguments or create your own:
88
+
89
+ .. code-block:: python
90
+
91
+ class SlowBar(Bar):
92
+ suffix = '%(remaining_hours)d hours remaining'
93
+ @property
94
+ def remaining_hours(self):
95
+ return self.eta // 3600
96
+
97
+
98
+ Spinners
99
+ ========
100
+
101
+ For actions with an unknown number of steps you can use a spinner:
102
+
103
+ .. code-block:: python
104
+
105
+ from progress.spinner import Spinner
106
+
107
+ spinner = Spinner('Loading ')
108
+ while state != 'FINISHED':
109
+ # Do some work
110
+ spinner.next()
111
+
112
+ There are 5 predefined spinners:
113
+
114
+ - ``Spinner``
115
+ - ``PieSpinner``
116
+ - ``MoonSpinner``
117
+ - ``LineSpinner``
118
+ - ``PixelSpinner``
119
+
120
+
121
+ Other
122
+ =====
123
+
124
+ There are a number of other classes available too, please check the source or
125
+ subclass one of them to create your own.
126
+
127
+
128
+ License
129
+ =======
130
+
131
+ progress is licensed under ISC
client/software/FaceBoxes/utils/progress/demo.gif ADDED

Git LFS Details

  • SHA256: e7ae3ca9c3d23d155e440c0f0971a32a1c6825b656de773d993b92152c4f6fc2
  • Pointer size: 131 Bytes
  • Size of remote file: 924 kB
client/software/FaceBoxes/utils/progress/progress/__init__.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2012 Giorgos Verigakis <verigak@gmail.com>
2
+ #
3
+ # Permission to use, copy, modify, and distribute this software for any
4
+ # purpose with or without fee is hereby granted, provided that the above
5
+ # copyright notice and this permission notice appear in all copies.
6
+ #
7
+ # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8
+ # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9
+ # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
10
+ # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11
+ # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
12
+ # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
13
+ # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14
+
15
+ from __future__ import division
16
+
17
+ from collections import deque
18
+ from datetime import timedelta
19
+ from math import ceil
20
+ from sys import stderr
21
+ from time import time
22
+
23
+
24
+ __version__ = '1.3'
25
+
26
+
27
+ class Infinite(object):
28
+ file = stderr
29
+ sma_window = 10 # Simple Moving Average window
30
+
31
+ def __init__(self, *args, **kwargs):
32
+ self.index = 0
33
+ self.start_ts = time()
34
+ self.avg = 0
35
+ self._ts = self.start_ts
36
+ self._xput = deque(maxlen=self.sma_window)
37
+ for key, val in kwargs.items():
38
+ setattr(self, key, val)
39
+
40
+ def __getitem__(self, key):
41
+ if key.startswith('_'):
42
+ return None
43
+ return getattr(self, key, None)
44
+
45
+ @property
46
+ def elapsed(self):
47
+ return int(time() - self.start_ts)
48
+
49
+ @property
50
+ def elapsed_td(self):
51
+ return timedelta(seconds=self.elapsed)
52
+
53
+ def update_avg(self, n, dt):
54
+ if n > 0:
55
+ self._xput.append(dt / n)
56
+ self.avg = sum(self._xput) / len(self._xput)
57
+
58
+ def update(self):
59
+ pass
60
+
61
+ def start(self):
62
+ pass
63
+
64
+ def finish(self):
65
+ pass
66
+
67
+ def next(self, n=1):
68
+ now = time()
69
+ dt = now - self._ts
70
+ self.update_avg(n, dt)
71
+ self._ts = now
72
+ self.index = self.index + n
73
+ self.update()
74
+
75
+ def iter(self, it):
76
+ try:
77
+ for x in it:
78
+ yield x
79
+ self.next()
80
+ finally:
81
+ self.finish()
82
+
83
+
84
+ class Progress(Infinite):
85
+ def __init__(self, *args, **kwargs):
86
+ super(Progress, self).__init__(*args, **kwargs)
87
+ self.max = kwargs.get('max', 100)
88
+
89
+ @property
90
+ def eta(self):
91
+ return int(ceil(self.avg * self.remaining))
92
+
93
+ @property
94
+ def eta_td(self):
95
+ return timedelta(seconds=self.eta)
96
+
97
+ @property
98
+ def percent(self):
99
+ return self.progress * 100
100
+
101
+ @property
102
+ def progress(self):
103
+ return min(1, self.index / self.max)
104
+
105
+ @property
106
+ def remaining(self):
107
+ return max(self.max - self.index, 0)
108
+
109
+ def start(self):
110
+ self.update()
111
+
112
+ def goto(self, index):
113
+ incr = index - self.index
114
+ self.next(incr)
115
+
116
+ def iter(self, it):
117
+ try:
118
+ self.max = len(it)
119
+ except TypeError:
120
+ pass
121
+
122
+ try:
123
+ for x in it:
124
+ yield x
125
+ self.next()
126
+ finally:
127
+ self.finish()
client/software/FaceBoxes/utils/progress/progress/bar.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # Copyright (c) 2012 Giorgos Verigakis <verigak@gmail.com>
4
+ #
5
+ # Permission to use, copy, modify, and distribute this software for any
6
+ # purpose with or without fee is hereby granted, provided that the above
7
+ # copyright notice and this permission notice appear in all copies.
8
+ #
9
+ # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
+ # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
+ # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
+ # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
+ # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
+ # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
+ # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16
+
17
+ from __future__ import unicode_literals
18
+ from . import Progress
19
+ from .helpers import WritelnMixin
20
+
21
+
22
+ class Bar(WritelnMixin, Progress):
23
+ width = 32
24
+ message = ''
25
+ suffix = '%(index)d/%(max)d'
26
+ bar_prefix = ' |'
27
+ bar_suffix = '| '
28
+ empty_fill = ' '
29
+ fill = '#'
30
+ hide_cursor = True
31
+
32
+ def update(self):
33
+ filled_length = int(self.width * self.progress)
34
+ empty_length = self.width - filled_length
35
+
36
+ message = self.message % self
37
+ bar = self.fill * filled_length
38
+ empty = self.empty_fill * empty_length
39
+ suffix = self.suffix % self
40
+ line = ''.join([message, self.bar_prefix, bar, empty, self.bar_suffix,
41
+ suffix])
42
+ self.writeln(line)
43
+
44
+
45
+ class ChargingBar(Bar):
46
+ suffix = '%(percent)d%%'
47
+ bar_prefix = ' '
48
+ bar_suffix = ' '
49
+ empty_fill = 'βˆ™'
50
+ fill = 'β–ˆ'
51
+
52
+
53
+ class FillingSquaresBar(ChargingBar):
54
+ empty_fill = 'β–’'
55
+ fill = 'β–£'
56
+
57
+
58
+ class FillingCirclesBar(ChargingBar):
59
+ empty_fill = 'β—―'
60
+ fill = 'β—‰'
61
+
62
+
63
+ class IncrementalBar(Bar):
64
+ phases = (' ', '▏', 'β–Ž', '▍', 'β–Œ', 'β–‹', 'β–Š', 'β–‰', 'β–ˆ')
65
+
66
+ def update(self):
67
+ nphases = len(self.phases)
68
+ filled_len = self.width * self.progress
69
+ nfull = int(filled_len) # Number of full chars
70
+ phase = int((filled_len - nfull) * nphases) # Phase of last char
71
+ nempty = self.width - nfull # Number of empty chars
72
+
73
+ message = self.message % self
74
+ bar = self.phases[-1] * nfull
75
+ current = self.phases[phase] if phase > 0 else ''
76
+ empty = self.empty_fill * max(0, nempty - len(current))
77
+ suffix = self.suffix % self
78
+ line = ''.join([message, self.bar_prefix, bar, current, empty,
79
+ self.bar_suffix, suffix])
80
+ self.writeln(line)
81
+
82
+
83
+ class PixelBar(IncrementalBar):
84
+ phases = ('β‘€', 'β‘„', '⑆', '⑇', '⣇', 'β£§', 'β£·', 'β£Ώ')
85
+
86
+
87
+ class ShadyBar(IncrementalBar):
88
+ phases = (' ', 'β–‘', 'β–’', 'β–“', 'β–ˆ')
client/software/FaceBoxes/utils/progress/progress/counter.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # Copyright (c) 2012 Giorgos Verigakis <verigak@gmail.com>
4
+ #
5
+ # Permission to use, copy, modify, and distribute this software for any
6
+ # purpose with or without fee is hereby granted, provided that the above
7
+ # copyright notice and this permission notice appear in all copies.
8
+ #
9
+ # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
+ # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
+ # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
+ # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
+ # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
+ # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
+ # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16
+
17
+ from __future__ import unicode_literals
18
+ from . import Infinite, Progress
19
+ from .helpers import WriteMixin
20
+
21
+
22
+ class Counter(WriteMixin, Infinite):
23
+ message = ''
24
+ hide_cursor = True
25
+
26
+ def update(self):
27
+ self.write(str(self.index))
28
+
29
+
30
+ class Countdown(WriteMixin, Progress):
31
+ hide_cursor = True
32
+
33
+ def update(self):
34
+ self.write(str(self.remaining))
35
+
36
+
37
+ class Stack(WriteMixin, Progress):
38
+ phases = (' ', '▁', 'β–‚', 'β–ƒ', 'β–„', 'β–…', 'β–†', 'β–‡', 'β–ˆ')
39
+ hide_cursor = True
40
+
41
+ def update(self):
42
+ nphases = len(self.phases)
43
+ i = min(nphases - 1, int(self.progress * nphases))
44
+ self.write(self.phases[i])
45
+
46
+
47
+ class Pie(Stack):
48
+ phases = ('β—‹', 'β—”', 'β—‘', 'β—•', '●')