Upload 16 files
Browse files- .gitattributes +2 -34
- .gitignore +9 -0
- LICENSE +674 -0
- README.md +4 -4
- app.py +166 -0
- bbox.py +92 -0
- eval.py +74 -0
- evaluator.py +46 -0
- infer.py +89 -0
- infer_stream.py +117 -0
- logger.py +35 -0
- model.py +218 -0
- packages.txt +1 -0
- requirements.txt +11 -0
- test_streamlit.py +170 -0
- voc_eval.py +198 -0
.gitattributes
CHANGED
@@ -1,35 +1,3 @@
|
|
1 |
-
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
-
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
-
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
-
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
5 |
-
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
6 |
-
*.ftz filter=lfs diff=lfs merge=lfs -text
|
7 |
-
*.gz filter=lfs diff=lfs merge=lfs -text
|
8 |
-
*.h5 filter=lfs diff=lfs merge=lfs -text
|
9 |
-
*.joblib filter=lfs diff=lfs merge=lfs -text
|
10 |
-
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
11 |
-
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
12 |
-
*.model filter=lfs diff=lfs merge=lfs -text
|
13 |
-
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
14 |
-
*.npy filter=lfs diff=lfs merge=lfs -text
|
15 |
-
*.npz filter=lfs diff=lfs merge=lfs -text
|
16 |
-
*.onnx filter=lfs diff=lfs merge=lfs -text
|
17 |
-
*.ot filter=lfs diff=lfs merge=lfs -text
|
18 |
-
*.parquet filter=lfs diff=lfs merge=lfs -text
|
19 |
-
*.pb filter=lfs diff=lfs merge=lfs -text
|
20 |
-
*.pickle filter=lfs diff=lfs merge=lfs -text
|
21 |
-
*.pkl filter=lfs diff=lfs merge=lfs -text
|
22 |
-
*.pt filter=lfs diff=lfs merge=lfs -text
|
23 |
*.pth filter=lfs diff=lfs merge=lfs -text
|
24 |
-
*.
|
25 |
-
|
26 |
-
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
27 |
-
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
28 |
-
*.tar filter=lfs diff=lfs merge=lfs -text
|
29 |
-
*.tflite filter=lfs diff=lfs merge=lfs -text
|
30 |
-
*.tgz filter=lfs diff=lfs merge=lfs -text
|
31 |
-
*.wasm filter=lfs diff=lfs merge=lfs -text
|
32 |
-
*.xz 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
*.pth filter=lfs diff=lfs merge=lfs -text
|
2 |
+
*.caffemodel filter=lfs diff=lfs merge=lfs -text
|
3 |
+
models/*.caffemodel filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
.gitignore
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
.idea/
|
2 |
+
__pycache__/
|
3 |
+
|
4 |
+
build
|
5 |
+
caches
|
6 |
+
support.egg-info
|
7 |
+
pycocotools
|
8 |
+
|
9 |
+
*.so
|
LICENSE
ADDED
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
GNU GENERAL PUBLIC LICENSE
|
2 |
+
Version 3, 29 June 2007
|
3 |
+
|
4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
6 |
+
of this license document, but changing it is not allowed.
|
7 |
+
|
8 |
+
Preamble
|
9 |
+
|
10 |
+
The GNU General Public License is a free, copyleft license for
|
11 |
+
software and other kinds of works.
|
12 |
+
|
13 |
+
The licenses for most software and other practical works are designed
|
14 |
+
to take away your freedom to share and change the works. By contrast,
|
15 |
+
the GNU General Public License is intended to guarantee your freedom to
|
16 |
+
share and change all versions of a program--to make sure it remains free
|
17 |
+
software for all its users. We, the Free Software Foundation, use the
|
18 |
+
GNU General Public License for most of our software; it applies also to
|
19 |
+
any other work released this way by its authors. You can apply it to
|
20 |
+
your programs, too.
|
21 |
+
|
22 |
+
When we speak of free software, we are referring to freedom, not
|
23 |
+
price. Our General Public Licenses are designed to make sure that you
|
24 |
+
have the freedom to distribute copies of free software (and charge for
|
25 |
+
them if you wish), that you receive source code or can get it if you
|
26 |
+
want it, that you can change the software or use pieces of it in new
|
27 |
+
free programs, and that you know you can do these things.
|
28 |
+
|
29 |
+
To protect your rights, we need to prevent others from denying you
|
30 |
+
these rights or asking you to surrender the rights. Therefore, you have
|
31 |
+
certain responsibilities if you distribute copies of the software, or if
|
32 |
+
you modify it: responsibilities to respect the freedom of others.
|
33 |
+
|
34 |
+
For example, if you distribute copies of such a program, whether
|
35 |
+
gratis or for a fee, you must pass on to the recipients the same
|
36 |
+
freedoms that you received. You must make sure that they, too, receive
|
37 |
+
or can get the source code. And you must show them these terms so they
|
38 |
+
know their rights.
|
39 |
+
|
40 |
+
Developers that use the GNU GPL protect your rights with two steps:
|
41 |
+
(1) assert copyright on the software, and (2) offer you this License
|
42 |
+
giving you legal permission to copy, distribute and/or modify it.
|
43 |
+
|
44 |
+
For the developers' and authors' protection, the GPL clearly explains
|
45 |
+
that there is no warranty for this free software. For both users' and
|
46 |
+
authors' sake, the GPL requires that modified versions be marked as
|
47 |
+
changed, so that their problems will not be attributed erroneously to
|
48 |
+
authors of previous versions.
|
49 |
+
|
50 |
+
Some devices are designed to deny users access to install or run
|
51 |
+
modified versions of the software inside them, although the manufacturer
|
52 |
+
can do so. This is fundamentally incompatible with the aim of
|
53 |
+
protecting users' freedom to change the software. The systematic
|
54 |
+
pattern of such abuse occurs in the area of products for individuals to
|
55 |
+
use, which is precisely where it is most unacceptable. Therefore, we
|
56 |
+
have designed this version of the GPL to prohibit the practice for those
|
57 |
+
products. If such problems arise substantially in other domains, we
|
58 |
+
stand ready to extend this provision to those domains in future versions
|
59 |
+
of the GPL, as needed to protect the freedom of users.
|
60 |
+
|
61 |
+
Finally, every program is threatened constantly by software patents.
|
62 |
+
States should not allow patents to restrict development and use of
|
63 |
+
software on general-purpose computers, but in those that do, we wish to
|
64 |
+
avoid the special danger that patents applied to a free program could
|
65 |
+
make it effectively proprietary. To prevent this, the GPL assures that
|
66 |
+
patents cannot be used to render the program non-free.
|
67 |
+
|
68 |
+
The precise terms and conditions for copying, distribution and
|
69 |
+
modification follow.
|
70 |
+
|
71 |
+
TERMS AND CONDITIONS
|
72 |
+
|
73 |
+
0. Definitions.
|
74 |
+
|
75 |
+
"This License" refers to version 3 of the GNU General Public License.
|
76 |
+
|
77 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
78 |
+
works, such as semiconductor masks.
|
79 |
+
|
80 |
+
"The Program" refers to any copyrightable work licensed under this
|
81 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
82 |
+
"recipients" may be individuals or organizations.
|
83 |
+
|
84 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
85 |
+
in a fashion requiring copyright permission, other than the making of an
|
86 |
+
exact copy. The resulting work is called a "modified version" of the
|
87 |
+
earlier work or a work "based on" the earlier work.
|
88 |
+
|
89 |
+
A "covered work" means either the unmodified Program or a work based
|
90 |
+
on the Program.
|
91 |
+
|
92 |
+
To "propagate" a work means to do anything with it that, without
|
93 |
+
permission, would make you directly or secondarily liable for
|
94 |
+
infringement under applicable copyright law, except executing it on a
|
95 |
+
computer or modifying a private copy. Propagation includes copying,
|
96 |
+
distribution (with or without modification), making available to the
|
97 |
+
public, and in some countries other activities as well.
|
98 |
+
|
99 |
+
To "convey" a work means any kind of propagation that enables other
|
100 |
+
parties to make or receive copies. Mere interaction with a user through
|
101 |
+
a computer network, with no transfer of a copy, is not conveying.
|
102 |
+
|
103 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
104 |
+
to the extent that it includes a convenient and prominently visible
|
105 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
106 |
+
tells the user that there is no warranty for the work (except to the
|
107 |
+
extent that warranties are provided), that licensees may convey the
|
108 |
+
work under this License, and how to view a copy of this License. If
|
109 |
+
the interface presents a list of user commands or options, such as a
|
110 |
+
menu, a prominent item in the list meets this criterion.
|
111 |
+
|
112 |
+
1. Source Code.
|
113 |
+
|
114 |
+
The "source code" for a work means the preferred form of the work
|
115 |
+
for making modifications to it. "Object code" means any non-source
|
116 |
+
form of a work.
|
117 |
+
|
118 |
+
A "Standard Interface" means an interface that either is an official
|
119 |
+
standard defined by a recognized standards body, or, in the case of
|
120 |
+
interfaces specified for a particular programming language, one that
|
121 |
+
is widely used among developers working in that language.
|
122 |
+
|
123 |
+
The "System Libraries" of an executable work include anything, other
|
124 |
+
than the work as a whole, that (a) is included in the normal form of
|
125 |
+
packaging a Major Component, but which is not part of that Major
|
126 |
+
Component, and (b) serves only to enable use of the work with that
|
127 |
+
Major Component, or to implement a Standard Interface for which an
|
128 |
+
implementation is available to the public in source code form. A
|
129 |
+
"Major Component", in this context, means a major essential component
|
130 |
+
(kernel, window system, and so on) of the specific operating system
|
131 |
+
(if any) on which the executable work runs, or a compiler used to
|
132 |
+
produce the work, or an object code interpreter used to run it.
|
133 |
+
|
134 |
+
The "Corresponding Source" for a work in object code form means all
|
135 |
+
the source code needed to generate, install, and (for an executable
|
136 |
+
work) run the object code and to modify the work, including scripts to
|
137 |
+
control those activities. However, it does not include the work's
|
138 |
+
System Libraries, or general-purpose tools or generally available free
|
139 |
+
programs which are used unmodified in performing those activities but
|
140 |
+
which are not part of the work. For example, Corresponding Source
|
141 |
+
includes interface definition files associated with source files for
|
142 |
+
the work, and the source code for shared libraries and dynamically
|
143 |
+
linked subprograms that the work is specifically designed to require,
|
144 |
+
such as by intimate data communication or control flow between those
|
145 |
+
subprograms and other parts of the work.
|
146 |
+
|
147 |
+
The Corresponding Source need not include anything that users
|
148 |
+
can regenerate automatically from other parts of the Corresponding
|
149 |
+
Source.
|
150 |
+
|
151 |
+
The Corresponding Source for a work in source code form is that
|
152 |
+
same work.
|
153 |
+
|
154 |
+
2. Basic Permissions.
|
155 |
+
|
156 |
+
All rights granted under this License are granted for the term of
|
157 |
+
copyright on the Program, and are irrevocable provided the stated
|
158 |
+
conditions are met. This License explicitly affirms your unlimited
|
159 |
+
permission to run the unmodified Program. The output from running a
|
160 |
+
covered work is covered by this License only if the output, given its
|
161 |
+
content, constitutes a covered work. This License acknowledges your
|
162 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
163 |
+
|
164 |
+
You may make, run and propagate covered works that you do not
|
165 |
+
convey, without conditions so long as your license otherwise remains
|
166 |
+
in force. You may convey covered works to others for the sole purpose
|
167 |
+
of having them make modifications exclusively for you, or provide you
|
168 |
+
with facilities for running those works, provided that you comply with
|
169 |
+
the terms of this License in conveying all material for which you do
|
170 |
+
not control copyright. Those thus making or running the covered works
|
171 |
+
for you must do so exclusively on your behalf, under your direction
|
172 |
+
and control, on terms that prohibit them from making any copies of
|
173 |
+
your copyrighted material outside their relationship with you.
|
174 |
+
|
175 |
+
Conveying under any other circumstances is permitted solely under
|
176 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
177 |
+
makes it unnecessary.
|
178 |
+
|
179 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
180 |
+
|
181 |
+
No covered work shall be deemed part of an effective technological
|
182 |
+
measure under any applicable law fulfilling obligations under article
|
183 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
184 |
+
similar laws prohibiting or restricting circumvention of such
|
185 |
+
measures.
|
186 |
+
|
187 |
+
When you convey a covered work, you waive any legal power to forbid
|
188 |
+
circumvention of technological measures to the extent such circumvention
|
189 |
+
is effected by exercising rights under this License with respect to
|
190 |
+
the covered work, and you disclaim any intention to limit operation or
|
191 |
+
modification of the work as a means of enforcing, against the work's
|
192 |
+
users, your or third parties' legal rights to forbid circumvention of
|
193 |
+
technological measures.
|
194 |
+
|
195 |
+
4. Conveying Verbatim Copies.
|
196 |
+
|
197 |
+
You may convey verbatim copies of the Program's source code as you
|
198 |
+
receive it, in any medium, provided that you conspicuously and
|
199 |
+
appropriately publish on each copy an appropriate copyright notice;
|
200 |
+
keep intact all notices stating that this License and any
|
201 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
202 |
+
keep intact all notices of the absence of any warranty; and give all
|
203 |
+
recipients a copy of this License along with the Program.
|
204 |
+
|
205 |
+
You may charge any price or no price for each copy that you convey,
|
206 |
+
and you may offer support or warranty protection for a fee.
|
207 |
+
|
208 |
+
5. Conveying Modified Source Versions.
|
209 |
+
|
210 |
+
You may convey a work based on the Program, or the modifications to
|
211 |
+
produce it from the Program, in the form of source code under the
|
212 |
+
terms of section 4, provided that you also meet all of these conditions:
|
213 |
+
|
214 |
+
a) The work must carry prominent notices stating that you modified
|
215 |
+
it, and giving a relevant date.
|
216 |
+
|
217 |
+
b) The work must carry prominent notices stating that it is
|
218 |
+
released under this License and any conditions added under section
|
219 |
+
7. This requirement modifies the requirement in section 4 to
|
220 |
+
"keep intact all notices".
|
221 |
+
|
222 |
+
c) You must license the entire work, as a whole, under this
|
223 |
+
License to anyone who comes into possession of a copy. This
|
224 |
+
License will therefore apply, along with any applicable section 7
|
225 |
+
additional terms, to the whole of the work, and all its parts,
|
226 |
+
regardless of how they are packaged. This License gives no
|
227 |
+
permission to license the work in any other way, but it does not
|
228 |
+
invalidate such permission if you have separately received it.
|
229 |
+
|
230 |
+
d) If the work has interactive user interfaces, each must display
|
231 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
232 |
+
interfaces that do not display Appropriate Legal Notices, your
|
233 |
+
work need not make them do so.
|
234 |
+
|
235 |
+
A compilation of a covered work with other separate and independent
|
236 |
+
works, which are not by their nature extensions of the covered work,
|
237 |
+
and which are not combined with it such as to form a larger program,
|
238 |
+
in or on a volume of a storage or distribution medium, is called an
|
239 |
+
"aggregate" if the compilation and its resulting copyright are not
|
240 |
+
used to limit the access or legal rights of the compilation's users
|
241 |
+
beyond what the individual works permit. Inclusion of a covered work
|
242 |
+
in an aggregate does not cause this License to apply to the other
|
243 |
+
parts of the aggregate.
|
244 |
+
|
245 |
+
6. Conveying Non-Source Forms.
|
246 |
+
|
247 |
+
You may convey a covered work in object code form under the terms
|
248 |
+
of sections 4 and 5, provided that you also convey the
|
249 |
+
machine-readable Corresponding Source under the terms of this License,
|
250 |
+
in one of these ways:
|
251 |
+
|
252 |
+
a) Convey the object code in, or embodied in, a physical product
|
253 |
+
(including a physical distribution medium), accompanied by the
|
254 |
+
Corresponding Source fixed on a durable physical medium
|
255 |
+
customarily used for software interchange.
|
256 |
+
|
257 |
+
b) Convey the object code in, or embodied in, a physical product
|
258 |
+
(including a physical distribution medium), accompanied by a
|
259 |
+
written offer, valid for at least three years and valid for as
|
260 |
+
long as you offer spare parts or customer support for that product
|
261 |
+
model, to give anyone who possesses the object code either (1) a
|
262 |
+
copy of the Corresponding Source for all the software in the
|
263 |
+
product that is covered by this License, on a durable physical
|
264 |
+
medium customarily used for software interchange, for a price no
|
265 |
+
more than your reasonable cost of physically performing this
|
266 |
+
conveying of source, or (2) access to copy the
|
267 |
+
Corresponding Source from a network server at no charge.
|
268 |
+
|
269 |
+
c) Convey individual copies of the object code with a copy of the
|
270 |
+
written offer to provide the Corresponding Source. This
|
271 |
+
alternative is allowed only occasionally and noncommercially, and
|
272 |
+
only if you received the object code with such an offer, in accord
|
273 |
+
with subsection 6b.
|
274 |
+
|
275 |
+
d) Convey the object code by offering access from a designated
|
276 |
+
place (gratis or for a charge), and offer equivalent access to the
|
277 |
+
Corresponding Source in the same way through the same place at no
|
278 |
+
further charge. You need not require recipients to copy the
|
279 |
+
Corresponding Source along with the object code. If the place to
|
280 |
+
copy the object code is a network server, the Corresponding Source
|
281 |
+
may be on a different server (operated by you or a third party)
|
282 |
+
that supports equivalent copying facilities, provided you maintain
|
283 |
+
clear directions next to the object code saying where to find the
|
284 |
+
Corresponding Source. Regardless of what server hosts the
|
285 |
+
Corresponding Source, you remain obligated to ensure that it is
|
286 |
+
available for as long as needed to satisfy these requirements.
|
287 |
+
|
288 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
289 |
+
you inform other peers where the object code and Corresponding
|
290 |
+
Source of the work are being offered to the general public at no
|
291 |
+
charge under subsection 6d.
|
292 |
+
|
293 |
+
A separable portion of the object code, whose source code is excluded
|
294 |
+
from the Corresponding Source as a System Library, need not be
|
295 |
+
included in conveying the object code work.
|
296 |
+
|
297 |
+
A "User Product" is either (1) a "consumer product", which means any
|
298 |
+
tangible personal property which is normally used for personal, family,
|
299 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
300 |
+
into a dwelling. In determining whether a product is a consumer product,
|
301 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
302 |
+
product received by a particular user, "normally used" refers to a
|
303 |
+
typical or common use of that class of product, regardless of the status
|
304 |
+
of the particular user or of the way in which the particular user
|
305 |
+
actually uses, or expects or is expected to use, the product. A product
|
306 |
+
is a consumer product regardless of whether the product has substantial
|
307 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
308 |
+
the only significant mode of use of the product.
|
309 |
+
|
310 |
+
"Installation Information" for a User Product means any methods,
|
311 |
+
procedures, authorization keys, or other information required to install
|
312 |
+
and execute modified versions of a covered work in that User Product from
|
313 |
+
a modified version of its Corresponding Source. The information must
|
314 |
+
suffice to ensure that the continued functioning of the modified object
|
315 |
+
code is in no case prevented or interfered with solely because
|
316 |
+
modification has been made.
|
317 |
+
|
318 |
+
If you convey an object code work under this section in, or with, or
|
319 |
+
specifically for use in, a User Product, and the conveying occurs as
|
320 |
+
part of a transaction in which the right of possession and use of the
|
321 |
+
User Product is transferred to the recipient in perpetuity or for a
|
322 |
+
fixed term (regardless of how the transaction is characterized), the
|
323 |
+
Corresponding Source conveyed under this section must be accompanied
|
324 |
+
by the Installation Information. But this requirement does not apply
|
325 |
+
if neither you nor any third party retains the ability to install
|
326 |
+
modified object code on the User Product (for example, the work has
|
327 |
+
been installed in ROM).
|
328 |
+
|
329 |
+
The requirement to provide Installation Information does not include a
|
330 |
+
requirement to continue to provide support service, warranty, or updates
|
331 |
+
for a work that has been modified or installed by the recipient, or for
|
332 |
+
the User Product in which it has been modified or installed. Access to a
|
333 |
+
network may be denied when the modification itself materially and
|
334 |
+
adversely affects the operation of the network or violates the rules and
|
335 |
+
protocols for communication across the network.
|
336 |
+
|
337 |
+
Corresponding Source conveyed, and Installation Information provided,
|
338 |
+
in accord with this section must be in a format that is publicly
|
339 |
+
documented (and with an implementation available to the public in
|
340 |
+
source code form), and must require no special password or key for
|
341 |
+
unpacking, reading or copying.
|
342 |
+
|
343 |
+
7. Additional Terms.
|
344 |
+
|
345 |
+
"Additional permissions" are terms that supplement the terms of this
|
346 |
+
License by making exceptions from one or more of its conditions.
|
347 |
+
Additional permissions that are applicable to the entire Program shall
|
348 |
+
be treated as though they were included in this License, to the extent
|
349 |
+
that they are valid under applicable law. If additional permissions
|
350 |
+
apply only to part of the Program, that part may be used separately
|
351 |
+
under those permissions, but the entire Program remains governed by
|
352 |
+
this License without regard to the additional permissions.
|
353 |
+
|
354 |
+
When you convey a copy of a covered work, you may at your option
|
355 |
+
remove any additional permissions from that copy, or from any part of
|
356 |
+
it. (Additional permissions may be written to require their own
|
357 |
+
removal in certain cases when you modify the work.) You may place
|
358 |
+
additional permissions on material, added by you to a covered work,
|
359 |
+
for which you have or can give appropriate copyright permission.
|
360 |
+
|
361 |
+
Notwithstanding any other provision of this License, for material you
|
362 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
363 |
+
that material) supplement the terms of this License with terms:
|
364 |
+
|
365 |
+
a) Disclaiming warranty or limiting liability differently from the
|
366 |
+
terms of sections 15 and 16 of this License; or
|
367 |
+
|
368 |
+
b) Requiring preservation of specified reasonable legal notices or
|
369 |
+
author attributions in that material or in the Appropriate Legal
|
370 |
+
Notices displayed by works containing it; or
|
371 |
+
|
372 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
373 |
+
requiring that modified versions of such material be marked in
|
374 |
+
reasonable ways as different from the original version; or
|
375 |
+
|
376 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
377 |
+
authors of the material; or
|
378 |
+
|
379 |
+
e) Declining to grant rights under trademark law for use of some
|
380 |
+
trade names, trademarks, or service marks; or
|
381 |
+
|
382 |
+
f) Requiring indemnification of licensors and authors of that
|
383 |
+
material by anyone who conveys the material (or modified versions of
|
384 |
+
it) with contractual assumptions of liability to the recipient, for
|
385 |
+
any liability that these contractual assumptions directly impose on
|
386 |
+
those licensors and authors.
|
387 |
+
|
388 |
+
All other non-permissive additional terms are considered "further
|
389 |
+
restrictions" within the meaning of section 10. If the Program as you
|
390 |
+
received it, or any part of it, contains a notice stating that it is
|
391 |
+
governed by this License along with a term that is a further
|
392 |
+
restriction, you may remove that term. If a license document contains
|
393 |
+
a further restriction but permits relicensing or conveying under this
|
394 |
+
License, you may add to a covered work material governed by the terms
|
395 |
+
of that license document, provided that the further restriction does
|
396 |
+
not survive such relicensing or conveying.
|
397 |
+
|
398 |
+
If you add terms to a covered work in accord with this section, you
|
399 |
+
must place, in the relevant source files, a statement of the
|
400 |
+
additional terms that apply to those files, or a notice indicating
|
401 |
+
where to find the applicable terms.
|
402 |
+
|
403 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
404 |
+
form of a separately written license, or stated as exceptions;
|
405 |
+
the above requirements apply either way.
|
406 |
+
|
407 |
+
8. Termination.
|
408 |
+
|
409 |
+
You may not propagate or modify a covered work except as expressly
|
410 |
+
provided under this License. Any attempt otherwise to propagate or
|
411 |
+
modify it is void, and will automatically terminate your rights under
|
412 |
+
this License (including any patent licenses granted under the third
|
413 |
+
paragraph of section 11).
|
414 |
+
|
415 |
+
However, if you cease all violation of this License, then your
|
416 |
+
license from a particular copyright holder is reinstated (a)
|
417 |
+
provisionally, unless and until the copyright holder explicitly and
|
418 |
+
finally terminates your license, and (b) permanently, if the copyright
|
419 |
+
holder fails to notify you of the violation by some reasonable means
|
420 |
+
prior to 60 days after the cessation.
|
421 |
+
|
422 |
+
Moreover, your license from a particular copyright holder is
|
423 |
+
reinstated permanently if the copyright holder notifies you of the
|
424 |
+
violation by some reasonable means, this is the first time you have
|
425 |
+
received notice of violation of this License (for any work) from that
|
426 |
+
copyright holder, and you cure the violation prior to 30 days after
|
427 |
+
your receipt of the notice.
|
428 |
+
|
429 |
+
Termination of your rights under this section does not terminate the
|
430 |
+
licenses of parties who have received copies or rights from you under
|
431 |
+
this License. If your rights have been terminated and not permanently
|
432 |
+
reinstated, you do not qualify to receive new licenses for the same
|
433 |
+
material under section 10.
|
434 |
+
|
435 |
+
9. Acceptance Not Required for Having Copies.
|
436 |
+
|
437 |
+
You are not required to accept this License in order to receive or
|
438 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
439 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
440 |
+
to receive a copy likewise does not require acceptance. However,
|
441 |
+
nothing other than this License grants you permission to propagate or
|
442 |
+
modify any covered work. These actions infringe copyright if you do
|
443 |
+
not accept this License. Therefore, by modifying or propagating a
|
444 |
+
covered work, you indicate your acceptance of this License to do so.
|
445 |
+
|
446 |
+
10. Automatic Licensing of Downstream Recipients.
|
447 |
+
|
448 |
+
Each time you convey a covered work, the recipient automatically
|
449 |
+
receives a license from the original licensors, to run, modify and
|
450 |
+
propagate that work, subject to this License. You are not responsible
|
451 |
+
for enforcing compliance by third parties with this License.
|
452 |
+
|
453 |
+
An "entity transaction" is a transaction transferring control of an
|
454 |
+
organization, or substantially all assets of one, or subdividing an
|
455 |
+
organization, or merging organizations. If propagation of a covered
|
456 |
+
work results from an entity transaction, each party to that
|
457 |
+
transaction who receives a copy of the work also receives whatever
|
458 |
+
licenses to the work the party's predecessor in interest had or could
|
459 |
+
give under the previous paragraph, plus a right to possession of the
|
460 |
+
Corresponding Source of the work from the predecessor in interest, if
|
461 |
+
the predecessor has it or can get it with reasonable efforts.
|
462 |
+
|
463 |
+
You may not impose any further restrictions on the exercise of the
|
464 |
+
rights granted or affirmed under this License. For example, you may
|
465 |
+
not impose a license fee, royalty, or other charge for exercise of
|
466 |
+
rights granted under this License, and you may not initiate litigation
|
467 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
468 |
+
any patent claim is infringed by making, using, selling, offering for
|
469 |
+
sale, or importing the Program or any portion of it.
|
470 |
+
|
471 |
+
11. Patents.
|
472 |
+
|
473 |
+
A "contributor" is a copyright holder who authorizes use under this
|
474 |
+
License of the Program or a work on which the Program is based. The
|
475 |
+
work thus licensed is called the contributor's "contributor version".
|
476 |
+
|
477 |
+
A contributor's "essential patent claims" are all patent claims
|
478 |
+
owned or controlled by the contributor, whether already acquired or
|
479 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
480 |
+
by this License, of making, using, or selling its contributor version,
|
481 |
+
but do not include claims that would be infringed only as a
|
482 |
+
consequence of further modification of the contributor version. For
|
483 |
+
purposes of this definition, "control" includes the right to grant
|
484 |
+
patent sublicenses in a manner consistent with the requirements of
|
485 |
+
this License.
|
486 |
+
|
487 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
488 |
+
patent license under the contributor's essential patent claims, to
|
489 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
490 |
+
propagate the contents of its contributor version.
|
491 |
+
|
492 |
+
In the following three paragraphs, a "patent license" is any express
|
493 |
+
agreement or commitment, however denominated, not to enforce a patent
|
494 |
+
(such as an express permission to practice a patent or covenant not to
|
495 |
+
sue for patent infringement). To "grant" such a patent license to a
|
496 |
+
party means to make such an agreement or commitment not to enforce a
|
497 |
+
patent against the party.
|
498 |
+
|
499 |
+
If you convey a covered work, knowingly relying on a patent license,
|
500 |
+
and the Corresponding Source of the work is not available for anyone
|
501 |
+
to copy, free of charge and under the terms of this License, through a
|
502 |
+
publicly available network server or other readily accessible means,
|
503 |
+
then you must either (1) cause the Corresponding Source to be so
|
504 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
505 |
+
patent license for this particular work, or (3) arrange, in a manner
|
506 |
+
consistent with the requirements of this License, to extend the patent
|
507 |
+
license to downstream recipients. "Knowingly relying" means you have
|
508 |
+
actual knowledge that, but for the patent license, your conveying the
|
509 |
+
covered work in a country, or your recipient's use of the covered work
|
510 |
+
in a country, would infringe one or more identifiable patents in that
|
511 |
+
country that you have reason to believe are valid.
|
512 |
+
|
513 |
+
If, pursuant to or in connection with a single transaction or
|
514 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
515 |
+
covered work, and grant a patent license to some of the parties
|
516 |
+
receiving the covered work authorizing them to use, propagate, modify
|
517 |
+
or convey a specific copy of the covered work, then the patent license
|
518 |
+
you grant is automatically extended to all recipients of the covered
|
519 |
+
work and works based on it.
|
520 |
+
|
521 |
+
A patent license is "discriminatory" if it does not include within
|
522 |
+
the scope of its coverage, prohibits the exercise of, or is
|
523 |
+
conditioned on the non-exercise of one or more of the rights that are
|
524 |
+
specifically granted under this License. You may not convey a covered
|
525 |
+
work if you are a party to an arrangement with a third party that is
|
526 |
+
in the business of distributing software, under which you make payment
|
527 |
+
to the third party based on the extent of your activity of conveying
|
528 |
+
the work, and under which the third party grants, to any of the
|
529 |
+
parties who would receive the covered work from you, a discriminatory
|
530 |
+
patent license (a) in connection with copies of the covered work
|
531 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
532 |
+
for and in connection with specific products or compilations that
|
533 |
+
contain the covered work, unless you entered into that arrangement,
|
534 |
+
or that patent license was granted, prior to 28 March 2007.
|
535 |
+
|
536 |
+
Nothing in this License shall be construed as excluding or limiting
|
537 |
+
any implied license or other defenses to infringement that may
|
538 |
+
otherwise be available to you under applicable patent law.
|
539 |
+
|
540 |
+
12. No Surrender of Others' Freedom.
|
541 |
+
|
542 |
+
If conditions are imposed on you (whether by court order, agreement or
|
543 |
+
otherwise) that contradict the conditions of this License, they do not
|
544 |
+
excuse you from the conditions of this License. If you cannot convey a
|
545 |
+
covered work so as to satisfy simultaneously your obligations under this
|
546 |
+
License and any other pertinent obligations, then as a consequence you may
|
547 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
548 |
+
to collect a royalty for further conveying from those to whom you convey
|
549 |
+
the Program, the only way you could satisfy both those terms and this
|
550 |
+
License would be to refrain entirely from conveying the Program.
|
551 |
+
|
552 |
+
13. Use with the GNU Affero General Public License.
|
553 |
+
|
554 |
+
Notwithstanding any other provision of this License, you have
|
555 |
+
permission to link or combine any covered work with a work licensed
|
556 |
+
under version 3 of the GNU Affero General Public License into a single
|
557 |
+
combined work, and to convey the resulting work. The terms of this
|
558 |
+
License will continue to apply to the part which is the covered work,
|
559 |
+
but the special requirements of the GNU Affero General Public License,
|
560 |
+
section 13, concerning interaction through a network will apply to the
|
561 |
+
combination as such.
|
562 |
+
|
563 |
+
14. Revised Versions of this License.
|
564 |
+
|
565 |
+
The Free Software Foundation may publish revised and/or new versions of
|
566 |
+
the GNU General Public License from time to time. Such new versions will
|
567 |
+
be similar in spirit to the present version, but may differ in detail to
|
568 |
+
address new problems or concerns.
|
569 |
+
|
570 |
+
Each version is given a distinguishing version number. If the
|
571 |
+
Program specifies that a certain numbered version of the GNU General
|
572 |
+
Public License "or any later version" applies to it, you have the
|
573 |
+
option of following the terms and conditions either of that numbered
|
574 |
+
version or of any later version published by the Free Software
|
575 |
+
Foundation. If the Program does not specify a version number of the
|
576 |
+
GNU General Public License, you may choose any version ever published
|
577 |
+
by the Free Software Foundation.
|
578 |
+
|
579 |
+
If the Program specifies that a proxy can decide which future
|
580 |
+
versions of the GNU General Public License can be used, that proxy's
|
581 |
+
public statement of acceptance of a version permanently authorizes you
|
582 |
+
to choose that version for the Program.
|
583 |
+
|
584 |
+
Later license versions may give you additional or different
|
585 |
+
permissions. However, no additional obligations are imposed on any
|
586 |
+
author or copyright holder as a result of your choosing to follow a
|
587 |
+
later version.
|
588 |
+
|
589 |
+
15. Disclaimer of Warranty.
|
590 |
+
|
591 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
592 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
593 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
594 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
595 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
596 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
597 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
598 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
599 |
+
|
600 |
+
16. Limitation of Liability.
|
601 |
+
|
602 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
603 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
604 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
605 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
606 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
607 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
608 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
609 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
610 |
+
SUCH DAMAGES.
|
611 |
+
|
612 |
+
17. Interpretation of Sections 15 and 16.
|
613 |
+
|
614 |
+
If the disclaimer of warranty and limitation of liability provided
|
615 |
+
above cannot be given local legal effect according to their terms,
|
616 |
+
reviewing courts shall apply local law that most closely approximates
|
617 |
+
an absolute waiver of all civil liability in connection with the
|
618 |
+
Program, unless a warranty or assumption of liability accompanies a
|
619 |
+
copy of the Program in return for a fee.
|
620 |
+
|
621 |
+
END OF TERMS AND CONDITIONS
|
622 |
+
|
623 |
+
How to Apply These Terms to Your New Programs
|
624 |
+
|
625 |
+
If you develop a new program, and you want it to be of the greatest
|
626 |
+
possible use to the public, the best way to achieve this is to make it
|
627 |
+
free software which everyone can redistribute and change under these terms.
|
628 |
+
|
629 |
+
To do so, attach the following notices to the program. It is safest
|
630 |
+
to attach them to the start of each source file to most effectively
|
631 |
+
state the exclusion of warranty; and each file should have at least
|
632 |
+
the "copyright" line and a pointer to where the full notice is found.
|
633 |
+
|
634 |
+
<one line to give the program's name and a brief idea of what it does.>
|
635 |
+
Copyright (C) <year> <name of author>
|
636 |
+
|
637 |
+
This program is free software: you can redistribute it and/or modify
|
638 |
+
it under the terms of the GNU General Public License as published by
|
639 |
+
the Free Software Foundation, either version 3 of the License, or
|
640 |
+
(at your option) any later version.
|
641 |
+
|
642 |
+
This program is distributed in the hope that it will be useful,
|
643 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
644 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
645 |
+
GNU General Public License for more details.
|
646 |
+
|
647 |
+
You should have received a copy of the GNU General Public License
|
648 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
649 |
+
|
650 |
+
Also add information on how to contact you by electronic and paper mail.
|
651 |
+
|
652 |
+
If the program does terminal interaction, make it output a short
|
653 |
+
notice like this when it starts in an interactive mode:
|
654 |
+
|
655 |
+
<program> Copyright (C) <year> <name of author>
|
656 |
+
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
657 |
+
This is free software, and you are welcome to redistribute it
|
658 |
+
under certain conditions; type `show c' for details.
|
659 |
+
|
660 |
+
The hypothetical commands `show w' and `show c' should show the appropriate
|
661 |
+
parts of the General Public License. Of course, your program's commands
|
662 |
+
might be different; for a GUI interface, you would use an "about box".
|
663 |
+
|
664 |
+
You should also get your employer (if you work as a programmer) or school,
|
665 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
666 |
+
For more information on this, and how to apply and follow the GNU GPL, see
|
667 |
+
<https://www.gnu.org/licenses/>.
|
668 |
+
|
669 |
+
The GNU General Public License does not permit incorporating your program
|
670 |
+
into proprietary programs. If your program is a subroutine library, you
|
671 |
+
may consider it more useful to permit linking proprietary applications with
|
672 |
+
the library. If this is what you want to do, use the GNU Lesser General
|
673 |
+
Public License instead of this License. But first, please read
|
674 |
+
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
README.md
CHANGED
@@ -1,8 +1,8 @@
|
|
1 |
---
|
2 |
-
title: Fasterrcnn
|
3 |
-
emoji:
|
4 |
colorFrom: red
|
5 |
-
colorTo:
|
6 |
sdk: streamlit
|
7 |
sdk_version: 1.26.0
|
8 |
app_file: app.py
|
@@ -10,4 +10,4 @@ pinned: false
|
|
10 |
license: lgpl-3.0
|
11 |
---
|
12 |
|
13 |
-
|
|
|
1 |
---
|
2 |
+
title: Fasterrcnn
|
3 |
+
emoji: 📷
|
4 |
colorFrom: red
|
5 |
+
colorTo: purple
|
6 |
sdk: streamlit
|
7 |
sdk_version: 1.26.0
|
8 |
app_file: app.py
|
|
|
10 |
license: lgpl-3.0
|
11 |
---
|
12 |
|
13 |
+
# Faster RCNN Demo with Web App using Hugging Face Spaces
|
app.py
ADDED
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Object detection demo with MobileNet SSD.
|
2 |
+
This model and code are based on
|
3 |
+
https://github.com/robmarkcole/object-detection-app
|
4 |
+
"""
|
5 |
+
|
6 |
+
import logging
|
7 |
+
import queue
|
8 |
+
from pathlib import Path
|
9 |
+
from typing import List, NamedTuple
|
10 |
+
|
11 |
+
import av
|
12 |
+
import cv2
|
13 |
+
import numpy as np
|
14 |
+
import streamlit as st
|
15 |
+
from streamlit_webrtc import WebRtcMode, webrtc_streamer
|
16 |
+
|
17 |
+
from sample_utils.download import download_file
|
18 |
+
from sample_utils.turn import get_ice_servers
|
19 |
+
|
20 |
+
HERE = Path(__file__).parent
|
21 |
+
ROOT = HERE
|
22 |
+
|
23 |
+
logger = logging.getLogger(__name__)
|
24 |
+
|
25 |
+
|
26 |
+
MODEL_URL = "https://github.com/robmarkcole/object-detection-app/raw/master/model/MobileNetSSD_deploy.caffemodel" # noqa: E501
|
27 |
+
MODEL_LOCAL_PATH = ROOT / "./models/MobileNetSSD_deploy.caffemodel"
|
28 |
+
PROTOTXT_URL = "https://github.com/robmarkcole/object-detection-app/raw/master/model/MobileNetSSD_deploy.prototxt.txt" # noqa: E501
|
29 |
+
PROTOTXT_LOCAL_PATH = ROOT / "./models/MobileNetSSD_deploy.prototxt.txt"
|
30 |
+
|
31 |
+
CLASSES = [
|
32 |
+
"background",
|
33 |
+
"aeroplane",
|
34 |
+
"bicycle",
|
35 |
+
"bird",
|
36 |
+
"boat",
|
37 |
+
"bottle",
|
38 |
+
"bus",
|
39 |
+
"car",
|
40 |
+
"cat",
|
41 |
+
"chair",
|
42 |
+
"cow",
|
43 |
+
"diningtable",
|
44 |
+
"dog",
|
45 |
+
"horse",
|
46 |
+
"motorbike",
|
47 |
+
"person",
|
48 |
+
"pottedplant",
|
49 |
+
"sheep",
|
50 |
+
"sofa",
|
51 |
+
"train",
|
52 |
+
"tvmonitor",
|
53 |
+
]
|
54 |
+
|
55 |
+
|
56 |
+
class Detection(NamedTuple):
|
57 |
+
class_id: int
|
58 |
+
label: str
|
59 |
+
score: float
|
60 |
+
box: np.ndarray
|
61 |
+
|
62 |
+
|
63 |
+
@st.cache_resource # type: ignore
|
64 |
+
def generate_label_colors():
|
65 |
+
return np.random.uniform(0, 255, size=(len(CLASSES), 3))
|
66 |
+
|
67 |
+
|
68 |
+
COLORS = generate_label_colors()
|
69 |
+
|
70 |
+
download_file(MODEL_URL, MODEL_LOCAL_PATH, expected_size=23147564)
|
71 |
+
download_file(PROTOTXT_URL, PROTOTXT_LOCAL_PATH, expected_size=29353)
|
72 |
+
|
73 |
+
|
74 |
+
# Session-specific caching
|
75 |
+
cache_key = "object_detection_dnn"
|
76 |
+
if cache_key in st.session_state:
|
77 |
+
net = st.session_state[cache_key]
|
78 |
+
else:
|
79 |
+
net = cv2.dnn.readNetFromCaffe(str(PROTOTXT_LOCAL_PATH), str(MODEL_LOCAL_PATH))
|
80 |
+
st.session_state[cache_key] = net
|
81 |
+
|
82 |
+
score_threshold = st.slider("Score threshold", 0.0, 1.0, 0.5, 0.05)
|
83 |
+
|
84 |
+
# NOTE: The callback will be called in another thread,
|
85 |
+
# so use a queue here for thread-safety to pass the data
|
86 |
+
# from inside to outside the callback.
|
87 |
+
# TODO: A general-purpose shared state object may be more useful.
|
88 |
+
result_queue: "queue.Queue[List[Detection]]" = queue.Queue()
|
89 |
+
|
90 |
+
|
91 |
+
def video_frame_callback(frame: av.VideoFrame) -> av.VideoFrame:
|
92 |
+
image = frame.to_ndarray(format="bgr24")
|
93 |
+
|
94 |
+
# Run inference
|
95 |
+
blob = cv2.dnn.blobFromImage(
|
96 |
+
cv2.resize(image, (300, 300)), 0.007843, (300, 300), 127.5
|
97 |
+
)
|
98 |
+
net.setInput(blob)
|
99 |
+
output = net.forward()
|
100 |
+
|
101 |
+
h, w = image.shape[:2]
|
102 |
+
|
103 |
+
# Convert the output array into a structured form.
|
104 |
+
output = output.squeeze() # (1, 1, N, 7) -> (N, 7)
|
105 |
+
output = output[output[:, 2] >= score_threshold]
|
106 |
+
detections = [
|
107 |
+
Detection(
|
108 |
+
class_id=int(detection[1]),
|
109 |
+
label=CLASSES[int(detection[1])],
|
110 |
+
score=float(detection[2]),
|
111 |
+
box=(detection[3:7] * np.array([w, h, w, h])),
|
112 |
+
)
|
113 |
+
for detection in output
|
114 |
+
]
|
115 |
+
|
116 |
+
# Render bounding boxes and captions
|
117 |
+
for detection in detections:
|
118 |
+
caption = f"{detection.label}: {round(detection.score * 100, 2)}%"
|
119 |
+
color = COLORS[detection.class_id]
|
120 |
+
xmin, ymin, xmax, ymax = detection.box.astype("int")
|
121 |
+
|
122 |
+
cv2.rectangle(image, (xmin, ymin), (xmax, ymax), color, 2)
|
123 |
+
cv2.putText(
|
124 |
+
image,
|
125 |
+
caption,
|
126 |
+
(xmin, ymin - 15 if ymin - 15 > 15 else ymin + 15),
|
127 |
+
cv2.FONT_HERSHEY_SIMPLEX,
|
128 |
+
0.5,
|
129 |
+
color,
|
130 |
+
2,
|
131 |
+
)
|
132 |
+
|
133 |
+
result_queue.put(detections)
|
134 |
+
|
135 |
+
return av.VideoFrame.from_ndarray(image, format="bgr24")
|
136 |
+
|
137 |
+
|
138 |
+
webrtc_ctx = webrtc_streamer(
|
139 |
+
key="object-detection",
|
140 |
+
mode=WebRtcMode.SENDRECV,
|
141 |
+
rtc_configuration={
|
142 |
+
"iceServers": get_ice_servers(),
|
143 |
+
"iceTransportPolicy": "relay",
|
144 |
+
},
|
145 |
+
video_frame_callback=video_frame_callback,
|
146 |
+
media_stream_constraints={"video": True, "audio": False},
|
147 |
+
async_processing=True,
|
148 |
+
)
|
149 |
+
|
150 |
+
if st.checkbox("Show the detected labels", value=True):
|
151 |
+
if webrtc_ctx.state.playing:
|
152 |
+
labels_placeholder = st.empty()
|
153 |
+
# NOTE: The video transformation with object detection and
|
154 |
+
# this loop displaying the result labels are running
|
155 |
+
# in different threads asynchronously.
|
156 |
+
# Then the rendered video frames and the labels displayed here
|
157 |
+
# are not strictly synchronized.
|
158 |
+
while True:
|
159 |
+
result = result_queue.get()
|
160 |
+
labels_placeholder.table(result)
|
161 |
+
|
162 |
+
st.markdown(
|
163 |
+
"This demo uses a model and code from "
|
164 |
+
"https://github.com/robmarkcole/object-detection-app. "
|
165 |
+
"Many thanks to the project."
|
166 |
+
)
|
bbox.py
ADDED
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import List
|
2 |
+
|
3 |
+
import torch
|
4 |
+
from torch import Tensor
|
5 |
+
|
6 |
+
|
7 |
+
class BBox(object):
|
8 |
+
|
9 |
+
def __init__(self, left: float, top: float, right: float, bottom: float):
|
10 |
+
super().__init__()
|
11 |
+
self.left = left
|
12 |
+
self.top = top
|
13 |
+
self.right = right
|
14 |
+
self.bottom = bottom
|
15 |
+
|
16 |
+
def __repr__(self) -> str:
|
17 |
+
return 'BBox[l={:.1f}, t={:.1f}, r={:.1f}, b={:.1f}]'.format(
|
18 |
+
self.left, self.top, self.right, self.bottom)
|
19 |
+
|
20 |
+
def tolist(self) -> List[float]:
|
21 |
+
return [self.left, self.top, self.right, self.bottom]
|
22 |
+
|
23 |
+
@staticmethod
|
24 |
+
def to_center_base(bboxes: Tensor) -> Tensor:
|
25 |
+
return torch.stack([
|
26 |
+
(bboxes[..., 0] + bboxes[..., 2]) / 2,
|
27 |
+
(bboxes[..., 1] + bboxes[..., 3]) / 2,
|
28 |
+
bboxes[..., 2] - bboxes[..., 0],
|
29 |
+
bboxes[..., 3] - bboxes[..., 1]
|
30 |
+
], dim=-1)
|
31 |
+
|
32 |
+
@staticmethod
|
33 |
+
def from_center_base(center_based_bboxes: Tensor) -> Tensor:
|
34 |
+
return torch.stack([
|
35 |
+
center_based_bboxes[..., 0] - center_based_bboxes[..., 2] / 2,
|
36 |
+
center_based_bboxes[..., 1] - center_based_bboxes[..., 3] / 2,
|
37 |
+
center_based_bboxes[..., 0] + center_based_bboxes[..., 2] / 2,
|
38 |
+
center_based_bboxes[..., 1] + center_based_bboxes[..., 3] / 2
|
39 |
+
], dim=-1)
|
40 |
+
|
41 |
+
@staticmethod
|
42 |
+
def calc_transformer(src_bboxes: Tensor, dst_bboxes: Tensor) -> Tensor:
|
43 |
+
center_based_src_bboxes = BBox.to_center_base(src_bboxes)
|
44 |
+
center_based_dst_bboxes = BBox.to_center_base(dst_bboxes)
|
45 |
+
transformers = torch.stack([
|
46 |
+
(center_based_dst_bboxes[..., 0] - center_based_src_bboxes[..., 0]) / center_based_src_bboxes[..., 2],
|
47 |
+
(center_based_dst_bboxes[..., 1] - center_based_src_bboxes[..., 1]) / center_based_src_bboxes[..., 3],
|
48 |
+
torch.log(center_based_dst_bboxes[..., 2] / center_based_src_bboxes[..., 2]),
|
49 |
+
torch.log(center_based_dst_bboxes[..., 3] / center_based_src_bboxes[..., 3])
|
50 |
+
], dim=-1)
|
51 |
+
return transformers
|
52 |
+
|
53 |
+
@staticmethod
|
54 |
+
def apply_transformer(src_bboxes: Tensor, transformers: Tensor) -> Tensor:
|
55 |
+
center_based_src_bboxes = BBox.to_center_base(src_bboxes)
|
56 |
+
center_based_dst_bboxes = torch.stack([
|
57 |
+
transformers[..., 0] * center_based_src_bboxes[..., 2] + center_based_src_bboxes[..., 0],
|
58 |
+
transformers[..., 1] * center_based_src_bboxes[..., 3] + center_based_src_bboxes[..., 1],
|
59 |
+
torch.exp(transformers[..., 2]) * center_based_src_bboxes[..., 2],
|
60 |
+
torch.exp(transformers[..., 3]) * center_based_src_bboxes[..., 3]
|
61 |
+
], dim=-1)
|
62 |
+
dst_bboxes = BBox.from_center_base(center_based_dst_bboxes)
|
63 |
+
return dst_bboxes
|
64 |
+
|
65 |
+
@staticmethod
|
66 |
+
def iou(source: Tensor, other: Tensor) -> Tensor:
|
67 |
+
source, other = source.unsqueeze(dim=-2).repeat(1, 1, other.shape[-2], 1), \
|
68 |
+
other.unsqueeze(dim=-3).repeat(1, source.shape[-2], 1, 1)
|
69 |
+
|
70 |
+
source_area = (source[..., 2] - source[..., 0]) * (source[..., 3] - source[..., 1])
|
71 |
+
other_area = (other[..., 2] - other[..., 0]) * (other[..., 3] - other[..., 1])
|
72 |
+
|
73 |
+
intersection_left = torch.max(source[..., 0], other[..., 0])
|
74 |
+
intersection_top = torch.max(source[..., 1], other[..., 1])
|
75 |
+
intersection_right = torch.min(source[..., 2], other[..., 2])
|
76 |
+
intersection_bottom = torch.min(source[..., 3], other[..., 3])
|
77 |
+
intersection_width = torch.clamp(intersection_right - intersection_left, min=0)
|
78 |
+
intersection_height = torch.clamp(intersection_bottom - intersection_top, min=0)
|
79 |
+
intersection_area = intersection_width * intersection_height
|
80 |
+
|
81 |
+
return intersection_area / (source_area + other_area - intersection_area)
|
82 |
+
|
83 |
+
@staticmethod
|
84 |
+
def inside(bboxes: Tensor, left: float, top: float, right: float, bottom: float) -> Tensor:
|
85 |
+
return ((bboxes[..., 0] >= left) * (bboxes[..., 1] >= top) *
|
86 |
+
(bboxes[..., 2] <= right) * (bboxes[..., 3] <= bottom))
|
87 |
+
|
88 |
+
@staticmethod
|
89 |
+
def clip(bboxes: Tensor, left: float, top: float, right: float, bottom: float) -> Tensor:
|
90 |
+
bboxes[..., [0, 2]] = bboxes[..., [0, 2]].clamp(min=left, max=right)
|
91 |
+
bboxes[..., [1, 3]] = bboxes[..., [1, 3]].clamp(min=top, max=bottom)
|
92 |
+
return bboxes
|
eval.py
ADDED
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import os
|
3 |
+
import time
|
4 |
+
|
5 |
+
import uuid
|
6 |
+
|
7 |
+
from backbone.base import Base as BackboneBase
|
8 |
+
from config.eval_config import EvalConfig as Config
|
9 |
+
from dataset.base import Base as DatasetBase
|
10 |
+
from evaluator import Evaluator
|
11 |
+
from logger import Logger as Log
|
12 |
+
from model import Model
|
13 |
+
from roi.pooler import Pooler
|
14 |
+
|
15 |
+
|
16 |
+
def _eval(path_to_checkpoint: str, dataset_name: str, backbone_name: str, path_to_data_dir: str, path_to_results_dir: str):
|
17 |
+
dataset = DatasetBase.from_name(dataset_name)(path_to_data_dir, DatasetBase.Mode.EVAL, Config.IMAGE_MIN_SIDE, Config.IMAGE_MAX_SIDE)
|
18 |
+
evaluator = Evaluator(dataset, path_to_data_dir, path_to_results_dir)
|
19 |
+
|
20 |
+
Log.i('Found {:d} samples'.format(len(dataset)))
|
21 |
+
|
22 |
+
backbone = BackboneBase.from_name(backbone_name)(pretrained=False)
|
23 |
+
model = Model(backbone, dataset.num_classes(), pooler_mode=Config.POOLER_MODE,
|
24 |
+
anchor_ratios=Config.ANCHOR_RATIOS, anchor_sizes=Config.ANCHOR_SIZES,
|
25 |
+
rpn_pre_nms_top_n=Config.RPN_PRE_NMS_TOP_N, rpn_post_nms_top_n=Config.RPN_POST_NMS_TOP_N).cuda()
|
26 |
+
model.load(path_to_checkpoint)
|
27 |
+
|
28 |
+
Log.i('Start evaluating with 1 GPU (1 batch per GPU)')
|
29 |
+
mean_ap, detail = evaluator.evaluate(model)
|
30 |
+
Log.i('Done')
|
31 |
+
|
32 |
+
Log.i('mean AP = {:.4f}'.format(mean_ap))
|
33 |
+
Log.i('\n' + detail)
|
34 |
+
|
35 |
+
|
36 |
+
if __name__ == '__main__':
|
37 |
+
def main():
|
38 |
+
parser = argparse.ArgumentParser()
|
39 |
+
parser.add_argument('-s', '--dataset', type=str, choices=DatasetBase.OPTIONS, required=True, help='name of dataset')
|
40 |
+
parser.add_argument('-b', '--backbone', type=str, choices=BackboneBase.OPTIONS, required=True, help='name of backbone model')
|
41 |
+
parser.add_argument('-d', '--data_dir', type=str, default='./data', help='path to data directory')
|
42 |
+
parser.add_argument('--image_min_side', type=float, help='default: {:g}'.format(Config.IMAGE_MIN_SIDE))
|
43 |
+
parser.add_argument('--image_max_side', type=float, help='default: {:g}'.format(Config.IMAGE_MAX_SIDE))
|
44 |
+
parser.add_argument('--anchor_ratios', type=str, help='default: "{!s}"'.format(Config.ANCHOR_RATIOS))
|
45 |
+
parser.add_argument('--anchor_sizes', type=str, help='default: "{!s}"'.format(Config.ANCHOR_SIZES))
|
46 |
+
parser.add_argument('--pooler_mode', type=str, choices=Pooler.OPTIONS, help='default: {.value:s}'.format(Config.POOLER_MODE))
|
47 |
+
parser.add_argument('--rpn_pre_nms_top_n', type=int, help='default: {:d}'.format(Config.RPN_PRE_NMS_TOP_N))
|
48 |
+
parser.add_argument('--rpn_post_nms_top_n', type=int, help='default: {:d}'.format(Config.RPN_POST_NMS_TOP_N))
|
49 |
+
parser.add_argument('--checkpoint', type=str, help='path to evaluating checkpoint')
|
50 |
+
args = parser.parse_args()
|
51 |
+
|
52 |
+
path_to_checkpoint = args.checkpoint
|
53 |
+
dataset_name = args.dataset
|
54 |
+
backbone_name = args.backbone
|
55 |
+
path_to_data_dir = args.data_dir
|
56 |
+
|
57 |
+
path_to_results_dir = os.path.join(os.path.dirname(path_to_checkpoint), 'results-{:s}-{:s}-{:s}'.format(
|
58 |
+
time.strftime('%Y%m%d%H%M%S'), path_to_checkpoint.split(os.path.sep)[-1].split(os.path.curdir)[0],
|
59 |
+
str(uuid.uuid4()).split('-')[0]))
|
60 |
+
os.makedirs(path_to_results_dir)
|
61 |
+
|
62 |
+
Config.setup(image_min_side=args.image_min_side, image_max_side=args.image_max_side,
|
63 |
+
anchor_ratios=args.anchor_ratios, anchor_sizes=args.anchor_sizes, pooler_mode=args.pooler_mode,
|
64 |
+
rpn_pre_nms_top_n=args.rpn_pre_nms_top_n, rpn_post_nms_top_n=args.rpn_post_nms_top_n)
|
65 |
+
|
66 |
+
Log.initialize(os.path.join(path_to_results_dir, 'eval.log'))
|
67 |
+
Log.i('Arguments:')
|
68 |
+
for k, v in vars(args).items():
|
69 |
+
Log.i(f'\t{k} = {v}')
|
70 |
+
Log.i(Config.describe())
|
71 |
+
|
72 |
+
_eval(path_to_checkpoint, dataset_name, backbone_name, path_to_data_dir, path_to_results_dir)
|
73 |
+
|
74 |
+
main()
|
evaluator.py
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Tuple
|
2 |
+
|
3 |
+
import torch
|
4 |
+
from torch.utils.data import DataLoader
|
5 |
+
from tqdm import tqdm
|
6 |
+
|
7 |
+
from dataset.base import Base as DatasetBase
|
8 |
+
from model import Model
|
9 |
+
|
10 |
+
|
11 |
+
class Evaluator(object):
|
12 |
+
def __init__(self, dataset: DatasetBase, path_to_data_dir: str, path_to_results_dir: str):
|
13 |
+
super().__init__()
|
14 |
+
self._dataset = dataset
|
15 |
+
self._dataloader = DataLoader(dataset, batch_size=1, shuffle=False, num_workers=8, pin_memory=True)
|
16 |
+
self._path_to_data_dir = path_to_data_dir
|
17 |
+
self._path_to_results_dir = path_to_results_dir
|
18 |
+
|
19 |
+
def evaluate(self, model: Model) -> Tuple[float, str]:
|
20 |
+
all_image_ids, all_detection_bboxes, all_detection_classes, all_detection_probs = [], [], [], []
|
21 |
+
|
22 |
+
with torch.no_grad():
|
23 |
+
for _, (image_id_batch, image_batch, scale_batch, _, _) in enumerate(tqdm(self._dataloader)):
|
24 |
+
image_batch = image_batch.cuda()
|
25 |
+
assert image_batch.shape[0] == 1, 'do not use batch size more than 1 on evaluation'
|
26 |
+
|
27 |
+
detection_bboxes, detection_classes, detection_probs, detection_batch_indices = model.eval().forward(image_batch)
|
28 |
+
|
29 |
+
scale_batch = scale_batch[detection_batch_indices].unsqueeze(dim=-1).expand_as(detection_bboxes).to(device=detection_bboxes.device)
|
30 |
+
detection_bboxes = detection_bboxes / scale_batch
|
31 |
+
|
32 |
+
kept_indices = (detection_probs > 0.05).nonzero().view(-1)
|
33 |
+
detection_bboxes = detection_bboxes[kept_indices]
|
34 |
+
detection_classes = detection_classes.to(device=detection_bboxes.device)
|
35 |
+
detection_classes = detection_classes[kept_indices]
|
36 |
+
detection_probs = detection_probs[kept_indices]
|
37 |
+
detection_batch_indices = detection_batch_indices.to(device=detection_bboxes.device)
|
38 |
+
detection_batch_indices = detection_batch_indices[kept_indices]
|
39 |
+
|
40 |
+
all_detection_bboxes.extend(detection_bboxes.tolist())
|
41 |
+
all_detection_classes.extend(detection_classes.tolist())
|
42 |
+
all_detection_probs.extend(detection_probs.tolist())
|
43 |
+
all_image_ids.extend([image_id_batch[i] for i in detection_batch_indices])
|
44 |
+
|
45 |
+
mean_ap, detail = self._dataset.evaluate(self._path_to_results_dir, all_image_ids, all_detection_bboxes, all_detection_classes, all_detection_probs)
|
46 |
+
return mean_ap, detail
|
infer.py
ADDED
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import os
|
3 |
+
import random
|
4 |
+
import torch
|
5 |
+
|
6 |
+
from PIL import ImageDraw
|
7 |
+
from torchvision.transforms import transforms
|
8 |
+
from dataset.base import Base as DatasetBase
|
9 |
+
from backbone.base import Base as BackboneBase
|
10 |
+
from bbox import BBox
|
11 |
+
from model import Model
|
12 |
+
from roi.pooler import Pooler
|
13 |
+
from config.eval_config import EvalConfig as Config
|
14 |
+
|
15 |
+
|
16 |
+
def _infer(path_to_input_image: str, path_to_output_image: str, path_to_checkpoint: str, dataset_name: str, backbone_name: str, prob_thresh: float):
|
17 |
+
dataset_class = DatasetBase.from_name(dataset_name)
|
18 |
+
backbone = BackboneBase.from_name(backbone_name)(pretrained=False)
|
19 |
+
model = Model(backbone, dataset_class.num_classes(), pooler_mode=Config.POOLER_MODE,
|
20 |
+
anchor_ratios=Config.ANCHOR_RATIOS, anchor_sizes=Config.ANCHOR_SIZES,
|
21 |
+
rpn_pre_nms_top_n=Config.RPN_PRE_NMS_TOP_N, rpn_post_nms_top_n=Config.RPN_POST_NMS_TOP_N).cuda()
|
22 |
+
model.load(path_to_checkpoint)
|
23 |
+
|
24 |
+
with torch.no_grad():
|
25 |
+
image = transforms.Image.open(path_to_input_image)
|
26 |
+
image_tensor, scale = dataset_class.preprocess(image, Config.IMAGE_MIN_SIDE, Config.IMAGE_MAX_SIDE)
|
27 |
+
|
28 |
+
detection_bboxes, detection_classes, detection_probs, _ = \
|
29 |
+
model.eval().forward(image_tensor.unsqueeze(dim=0).cuda())
|
30 |
+
detection_bboxes /= scale
|
31 |
+
|
32 |
+
kept_indices = detection_probs > prob_thresh
|
33 |
+
detection_bboxes = detection_bboxes[kept_indices]
|
34 |
+
detection_classes = detection_classes[kept_indices]
|
35 |
+
detection_probs = detection_probs[kept_indices]
|
36 |
+
|
37 |
+
draw = ImageDraw.Draw(image)
|
38 |
+
|
39 |
+
for bbox, cls, prob in zip(detection_bboxes.tolist(), detection_classes.tolist(), detection_probs.tolist()):
|
40 |
+
color = random.choice(['red', 'green', 'blue', 'yellow', 'purple', 'white'])
|
41 |
+
bbox = BBox(left=bbox[0], top=bbox[1], right=bbox[2], bottom=bbox[3])
|
42 |
+
category = dataset_class.LABEL_TO_CATEGORY_DICT[cls]
|
43 |
+
|
44 |
+
draw.rectangle(((bbox.left, bbox.top), (bbox.right, bbox.bottom)), outline=color)
|
45 |
+
draw.text((bbox.left, bbox.top), text=f'{category:s} {prob:.3f}', fill=color)
|
46 |
+
|
47 |
+
image.save(path_to_output_image)
|
48 |
+
print(f'Output image is saved to {path_to_output_image}')
|
49 |
+
|
50 |
+
|
51 |
+
if __name__ == '__main__':
|
52 |
+
def main():
|
53 |
+
parser = argparse.ArgumentParser()
|
54 |
+
parser.add_argument('-s', '--dataset', type=str, choices=DatasetBase.OPTIONS, required=True, help='name of dataset')
|
55 |
+
parser.add_argument('-b', '--backbone', type=str, choices=BackboneBase.OPTIONS, required=True, help='name of backbone model')
|
56 |
+
parser.add_argument('-c', '--checkpoint', type=str, required=True, help='path to checkpoint')
|
57 |
+
parser.add_argument('-p', '--probability_threshold', type=float, default=0.6, help='threshold of detection probability')
|
58 |
+
parser.add_argument('--image_min_side', type=float, help='default: {:g}'.format(Config.IMAGE_MIN_SIDE))
|
59 |
+
parser.add_argument('--image_max_side', type=float, help='default: {:g}'.format(Config.IMAGE_MAX_SIDE))
|
60 |
+
parser.add_argument('--anchor_ratios', type=str, help='default: "{!s}"'.format(Config.ANCHOR_RATIOS))
|
61 |
+
parser.add_argument('--anchor_sizes', type=str, help='default: "{!s}"'.format(Config.ANCHOR_SIZES))
|
62 |
+
parser.add_argument('--pooler_mode', type=str, choices=Pooler.OPTIONS, help='default: {.value:s}'.format(Config.POOLER_MODE))
|
63 |
+
parser.add_argument('--rpn_pre_nms_top_n', type=int, help='default: {:d}'.format(Config.RPN_PRE_NMS_TOP_N))
|
64 |
+
parser.add_argument('--rpn_post_nms_top_n', type=int, help='default: {:d}'.format(Config.RPN_POST_NMS_TOP_N))
|
65 |
+
parser.add_argument('input', type=str, help='path to input image')
|
66 |
+
parser.add_argument('output', type=str, help='path to output result image')
|
67 |
+
args = parser.parse_args()
|
68 |
+
|
69 |
+
path_to_input_image = args.input
|
70 |
+
path_to_output_image = args.output
|
71 |
+
dataset_name = args.dataset
|
72 |
+
backbone_name = args.backbone
|
73 |
+
path_to_checkpoint = args.checkpoint
|
74 |
+
prob_thresh = args.probability_threshold
|
75 |
+
|
76 |
+
os.makedirs(os.path.join(os.path.curdir, os.path.dirname(path_to_output_image)), exist_ok=True)
|
77 |
+
|
78 |
+
Config.setup(image_min_side=args.image_min_side, image_max_side=args.image_max_side,
|
79 |
+
anchor_ratios=args.anchor_ratios, anchor_sizes=args.anchor_sizes, pooler_mode=args.pooler_mode,
|
80 |
+
rpn_pre_nms_top_n=args.rpn_pre_nms_top_n, rpn_post_nms_top_n=args.rpn_post_nms_top_n)
|
81 |
+
|
82 |
+
print('Arguments:')
|
83 |
+
for k, v in vars(args).items():
|
84 |
+
print(f'\t{k} = {v}')
|
85 |
+
print(Config.describe())
|
86 |
+
|
87 |
+
_infer(path_to_input_image, path_to_output_image, path_to_checkpoint, dataset_name, backbone_name, prob_thresh)
|
88 |
+
|
89 |
+
main()
|
infer_stream.py
ADDED
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import itertools
|
3 |
+
import random
|
4 |
+
import time
|
5 |
+
import torch
|
6 |
+
|
7 |
+
import cv2
|
8 |
+
import numpy as np
|
9 |
+
from PIL import ImageDraw, Image
|
10 |
+
|
11 |
+
from backbone.base import Base as BackboneBase
|
12 |
+
from config.eval_config import EvalConfig as Config
|
13 |
+
from dataset.base import Base as DatasetBase
|
14 |
+
from bbox import BBox
|
15 |
+
from model import Model
|
16 |
+
from roi.pooler import Pooler
|
17 |
+
|
18 |
+
|
19 |
+
def _infer_stream(path_to_input_stream_endpoint: str, period_of_inference: int, path_to_checkpoint: str, dataset_name: str, backbone_name: str, prob_thresh: float):
|
20 |
+
dataset_class = DatasetBase.from_name(dataset_name)
|
21 |
+
backbone = BackboneBase.from_name(backbone_name)(pretrained=False)
|
22 |
+
model = Model(backbone, dataset_class.num_classes(), pooler_mode=Config.POOLER_MODE,
|
23 |
+
anchor_ratios=Config.ANCHOR_RATIOS, anchor_sizes=Config.ANCHOR_SIZES,
|
24 |
+
rpn_pre_nms_top_n=Config.RPN_PRE_NMS_TOP_N, rpn_post_nms_top_n=Config.RPN_POST_NMS_TOP_N).cuda()
|
25 |
+
model.load(path_to_checkpoint)
|
26 |
+
|
27 |
+
if path_to_input_stream_endpoint.isdigit():
|
28 |
+
path_to_input_stream_endpoint = int(path_to_input_stream_endpoint)
|
29 |
+
video_capture = cv2.VideoCapture(path_to_input_stream_endpoint)
|
30 |
+
|
31 |
+
with torch.no_grad():
|
32 |
+
for sn in itertools.count(start=1):
|
33 |
+
success, frame = video_capture.read()
|
34 |
+
|
35 |
+
if not success:
|
36 |
+
break
|
37 |
+
|
38 |
+
if sn % period_of_inference != 0:
|
39 |
+
continue
|
40 |
+
|
41 |
+
timestamp = time.time()
|
42 |
+
|
43 |
+
image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
44 |
+
image = Image.fromarray(image)
|
45 |
+
image_tensor, scale = dataset_class.preprocess(image, Config.IMAGE_MIN_SIDE, Config.IMAGE_MAX_SIDE)
|
46 |
+
|
47 |
+
detection_bboxes, detection_classes, detection_probs, _ = \
|
48 |
+
model.eval().forward(image_tensor.unsqueeze(dim=0).cuda())
|
49 |
+
detection_bboxes /= scale
|
50 |
+
|
51 |
+
kept_indices = detection_probs > prob_thresh
|
52 |
+
detection_bboxes = detection_bboxes[kept_indices]
|
53 |
+
detection_classes = detection_classes[kept_indices]
|
54 |
+
detection_probs = detection_probs[kept_indices]
|
55 |
+
|
56 |
+
draw = ImageDraw.Draw(image)
|
57 |
+
|
58 |
+
for bbox, cls, prob in zip(detection_bboxes.tolist(), detection_classes.tolist(), detection_probs.tolist()):
|
59 |
+
color = random.choice(['red', 'green', 'blue', 'yellow', 'purple', 'white'])
|
60 |
+
bbox = BBox(left=bbox[0], top=bbox[1], right=bbox[2], bottom=bbox[3])
|
61 |
+
category = dataset_class.LABEL_TO_CATEGORY_DICT[cls]
|
62 |
+
|
63 |
+
draw.rectangle(((bbox.left, bbox.top), (bbox.right, bbox.bottom)), outline=color)
|
64 |
+
draw.text((bbox.left, bbox.top), text=f'{category:s} {prob:.3f}', fill=color)
|
65 |
+
|
66 |
+
image = np.array(image)
|
67 |
+
frame = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
|
68 |
+
|
69 |
+
elapse = time.time() - timestamp
|
70 |
+
fps = 1 / elapse
|
71 |
+
cv2.putText(frame, f'FPS = {fps:.1f}', (20, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1, cv2.LINE_AA)
|
72 |
+
|
73 |
+
cv2.imshow('easy-faster-rcnn-pytorch', frame)
|
74 |
+
if cv2.waitKey(10) == 27:
|
75 |
+
break
|
76 |
+
|
77 |
+
video_capture.release()
|
78 |
+
cv2.destroyAllWindows()
|
79 |
+
|
80 |
+
|
81 |
+
if __name__ == '__main__':
|
82 |
+
def main():
|
83 |
+
parser = argparse.ArgumentParser()
|
84 |
+
parser.add_argument('-s', '--dataset', type=str, choices=DatasetBase.OPTIONS, required=True, help='name of dataset')
|
85 |
+
parser.add_argument('-b', '--backbone', type=str, choices=BackboneBase.OPTIONS, required=True, help='name of backbone model')
|
86 |
+
parser.add_argument('-c', '--checkpoint', type=str, required=True, help='path to checkpoint')
|
87 |
+
parser.add_argument('-p', '--probability_threshold', type=float, default=0.6, help='threshold of detection probability')
|
88 |
+
parser.add_argument('--image_min_side', type=float, help='default: {:g}'.format(Config.IMAGE_MIN_SIDE))
|
89 |
+
parser.add_argument('--image_max_side', type=float, help='default: {:g}'.format(Config.IMAGE_MAX_SIDE))
|
90 |
+
parser.add_argument('--anchor_ratios', type=str, help='default: "{!s}"'.format(Config.ANCHOR_RATIOS))
|
91 |
+
parser.add_argument('--anchor_sizes', type=str, help='default: "{!s}"'.format(Config.ANCHOR_SIZES))
|
92 |
+
parser.add_argument('--pooler_mode', type=str, choices=Pooler.OPTIONS, help='default: {.value:s}'.format(Config.POOLER_MODE))
|
93 |
+
parser.add_argument('--rpn_pre_nms_top_n', type=int, help='default: {:d}'.format(Config.RPN_PRE_NMS_TOP_N))
|
94 |
+
parser.add_argument('--rpn_post_nms_top_n', type=int, help='default: {:d}'.format(Config.RPN_POST_NMS_TOP_N))
|
95 |
+
parser.add_argument('--stream_input', type=str, help='path to input stream endpoint')
|
96 |
+
parser.add_argument('--period', type=int, help='period of inference')
|
97 |
+
args = parser.parse_args()
|
98 |
+
|
99 |
+
path_to_input_stream_endpoint = args.stream_input
|
100 |
+
period_of_inference = args.period
|
101 |
+
dataset_name = args.dataset
|
102 |
+
backbone_name = args.backbone
|
103 |
+
path_to_checkpoint = args.checkpoint
|
104 |
+
prob_thresh = args.probability_threshold
|
105 |
+
|
106 |
+
Config.setup(image_min_side=args.image_min_side, image_max_side=args.image_max_side,
|
107 |
+
anchor_ratios=args.anchor_ratios, anchor_sizes=args.anchor_sizes, pooler_mode=args.pooler_mode,
|
108 |
+
rpn_pre_nms_top_n=args.rpn_pre_nms_top_n, rpn_post_nms_top_n=args.rpn_post_nms_top_n)
|
109 |
+
|
110 |
+
print('Arguments:')
|
111 |
+
for k, v in vars(args).items():
|
112 |
+
print(f'\t{k} = {v}')
|
113 |
+
print(Config.describe())
|
114 |
+
|
115 |
+
_infer_stream(path_to_input_stream_endpoint, period_of_inference, path_to_checkpoint, dataset_name, backbone_name, prob_thresh)
|
116 |
+
|
117 |
+
main()
|
logger.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
|
3 |
+
|
4 |
+
class Logger(object):
|
5 |
+
Initialized = False
|
6 |
+
|
7 |
+
@staticmethod
|
8 |
+
def initialize(path_to_log_file):
|
9 |
+
logging.basicConfig(level=logging.INFO,
|
10 |
+
format='%(asctime)s %(levelname)-8s %(message)s',
|
11 |
+
datefmt='%Y-%m-%d %H:%M:%S',
|
12 |
+
handlers=[logging.FileHandler(path_to_log_file),
|
13 |
+
logging.StreamHandler()])
|
14 |
+
Logger.Initialized = True
|
15 |
+
|
16 |
+
@staticmethod
|
17 |
+
def log(level, message):
|
18 |
+
assert Logger.Initialized, 'Logger has not been initialized'
|
19 |
+
logging.log(level, message)
|
20 |
+
|
21 |
+
@staticmethod
|
22 |
+
def d(message):
|
23 |
+
Logger.log(logging.DEBUG, message)
|
24 |
+
|
25 |
+
@staticmethod
|
26 |
+
def i(message):
|
27 |
+
Logger.log(logging.INFO, message)
|
28 |
+
|
29 |
+
@staticmethod
|
30 |
+
def w(message):
|
31 |
+
Logger.log(logging.WARNING, message)
|
32 |
+
|
33 |
+
@staticmethod
|
34 |
+
def e(message):
|
35 |
+
Logger.log(logging.ERROR, message)
|
model.py
ADDED
@@ -0,0 +1,218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from typing import Union, Tuple, List, Optional
|
3 |
+
|
4 |
+
import torch
|
5 |
+
from torch import nn, Tensor
|
6 |
+
from torch.nn import functional as F
|
7 |
+
from torch.optim import Optimizer
|
8 |
+
from torch.optim.lr_scheduler import _LRScheduler
|
9 |
+
|
10 |
+
from backbone.base import Base as BackboneBase
|
11 |
+
from bbox import BBox
|
12 |
+
from extension.functional import beta_smooth_l1_loss
|
13 |
+
from roi.pooler import Pooler
|
14 |
+
from rpn.region_proposal_network import RegionProposalNetwork
|
15 |
+
#from support.layer.nms import nms
|
16 |
+
from torchvision.ops import nms
|
17 |
+
|
18 |
+
|
19 |
+
class Model(nn.Module):
|
20 |
+
|
21 |
+
def __init__(self, backbone: BackboneBase, num_classes: int, pooler_mode: Pooler.Mode,
|
22 |
+
anchor_ratios: List[Tuple[int, int]], anchor_sizes: List[int],
|
23 |
+
rpn_pre_nms_top_n: int, rpn_post_nms_top_n: int,
|
24 |
+
anchor_smooth_l1_loss_beta: Optional[float] = None, proposal_smooth_l1_loss_beta: Optional[float] = None):
|
25 |
+
super().__init__()
|
26 |
+
|
27 |
+
self.features, hidden, num_features_out, num_hidden_out = backbone.features()
|
28 |
+
self._bn_modules = nn.ModuleList([it for it in self.features.modules() if isinstance(it, nn.BatchNorm2d)] +
|
29 |
+
[it for it in hidden.modules() if isinstance(it, nn.BatchNorm2d)])
|
30 |
+
|
31 |
+
# NOTE: It's crucial to freeze batch normalization modules for few batches training, which can be done by following processes
|
32 |
+
# (1) Change mode to `eval`
|
33 |
+
# (2) Disable gradient (we move this process into `forward`)
|
34 |
+
for bn_module in self._bn_modules:
|
35 |
+
for parameter in bn_module.parameters():
|
36 |
+
parameter.requires_grad = False
|
37 |
+
|
38 |
+
self.rpn = RegionProposalNetwork(num_features_out, anchor_ratios, anchor_sizes, rpn_pre_nms_top_n, rpn_post_nms_top_n, anchor_smooth_l1_loss_beta)
|
39 |
+
self.detection = Model.Detection(pooler_mode, hidden, num_hidden_out, num_classes, proposal_smooth_l1_loss_beta)
|
40 |
+
|
41 |
+
def forward(self, image_batch: Tensor,
|
42 |
+
gt_bboxes_batch: Tensor = None, gt_classes_batch: Tensor = None) -> Union[Tuple[Tensor, Tensor, Tensor, Tensor],
|
43 |
+
Tuple[Tensor, Tensor, Tensor, Tensor]]:
|
44 |
+
# disable gradient for each forwarding process just in case model was switched to `train` mode at any time
|
45 |
+
for bn_module in self._bn_modules:
|
46 |
+
bn_module.eval()
|
47 |
+
|
48 |
+
features = self.features(image_batch)
|
49 |
+
|
50 |
+
batch_size, _, image_height, image_width = image_batch.shape
|
51 |
+
_, _, features_height, features_width = features.shape
|
52 |
+
|
53 |
+
anchor_bboxes = self.rpn.generate_anchors(image_width, image_height, num_x_anchors=features_width, num_y_anchors=features_height).to(features).repeat(batch_size, 1, 1)
|
54 |
+
|
55 |
+
if self.training:
|
56 |
+
anchor_objectnesses, anchor_transformers, anchor_objectness_losses, anchor_transformer_losses = self.rpn.forward(features, anchor_bboxes, gt_bboxes_batch, image_width, image_height)
|
57 |
+
proposal_bboxes = self.rpn.generate_proposals(anchor_bboxes, anchor_objectnesses, anchor_transformers, image_width, image_height).detach() # it's necessary to detach `proposal_bboxes` here
|
58 |
+
proposal_classes, proposal_transformers, proposal_class_losses, proposal_transformer_losses = self.detection.forward(features, proposal_bboxes, gt_classes_batch, gt_bboxes_batch)
|
59 |
+
return anchor_objectness_losses, anchor_transformer_losses, proposal_class_losses, proposal_transformer_losses
|
60 |
+
else:
|
61 |
+
anchor_objectnesses, anchor_transformers = self.rpn.forward(features)
|
62 |
+
proposal_bboxes = self.rpn.generate_proposals(anchor_bboxes, anchor_objectnesses, anchor_transformers, image_width, image_height)
|
63 |
+
proposal_classes, proposal_transformers = self.detection.forward(features, proposal_bboxes)
|
64 |
+
detection_bboxes, detection_classes, detection_probs, detection_batch_indices = self.detection.generate_detections(proposal_bboxes, proposal_classes, proposal_transformers, image_width, image_height)
|
65 |
+
return detection_bboxes, detection_classes, detection_probs, detection_batch_indices
|
66 |
+
|
67 |
+
def save(self, path_to_checkpoints_dir: str, step: int, optimizer: Optimizer, scheduler: _LRScheduler) -> str:
|
68 |
+
path_to_checkpoint = os.path.join(path_to_checkpoints_dir, f'model-{step}.pth')
|
69 |
+
checkpoint = {
|
70 |
+
'state_dict': self.state_dict(),
|
71 |
+
'step': step,
|
72 |
+
'optimizer_state_dict': optimizer.state_dict(),
|
73 |
+
'scheduler_state_dict': scheduler.state_dict()
|
74 |
+
}
|
75 |
+
torch.save(checkpoint, path_to_checkpoint)
|
76 |
+
return path_to_checkpoint
|
77 |
+
|
78 |
+
def load(self, path_to_checkpoint: str, optimizer: Optimizer = None, scheduler: _LRScheduler = None) -> 'Model':
|
79 |
+
checkpoint = torch.load(path_to_checkpoint)
|
80 |
+
self.load_state_dict(checkpoint['state_dict'])
|
81 |
+
step = checkpoint['step']
|
82 |
+
if optimizer is not None:
|
83 |
+
optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
|
84 |
+
if scheduler is not None:
|
85 |
+
scheduler.load_state_dict(checkpoint['scheduler_state_dict'])
|
86 |
+
return step
|
87 |
+
|
88 |
+
class Detection(nn.Module):
|
89 |
+
|
90 |
+
def __init__(self, pooler_mode: Pooler.Mode, hidden: nn.Module, num_hidden_out: int, num_classes: int, proposal_smooth_l1_loss_beta: float):
|
91 |
+
super().__init__()
|
92 |
+
self._pooler_mode = pooler_mode
|
93 |
+
self.hidden = hidden
|
94 |
+
self.num_classes = num_classes
|
95 |
+
self._proposal_class = nn.Linear(num_hidden_out, num_classes)
|
96 |
+
self._proposal_transformer = nn.Linear(num_hidden_out, num_classes * 4)
|
97 |
+
self._proposal_smooth_l1_loss_beta = proposal_smooth_l1_loss_beta
|
98 |
+
self._transformer_normalize_mean = torch.tensor([0., 0., 0., 0.], dtype=torch.float)
|
99 |
+
self._transformer_normalize_std = torch.tensor([.1, .1, .2, .2], dtype=torch.float)
|
100 |
+
|
101 |
+
def forward(self, features: Tensor, proposal_bboxes: Tensor,
|
102 |
+
gt_classes_batch: Optional[Tensor] = None, gt_bboxes_batch: Optional[Tensor] = None) -> Union[Tuple[Tensor, Tensor], Tuple[Tensor, Tensor, Tensor, Tensor]]:
|
103 |
+
batch_size = features.shape[0]
|
104 |
+
|
105 |
+
if not self.training:
|
106 |
+
proposal_batch_indices = torch.arange(end=batch_size, dtype=torch.long, device=proposal_bboxes.device).view(-1, 1).repeat(1, proposal_bboxes.shape[1])
|
107 |
+
pool = Pooler.apply(features, proposal_bboxes.view(-1, 4), proposal_batch_indices.view(-1), mode=self._pooler_mode)
|
108 |
+
hidden = self.hidden(pool)
|
109 |
+
hidden = F.adaptive_max_pool2d(input=hidden, output_size=1)
|
110 |
+
hidden = hidden.view(hidden.shape[0], -1)
|
111 |
+
|
112 |
+
proposal_classes = self._proposal_class(hidden)
|
113 |
+
proposal_transformers = self._proposal_transformer(hidden)
|
114 |
+
|
115 |
+
proposal_classes = proposal_classes.view(batch_size, -1, proposal_classes.shape[-1])
|
116 |
+
proposal_transformers = proposal_transformers.view(batch_size, -1, proposal_transformers.shape[-1])
|
117 |
+
return proposal_classes, proposal_transformers
|
118 |
+
else:
|
119 |
+
# find labels for each `proposal_bboxes`
|
120 |
+
labels = torch.full((batch_size, proposal_bboxes.shape[1]), -1, dtype=torch.long, device=proposal_bboxes.device)
|
121 |
+
ious = BBox.iou(proposal_bboxes, gt_bboxes_batch)
|
122 |
+
proposal_max_ious, proposal_assignments = ious.max(dim=2)
|
123 |
+
labels[proposal_max_ious < 0.5] = 0
|
124 |
+
fg_masks = proposal_max_ious >= 0.5
|
125 |
+
if len(fg_masks.nonzero()) > 0:
|
126 |
+
labels[fg_masks] = gt_classes_batch[fg_masks.nonzero()[:, 0], proposal_assignments[fg_masks]]
|
127 |
+
|
128 |
+
# select 128 x `batch_size` samples
|
129 |
+
fg_indices = (labels > 0).nonzero()
|
130 |
+
bg_indices = (labels == 0).nonzero()
|
131 |
+
fg_indices = fg_indices[torch.randperm(len(fg_indices))[:min(len(fg_indices), 32 * batch_size)]]
|
132 |
+
bg_indices = bg_indices[torch.randperm(len(bg_indices))[:128 * batch_size - len(fg_indices)]]
|
133 |
+
selected_indices = torch.cat([fg_indices, bg_indices], dim=0)
|
134 |
+
selected_indices = selected_indices[torch.randperm(len(selected_indices))].unbind(dim=1)
|
135 |
+
|
136 |
+
proposal_bboxes = proposal_bboxes[selected_indices]
|
137 |
+
gt_bboxes = gt_bboxes_batch[selected_indices[0], proposal_assignments[selected_indices]]
|
138 |
+
gt_proposal_classes = labels[selected_indices]
|
139 |
+
gt_proposal_transformers = BBox.calc_transformer(proposal_bboxes, gt_bboxes)
|
140 |
+
batch_indices = selected_indices[0]
|
141 |
+
|
142 |
+
pool = Pooler.apply(features, proposal_bboxes, proposal_batch_indices=batch_indices, mode=self._pooler_mode)
|
143 |
+
hidden = self.hidden(pool)
|
144 |
+
hidden = F.adaptive_max_pool2d(input=hidden, output_size=1)
|
145 |
+
hidden = hidden.view(hidden.shape[0], -1)
|
146 |
+
|
147 |
+
proposal_classes = self._proposal_class(hidden)
|
148 |
+
proposal_transformers = self._proposal_transformer(hidden)
|
149 |
+
proposal_class_losses, proposal_transformer_losses = self.loss(proposal_classes, proposal_transformers,
|
150 |
+
gt_proposal_classes, gt_proposal_transformers,
|
151 |
+
batch_size, batch_indices)
|
152 |
+
|
153 |
+
return proposal_classes, proposal_transformers, proposal_class_losses, proposal_transformer_losses
|
154 |
+
|
155 |
+
def loss(self, proposal_classes: Tensor, proposal_transformers: Tensor,
|
156 |
+
gt_proposal_classes: Tensor, gt_proposal_transformers: Tensor,
|
157 |
+
batch_size, batch_indices) -> Tuple[Tensor, Tensor]:
|
158 |
+
proposal_transformers = proposal_transformers.view(-1, self.num_classes, 4)[torch.arange(end=len(proposal_transformers), dtype=torch.long), gt_proposal_classes]
|
159 |
+
transformer_normalize_mean = self._transformer_normalize_mean.to(device=gt_proposal_transformers.device)
|
160 |
+
transformer_normalize_std = self._transformer_normalize_std.to(device=gt_proposal_transformers.device)
|
161 |
+
gt_proposal_transformers = (gt_proposal_transformers - transformer_normalize_mean) / transformer_normalize_std # scale up target to make regressor easier to learn
|
162 |
+
|
163 |
+
cross_entropies = torch.empty(batch_size, dtype=torch.float, device=proposal_classes.device)
|
164 |
+
smooth_l1_losses = torch.empty(batch_size, dtype=torch.float, device=proposal_transformers.device)
|
165 |
+
|
166 |
+
for batch_index in range(batch_size):
|
167 |
+
selected_indices = (batch_indices == batch_index).nonzero().view(-1)
|
168 |
+
|
169 |
+
cross_entropy = F.cross_entropy(input=proposal_classes[selected_indices],
|
170 |
+
target=gt_proposal_classes[selected_indices])
|
171 |
+
|
172 |
+
fg_indices = gt_proposal_classes[selected_indices].nonzero().view(-1)
|
173 |
+
smooth_l1_loss = beta_smooth_l1_loss(input=proposal_transformers[selected_indices][fg_indices],
|
174 |
+
target=gt_proposal_transformers[selected_indices][fg_indices],
|
175 |
+
beta=self._proposal_smooth_l1_loss_beta)
|
176 |
+
|
177 |
+
cross_entropies[batch_index] = cross_entropy
|
178 |
+
smooth_l1_losses[batch_index] = smooth_l1_loss
|
179 |
+
|
180 |
+
return cross_entropies, smooth_l1_losses
|
181 |
+
|
182 |
+
def generate_detections(self, proposal_bboxes: Tensor, proposal_classes: Tensor, proposal_transformers: Tensor, image_width: int, image_height: int) -> Tuple[Tensor, Tensor, Tensor, Tensor]:
|
183 |
+
batch_size = proposal_bboxes.shape[0]
|
184 |
+
|
185 |
+
proposal_transformers = proposal_transformers.view(batch_size, -1, self.num_classes, 4)
|
186 |
+
transformer_normalize_std = self._transformer_normalize_std.to(device=proposal_transformers.device)
|
187 |
+
transformer_normalize_mean = self._transformer_normalize_mean.to(device=proposal_transformers.device)
|
188 |
+
proposal_transformers = proposal_transformers * transformer_normalize_std + transformer_normalize_mean
|
189 |
+
|
190 |
+
proposal_bboxes = proposal_bboxes.unsqueeze(dim=2).repeat(1, 1, self.num_classes, 1)
|
191 |
+
detection_bboxes = BBox.apply_transformer(proposal_bboxes, proposal_transformers)
|
192 |
+
detection_bboxes = BBox.clip(detection_bboxes, left=0, top=0, right=image_width, bottom=image_height)
|
193 |
+
detection_probs = F.softmax(proposal_classes, dim=-1)
|
194 |
+
|
195 |
+
all_detection_bboxes = []
|
196 |
+
all_detection_classes = []
|
197 |
+
all_detection_probs = []
|
198 |
+
all_detection_batch_indices = []
|
199 |
+
|
200 |
+
for batch_index in range(batch_size):
|
201 |
+
for c in range(1, self.num_classes):
|
202 |
+
class_bboxes = detection_bboxes[batch_index, :, c, :]
|
203 |
+
class_probs = detection_probs[batch_index, :, c]
|
204 |
+
threshold = 0.3
|
205 |
+
kept_indices = nms(class_bboxes, class_probs, threshold)
|
206 |
+
class_bboxes = class_bboxes[kept_indices]
|
207 |
+
class_probs = class_probs[kept_indices]
|
208 |
+
|
209 |
+
all_detection_bboxes.append(class_bboxes)
|
210 |
+
all_detection_classes.append(torch.full((len(kept_indices),), c, dtype=torch.int))
|
211 |
+
all_detection_probs.append(class_probs)
|
212 |
+
all_detection_batch_indices.append(torch.full((len(kept_indices),), batch_index, dtype=torch.long))
|
213 |
+
|
214 |
+
all_detection_bboxes = torch.cat(all_detection_bboxes, dim=0)
|
215 |
+
all_detection_classes = torch.cat(all_detection_classes, dim=0)
|
216 |
+
all_detection_probs = torch.cat(all_detection_probs, dim=0)
|
217 |
+
all_detection_batch_indices = torch.cat(all_detection_batch_indices, dim=0)
|
218 |
+
return all_detection_bboxes, all_detection_classes, all_detection_probs, all_detection_batch_indices
|
packages.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
ffmpeg
|
requirements.txt
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
tqdm
|
2 |
+
numpy
|
3 |
+
torch
|
4 |
+
torchvision
|
5 |
+
Pillow
|
6 |
+
opencv-python-headless==4.8.0.76
|
7 |
+
streamlit_webrtc==0.47.0
|
8 |
+
pyOpenSSL==23.1.0
|
9 |
+
pydub==0.25.1
|
10 |
+
twilio~=8.5.0
|
11 |
+
matplotlib
|
test_streamlit.py
ADDED
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Object detection demo with MobileNet SSD.
|
2 |
+
This model and code are based on
|
3 |
+
https://github.com/robmarkcole/object-detection-app
|
4 |
+
"""
|
5 |
+
|
6 |
+
import logging
|
7 |
+
import queue
|
8 |
+
from pathlib import Path
|
9 |
+
from typing import List, NamedTuple
|
10 |
+
|
11 |
+
import av
|
12 |
+
import cv2
|
13 |
+
import numpy as np
|
14 |
+
import streamlit as st
|
15 |
+
from streamlit_webrtc import WebRtcMode, webrtc_streamer
|
16 |
+
|
17 |
+
from sample_utils.download import download_file
|
18 |
+
from sample_utils.turn import get_ice_servers
|
19 |
+
|
20 |
+
HERE = Path(__file__).parent
|
21 |
+
ROOT = HERE
|
22 |
+
|
23 |
+
logger = logging.getLogger(__name__)
|
24 |
+
|
25 |
+
|
26 |
+
MODEL_URL = "https://github.com/robmarkcole/object-detection-app/raw/master/model/MobileNetSSD_deploy.caffemodel" # noqa: E501
|
27 |
+
MODEL_LOCAL_PATH = ROOT / "./models/MobileNetSSD_deploy.caffemodel"
|
28 |
+
PROTOTXT_URL = "https://github.com/robmarkcole/object-detection-app/raw/master/model/MobileNetSSD_deploy.prototxt.txt" # noqa: E501
|
29 |
+
PROTOTXT_LOCAL_PATH = ROOT / "./models/MobileNetSSD_deploy.prototxt.txt"
|
30 |
+
|
31 |
+
CLASSES = [
|
32 |
+
"background",
|
33 |
+
"aeroplane",
|
34 |
+
"bicycle",
|
35 |
+
"bird",
|
36 |
+
"boat",
|
37 |
+
"bottle",
|
38 |
+
"bus",
|
39 |
+
"car",
|
40 |
+
"cat",
|
41 |
+
"chair",
|
42 |
+
"cow",
|
43 |
+
"diningtable",
|
44 |
+
"dog",
|
45 |
+
"horse",
|
46 |
+
"motorbike",
|
47 |
+
"person",
|
48 |
+
"pottedplant",
|
49 |
+
"sheep",
|
50 |
+
"sofa",
|
51 |
+
"train",
|
52 |
+
"tvmonitor",
|
53 |
+
]
|
54 |
+
|
55 |
+
|
56 |
+
class Detection(NamedTuple):
|
57 |
+
class_id: int
|
58 |
+
label: str
|
59 |
+
score: float
|
60 |
+
box: np.ndarray
|
61 |
+
|
62 |
+
|
63 |
+
@st.cache_resource # type: ignore
|
64 |
+
def generate_label_colors():
|
65 |
+
return np.random.uniform(0, 255, size=(len(CLASSES), 3))
|
66 |
+
|
67 |
+
|
68 |
+
COLORS = generate_label_colors()
|
69 |
+
|
70 |
+
download_file(MODEL_URL, MODEL_LOCAL_PATH, expected_size=23147564)
|
71 |
+
download_file(PROTOTXT_URL, PROTOTXT_LOCAL_PATH, expected_size=29353)
|
72 |
+
|
73 |
+
|
74 |
+
# Session-specific caching
|
75 |
+
cache_key = "object_detection_dnn"
|
76 |
+
if cache_key in st.session_state:
|
77 |
+
net = st.session_state[cache_key]
|
78 |
+
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
|
79 |
+
net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)
|
80 |
+
else:
|
81 |
+
net = cv2.dnn.readNetFromCaffe(str(PROTOTXT_LOCAL_PATH), str(MODEL_LOCAL_PATH))
|
82 |
+
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
|
83 |
+
net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)
|
84 |
+
st.session_state[cache_key] = net
|
85 |
+
|
86 |
+
score_threshold = st.slider("Score threshold", 0.0, 1.0, 0.5, 0.05)
|
87 |
+
|
88 |
+
# NOTE: The callback will be called in another thread,
|
89 |
+
# so use a queue here for thread-safety to pass the data
|
90 |
+
# from inside to outside the callback.
|
91 |
+
# TODO: A general-purpose shared state object may be more useful.
|
92 |
+
result_queue: "queue.Queue[List[Detection]]" = queue.Queue()
|
93 |
+
|
94 |
+
|
95 |
+
def video_frame_callback(frame: av.VideoFrame) -> av.VideoFrame:
|
96 |
+
image = frame.to_ndarray(format="bgr24")
|
97 |
+
|
98 |
+
# Run inference
|
99 |
+
blob = cv2.dnn.blobFromImage(
|
100 |
+
cv2.resize(image, (300, 300)), 0.007843, (300, 300), 127.5
|
101 |
+
)
|
102 |
+
net.setInput(blob)
|
103 |
+
output = net.forward()
|
104 |
+
|
105 |
+
h, w = image.shape[:2]
|
106 |
+
|
107 |
+
# Convert the output array into a structured form.
|
108 |
+
output = output.squeeze() # (1, 1, N, 7) -> (N, 7)
|
109 |
+
output = output[output[:, 2] >= score_threshold]
|
110 |
+
detections = [
|
111 |
+
Detection(
|
112 |
+
class_id=int(detection[1]),
|
113 |
+
label=CLASSES[int(detection[1])],
|
114 |
+
score=float(detection[2]),
|
115 |
+
box=(detection[3:7] * np.array([w, h, w, h])),
|
116 |
+
)
|
117 |
+
for detection in output
|
118 |
+
]
|
119 |
+
|
120 |
+
# Render bounding boxes and captions
|
121 |
+
for detection in detections:
|
122 |
+
caption = f"{detection.label}: {round(detection.score * 100, 2)}%"
|
123 |
+
color = COLORS[detection.class_id]
|
124 |
+
xmin, ymin, xmax, ymax = detection.box.astype("int")
|
125 |
+
|
126 |
+
cv2.rectangle(image, (xmin, ymin), (xmax, ymax), color, 2)
|
127 |
+
cv2.putText(
|
128 |
+
image,
|
129 |
+
caption,
|
130 |
+
(xmin, ymin - 15 if ymin - 15 > 15 else ymin + 15),
|
131 |
+
cv2.FONT_HERSHEY_SIMPLEX,
|
132 |
+
0.5,
|
133 |
+
color,
|
134 |
+
2,
|
135 |
+
)
|
136 |
+
|
137 |
+
result_queue.put(detections)
|
138 |
+
|
139 |
+
return av.VideoFrame.from_ndarray(image, format="bgr24")
|
140 |
+
|
141 |
+
|
142 |
+
webrtc_ctx = webrtc_streamer(
|
143 |
+
key="object-detection",
|
144 |
+
mode=WebRtcMode.SENDRECV,
|
145 |
+
rtc_configuration={
|
146 |
+
"iceServers": get_ice_servers(),
|
147 |
+
"iceTransportPolicy": "relay",
|
148 |
+
},
|
149 |
+
video_frame_callback=video_frame_callback,
|
150 |
+
media_stream_constraints={"video": True, "audio": False},
|
151 |
+
async_processing=True,
|
152 |
+
)
|
153 |
+
|
154 |
+
if st.checkbox("Show the detected labels", value=True):
|
155 |
+
if webrtc_ctx.state.playing:
|
156 |
+
labels_placeholder = st.empty()
|
157 |
+
# NOTE: The video transformation with object detection and
|
158 |
+
# this loop displaying the result labels are running
|
159 |
+
# in different threads asynchronously.
|
160 |
+
# Then the rendered video frames and the labels displayed here
|
161 |
+
# are not strictly synchronized.
|
162 |
+
while True:
|
163 |
+
result = result_queue.get()
|
164 |
+
labels_placeholder.table(result)
|
165 |
+
|
166 |
+
st.markdown(
|
167 |
+
"This demo uses a model and code from "
|
168 |
+
"https://github.com/robmarkcole/object-detection-app. "
|
169 |
+
"Many thanks to the project."
|
170 |
+
)
|
voc_eval.py
ADDED
@@ -0,0 +1,198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# --------------------------------------------------------
|
2 |
+
# Fast/er R-CNN
|
3 |
+
# Licensed under The MIT License [see LICENSE for details]
|
4 |
+
# Written by Bharath Hariharan
|
5 |
+
# --------------------------------------------------------
|
6 |
+
|
7 |
+
import xml.etree.ElementTree as ET
|
8 |
+
import os
|
9 |
+
import _pickle as cPickle
|
10 |
+
import numpy as np
|
11 |
+
|
12 |
+
def parse_rec(filename):
|
13 |
+
""" Parse a PASCAL VOC xml file """
|
14 |
+
tree = ET.parse(filename)
|
15 |
+
objects = []
|
16 |
+
for obj in tree.findall('object'):
|
17 |
+
obj_struct = {}
|
18 |
+
obj_struct['name'] = obj.find('name').text
|
19 |
+
obj_struct['pose'] = obj.find('pose').text
|
20 |
+
obj_struct['truncated'] = int(obj.find('truncated').text)
|
21 |
+
obj_struct['difficult'] = int(obj.find('difficult').text)
|
22 |
+
bbox = obj.find('bndbox')
|
23 |
+
obj_struct['bbox'] = [int(bbox.find('xmin').text),
|
24 |
+
int(bbox.find('ymin').text),
|
25 |
+
int(bbox.find('xmax').text),
|
26 |
+
int(bbox.find('ymax').text)]
|
27 |
+
objects.append(obj_struct)
|
28 |
+
|
29 |
+
return objects
|
30 |
+
|
31 |
+
def voc_ap(rec, prec, use_07_metric=False):
|
32 |
+
""" ap = voc_ap(rec, prec, [use_07_metric])
|
33 |
+
Compute VOC AP given precision and recall.
|
34 |
+
If use_07_metric is true, uses the
|
35 |
+
VOC 07 11 point method (default:False).
|
36 |
+
"""
|
37 |
+
if use_07_metric:
|
38 |
+
# 11 point metric
|
39 |
+
ap = 0.
|
40 |
+
for t in np.arange(0., 1.1, 0.1):
|
41 |
+
if np.sum(rec >= t) == 0:
|
42 |
+
p = 0
|
43 |
+
else:
|
44 |
+
p = np.max(prec[rec >= t])
|
45 |
+
ap = ap + p / 11.
|
46 |
+
else:
|
47 |
+
# correct AP calculation
|
48 |
+
# first append sentinel values at the end
|
49 |
+
mrec = np.concatenate(([0.], rec, [1.]))
|
50 |
+
mpre = np.concatenate(([0.], prec, [0.]))
|
51 |
+
|
52 |
+
# compute the precision envelope
|
53 |
+
for i in range(mpre.size - 1, 0, -1):
|
54 |
+
mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])
|
55 |
+
|
56 |
+
# to calculate area under PR curve, look for points
|
57 |
+
# where X axis (recall) changes value
|
58 |
+
i = np.where(mrec[1:] != mrec[:-1])[0]
|
59 |
+
|
60 |
+
# and sum (\Delta recall) * prec
|
61 |
+
ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
|
62 |
+
return ap
|
63 |
+
|
64 |
+
def voc_eval(detpath,
|
65 |
+
annopath,
|
66 |
+
imagesetfile,
|
67 |
+
classname,
|
68 |
+
cachedir,
|
69 |
+
ovthresh=0.5,
|
70 |
+
use_07_metric=False):
|
71 |
+
"""rec, prec, ap = voc_eval(detpath,
|
72 |
+
annopath,
|
73 |
+
imagesetfile,
|
74 |
+
classname,
|
75 |
+
[ovthresh],
|
76 |
+
[use_07_metric])
|
77 |
+
Top level function that does the PASCAL VOC evaluation.
|
78 |
+
detpath: Path to detections
|
79 |
+
detpath.format(classname) should produce the detection results file.
|
80 |
+
annopath: Path to annotations
|
81 |
+
annopath.format(imagename) should be the xml annotations file.
|
82 |
+
imagesetfile: Text file containing the list of images, one image per line.
|
83 |
+
classname: Category name (duh)
|
84 |
+
cachedir: Directory for caching the annotations
|
85 |
+
[ovthresh]: Overlap threshold (default = 0.5)
|
86 |
+
[use_07_metric]: Whether to use VOC07's 11 point AP computation
|
87 |
+
(default False)
|
88 |
+
"""
|
89 |
+
# assumes detections are in detpath.format(classname)
|
90 |
+
# assumes annotations are in annopath.format(imagename)
|
91 |
+
# assumes imagesetfile is a text file with each line an image name
|
92 |
+
# cachedir caches the annotations in a pickle file
|
93 |
+
|
94 |
+
# first load gt
|
95 |
+
if not os.path.isdir(cachedir):
|
96 |
+
os.mkdir(cachedir)
|
97 |
+
cachefile = os.path.join(cachedir, 'annots.pkl')
|
98 |
+
# read list of images
|
99 |
+
with open(imagesetfile, 'r') as f:
|
100 |
+
lines = f.readlines()
|
101 |
+
imagenames = [x.strip() for x in lines]
|
102 |
+
|
103 |
+
if not os.path.isfile(cachefile):
|
104 |
+
# load annots
|
105 |
+
recs = {}
|
106 |
+
for i, imagename in enumerate(imagenames):
|
107 |
+
recs[imagename] = parse_rec(annopath.format(imagename))
|
108 |
+
if i % 100 == 0:
|
109 |
+
print('Reading annotation for {:d}/{:d}'.format(
|
110 |
+
i + 1, len(imagenames)))
|
111 |
+
# save
|
112 |
+
print('Saving cached annotations to {:s}'.format(cachefile))
|
113 |
+
with open(cachefile, 'wb') as f:
|
114 |
+
cPickle.dump(recs, f)
|
115 |
+
else:
|
116 |
+
# load
|
117 |
+
with open(cachefile, 'rb') as f:
|
118 |
+
recs = cPickle.load(f)
|
119 |
+
|
120 |
+
# extract gt objects for this class
|
121 |
+
class_recs = {}
|
122 |
+
npos = 0
|
123 |
+
for imagename in imagenames:
|
124 |
+
R = [obj for obj in recs[imagename] if obj['name'] == classname]
|
125 |
+
bbox = np.array([x['bbox'] for x in R])
|
126 |
+
difficult = np.array([x['difficult'] for x in R]).astype(np.bool_)
|
127 |
+
det = [False] * len(R)
|
128 |
+
npos = npos + sum(~difficult)
|
129 |
+
class_recs[imagename] = {'bbox': bbox,
|
130 |
+
'difficult': difficult,
|
131 |
+
'det': det}
|
132 |
+
|
133 |
+
# read dets
|
134 |
+
detfile = detpath.format(classname)
|
135 |
+
with open(detfile, 'r') as f:
|
136 |
+
lines = f.readlines()
|
137 |
+
|
138 |
+
splitlines = [x.strip().split(' ') for x in lines]
|
139 |
+
image_ids = [x[0] for x in splitlines]
|
140 |
+
confidence = np.array([float(x[1]) for x in splitlines])
|
141 |
+
BB = np.array([[float(z) for z in x[2:]] for x in splitlines])
|
142 |
+
|
143 |
+
# sort by confidence
|
144 |
+
sorted_ind = np.argsort(-confidence)
|
145 |
+
sorted_scores = np.sort(-confidence)
|
146 |
+
BB = BB[sorted_ind, :]
|
147 |
+
image_ids = [image_ids[x] for x in sorted_ind]
|
148 |
+
|
149 |
+
# go down dets and mark TPs and FPs
|
150 |
+
nd = len(image_ids)
|
151 |
+
tp = np.zeros(nd)
|
152 |
+
fp = np.zeros(nd)
|
153 |
+
for d in range(nd):
|
154 |
+
R = class_recs[image_ids[d]]
|
155 |
+
bb = BB[d, :].astype(float)
|
156 |
+
ovmax = -np.inf
|
157 |
+
BBGT = R['bbox'].astype(float)
|
158 |
+
|
159 |
+
if BBGT.size > 0:
|
160 |
+
# compute overlaps
|
161 |
+
# intersection
|
162 |
+
ixmin = np.maximum(BBGT[:, 0], bb[0])
|
163 |
+
iymin = np.maximum(BBGT[:, 1], bb[1])
|
164 |
+
ixmax = np.minimum(BBGT[:, 2], bb[2])
|
165 |
+
iymax = np.minimum(BBGT[:, 3], bb[3])
|
166 |
+
iw = np.maximum(ixmax - ixmin + 1., 0.)
|
167 |
+
ih = np.maximum(iymax - iymin + 1., 0.)
|
168 |
+
inters = iw * ih
|
169 |
+
|
170 |
+
# union
|
171 |
+
uni = ((bb[2] - bb[0] + 1.) * (bb[3] - bb[1] + 1.) +
|
172 |
+
(BBGT[:, 2] - BBGT[:, 0] + 1.) *
|
173 |
+
(BBGT[:, 3] - BBGT[:, 1] + 1.) - inters)
|
174 |
+
|
175 |
+
overlaps = inters / uni
|
176 |
+
ovmax = np.max(overlaps)
|
177 |
+
jmax = np.argmax(overlaps)
|
178 |
+
|
179 |
+
if ovmax > ovthresh:
|
180 |
+
if not R['difficult'][jmax]:
|
181 |
+
if not R['det'][jmax]:
|
182 |
+
tp[d] = 1.
|
183 |
+
R['det'][jmax] = 1
|
184 |
+
else:
|
185 |
+
fp[d] = 1.
|
186 |
+
else:
|
187 |
+
fp[d] = 1.
|
188 |
+
|
189 |
+
# compute precision recall
|
190 |
+
fp = np.cumsum(fp)
|
191 |
+
tp = np.cumsum(tp)
|
192 |
+
rec = tp / float(npos)
|
193 |
+
# avoid divide by zero in case the first detection matches a difficult
|
194 |
+
# ground truth
|
195 |
+
prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)
|
196 |
+
ap = voc_ap(rec, prec, use_07_metric)
|
197 |
+
|
198 |
+
return rec, prec, ap
|