Spaces:
Running
on
Zero
Running
on
Zero
iljung1106
commited on
Commit
·
81d425d
1
Parent(s):
1fa8e41
Add bundled model + prototypes (LFS) and Gradio app
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +0 -34
- LICENSE +674 -0
- README.md +9 -8
- THIRD_PARTY_NOTICES.md +13 -0
- anime-eyes-cascade.xml +0 -0
- app/__init__.py +3 -0
- app/model_io.py +108 -0
- app/proto_db.py +151 -0
- app/view_extractor.py +345 -0
- checkpoints_style/per_artist_prototypes_90_10_full.pt +3 -0
- checkpoints_style/stage3_epoch24.pt +3 -0
- packages.txt +2 -0
- requirements.txt +12 -0
- webui_gradio.py +446 -0
- yolov5_anime/.dockerignore +215 -0
- yolov5_anime/.gitattributes +2 -0
- yolov5_anime/LICENSE +674 -0
- yolov5_anime/README.md +81 -0
- yolov5_anime/README.txt +2 -0
- yolov5_anime/data/anime.yaml +6 -0
- yolov5_anime/data/coco.yaml +35 -0
- yolov5_anime/data/coco128.yaml +28 -0
- yolov5_anime/data/hyp.finetune.yaml +27 -0
- yolov5_anime/data/hyp.scratch.yaml +27 -0
- yolov5_anime/data/scripts/get_coco.sh +21 -0
- yolov5_anime/data/scripts/get_voc.sh +212 -0
- yolov5_anime/data/voc.yaml +21 -0
- yolov5_anime/detect.py +171 -0
- yolov5_anime/hubconf.py +99 -0
- yolov5_anime/models/__init__.py +0 -0
- yolov5_anime/models/common.py +118 -0
- yolov5_anime/models/experimental.py +145 -0
- yolov5_anime/models/export.py +74 -0
- yolov5_anime/models/hub/yolov3-spp.yaml +51 -0
- yolov5_anime/models/hub/yolov5-fpn.yaml +42 -0
- yolov5_anime/models/hub/yolov5-panet.yaml +48 -0
- yolov5_anime/models/yolo.py +259 -0
- yolov5_anime/models/yolov5l.yaml +48 -0
- yolov5_anime/models/yolov5m.yaml +48 -0
- yolov5_anime/models/yolov5s.yaml +48 -0
- yolov5_anime/models/yolov5x.yaml +48 -0
- yolov5_anime/requirements.txt +21 -0
- yolov5_anime/test.py +292 -0
- yolov5_anime/train.py +516 -0
- yolov5_anime/utils/__init__.py +0 -0
- yolov5_anime/utils/activations.py +69 -0
- yolov5_anime/utils/datasets.py +907 -0
- yolov5_anime/utils/general.py +1284 -0
- yolov5_anime/utils/google_utils.py +107 -0
- yolov5_anime/utils/torch_utils.py +226 -0
.gitattributes
CHANGED
|
@@ -1,35 +1 @@
|
|
| 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 |
-
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
-
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 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 |
*.pt filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
LICENSE
ADDED
|
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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,14 +1,15 @@
|
|
| 1 |
---
|
| 2 |
title: ArtistEmbeddingClassifier
|
| 3 |
-
emoji: 🌖
|
| 4 |
-
colorFrom: purple
|
| 5 |
-
colorTo: yellow
|
| 6 |
sdk: gradio
|
| 7 |
-
|
| 8 |
-
app_file: app.py
|
| 9 |
-
pinned: false
|
| 10 |
license: gpl-3.0
|
| 11 |
-
short_description: Train an artist embedding model from anime images (whole / f
|
| 12 |
---
|
| 13 |
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
title: ArtistEmbeddingClassifier
|
|
|
|
|
|
|
|
|
|
| 3 |
sdk: gradio
|
| 4 |
+
app_file: webui_gradio.py
|
|
|
|
|
|
|
| 5 |
license: gpl-3.0
|
|
|
|
| 6 |
---
|
| 7 |
|
| 8 |
+
### ArtistEmbeddingClassifier (Gradio Space)
|
| 9 |
+
|
| 10 |
+
This Space bundles the model checkpoint + prototype DB and runs the Gradio UI.
|
| 11 |
+
|
| 12 |
+
Notes:
|
| 13 |
+
- This project is GPL-3.0.
|
| 14 |
+
- `yolov5_anime/` is from [zymk9/yolov5_anime](https://github.com/zymk9/yolov5_anime) (GPL-3.0).
|
| 15 |
+
- `anime-eyes-cascade.xml` is from [recette-lemon/Haar-Cascade-Anime-Eye-Detector](https://github.com/recette-lemon/Haar-Cascade-Anime-Eye-Detector) (GPL-3.0).
|
THIRD_PARTY_NOTICES.md
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
### Third-party code and assets (GPL-3.0)
|
| 2 |
+
|
| 3 |
+
This repository includes and/or depends on the following GPL-3.0 licensed projects/assets:
|
| 4 |
+
|
| 5 |
+
- **`yolov5_anime/`**: from [`https://github.com/zymk9/yolov5_anime`](https://github.com/zymk9/yolov5_anime)
|
| 6 |
+
License: GPL-3.0 (see `yolov5_anime/LICENSE`)
|
| 7 |
+
|
| 8 |
+
- **`anime-eyes-cascade.xml`**: from [`https://github.com/recette-lemon/Haar-Cascade-Anime-Eye-Detector`](https://github.com/recette-lemon/Haar-Cascade-Anime-Eye-Detector)
|
| 9 |
+
License: GPL-3.0
|
| 10 |
+
|
| 11 |
+
If you redistribute this repository, ensure you comply with GPL-3.0 requirements, including providing the corresponding source and preserving license notices.
|
| 12 |
+
|
| 13 |
+
|
anime-eyes-cascade.xml
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
app/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# App utilities package (model + prototype DB helpers).
|
| 2 |
+
|
| 3 |
+
|
app/model_io.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import Optional, Tuple
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@dataclass(frozen=True)
|
| 11 |
+
class LoadedModel:
|
| 12 |
+
model: torch.nn.Module
|
| 13 |
+
device: torch.device
|
| 14 |
+
stage_i: int
|
| 15 |
+
embed_dim: int
|
| 16 |
+
T_w: object
|
| 17 |
+
T_f: object
|
| 18 |
+
T_e: object
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _pick_device(device: str) -> torch.device:
|
| 22 |
+
if device.strip().lower() == "cpu":
|
| 23 |
+
return torch.device("cpu")
|
| 24 |
+
if torch.cuda.is_available():
|
| 25 |
+
return torch.device("cuda")
|
| 26 |
+
return torch.device("cpu")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def load_style_model(
|
| 30 |
+
ckpt_path: str | Path,
|
| 31 |
+
*,
|
| 32 |
+
device: str = "auto",
|
| 33 |
+
) -> LoadedModel:
|
| 34 |
+
"""
|
| 35 |
+
Loads `train_style_ddp.TriViewStyleNet` from a checkpoint saved by `train_style_ddp.py`.
|
| 36 |
+
Returns the model and deterministic val transforms based on the checkpoint stage.
|
| 37 |
+
"""
|
| 38 |
+
import train_style_ddp as ts
|
| 39 |
+
|
| 40 |
+
ckpt_path = Path(ckpt_path)
|
| 41 |
+
if not ckpt_path.exists():
|
| 42 |
+
raise FileNotFoundError(str(ckpt_path))
|
| 43 |
+
|
| 44 |
+
dev = _pick_device("cpu" if device == "auto" else device)
|
| 45 |
+
if device == "auto":
|
| 46 |
+
dev = _pick_device("cuda" if torch.cuda.is_available() else "cpu")
|
| 47 |
+
|
| 48 |
+
ck = torch.load(str(ckpt_path), map_location="cpu")
|
| 49 |
+
meta = ck.get("meta", {}) if isinstance(ck, dict) else {}
|
| 50 |
+
stage_i = int(meta.get("stage", 1))
|
| 51 |
+
stage_i = max(1, min(stage_i, len(ts.cfg.stages)))
|
| 52 |
+
stage = ts.cfg.stages[stage_i - 1]
|
| 53 |
+
|
| 54 |
+
T_w, T_f, T_e = ts.make_val_transforms(stage["sz_whole"], stage["sz_face"], stage["sz_eyes"])
|
| 55 |
+
|
| 56 |
+
model = ts.TriViewStyleNet(out_dim=ts.cfg.embed_dim, mix_p=ts.cfg.mixstyle_p, share_backbone=True)
|
| 57 |
+
state = ck["model"] if isinstance(ck, dict) and "model" in ck else ck
|
| 58 |
+
model.load_state_dict(state, strict=False)
|
| 59 |
+
model.eval()
|
| 60 |
+
model = model.to(dev)
|
| 61 |
+
try:
|
| 62 |
+
model = model.to(memory_format=torch.channels_last)
|
| 63 |
+
except Exception:
|
| 64 |
+
pass
|
| 65 |
+
|
| 66 |
+
return LoadedModel(
|
| 67 |
+
model=model,
|
| 68 |
+
device=dev,
|
| 69 |
+
stage_i=stage_i,
|
| 70 |
+
embed_dim=int(ts.cfg.embed_dim),
|
| 71 |
+
T_w=T_w,
|
| 72 |
+
T_f=T_f,
|
| 73 |
+
T_e=T_e,
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def embed_triview(
|
| 78 |
+
lm: LoadedModel,
|
| 79 |
+
*,
|
| 80 |
+
whole: Optional[torch.Tensor],
|
| 81 |
+
face: Optional[torch.Tensor],
|
| 82 |
+
eyes: Optional[torch.Tensor],
|
| 83 |
+
) -> torch.Tensor:
|
| 84 |
+
"""
|
| 85 |
+
Computes a single fused embedding for a triview sample.
|
| 86 |
+
Each view tensor must be CHW (already normalized) and will be batched.
|
| 87 |
+
Missing views can be None.
|
| 88 |
+
"""
|
| 89 |
+
if whole is None and face is None and eyes is None:
|
| 90 |
+
raise ValueError("At least one of whole/face/eyes must be provided.")
|
| 91 |
+
|
| 92 |
+
views = {}
|
| 93 |
+
masks = {}
|
| 94 |
+
for k, v in (("whole", whole), ("face", face), ("eyes", eyes)):
|
| 95 |
+
if v is None:
|
| 96 |
+
views[k] = None
|
| 97 |
+
masks[k] = torch.zeros(1, dtype=torch.bool, device=lm.device)
|
| 98 |
+
else:
|
| 99 |
+
vb = v.unsqueeze(0).to(lm.device)
|
| 100 |
+
views[k] = vb
|
| 101 |
+
masks[k] = torch.ones(1, dtype=torch.bool, device=lm.device)
|
| 102 |
+
|
| 103 |
+
with torch.no_grad(), torch.amp.autocast("cuda", dtype=getattr(__import__("train_style_ddp"), "amp_dtype", torch.float16), enabled=(lm.device.type == "cuda")):
|
| 104 |
+
z, _, _ = lm.model(views, masks)
|
| 105 |
+
z = torch.nn.functional.normalize(z.float(), dim=1)
|
| 106 |
+
return z.squeeze(0).detach().c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| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import Dict, List, Optional, Tuple
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@dataclass
|
| 11 |
+
class PrototypeDB:
|
| 12 |
+
centers: torch.Tensor # [N,D] float32
|
| 13 |
+
labels: torch.Tensor # [N] int64
|
| 14 |
+
label_names: List[str] # id -> name
|
| 15 |
+
source_path: Optional[Path] = None
|
| 16 |
+
|
| 17 |
+
@property
|
| 18 |
+
def dim(self) -> int:
|
| 19 |
+
return int(self.centers.shape[1])
|
| 20 |
+
|
| 21 |
+
def id_to_name(self, idx: int) -> str:
|
| 22 |
+
if 0 <= idx < len(self.label_names):
|
| 23 |
+
return self.label_names[idx]
|
| 24 |
+
return str(idx)
|
| 25 |
+
|
| 26 |
+
def ensure_label_id(self, name: str) -> int:
|
| 27 |
+
name = str(name).strip()
|
| 28 |
+
if not name:
|
| 29 |
+
raise ValueError("Empty label name.")
|
| 30 |
+
try:
|
| 31 |
+
i = self.label_names.index(name)
|
| 32 |
+
return int(i)
|
| 33 |
+
except ValueError:
|
| 34 |
+
self.label_names.append(name)
|
| 35 |
+
return len(self.label_names) - 1
|
| 36 |
+
|
| 37 |
+
def add_center(self, label_name: str, center: torch.Tensor) -> int:
|
| 38 |
+
if center.ndim != 1:
|
| 39 |
+
raise ValueError("center must be 1D embedding vector.")
|
| 40 |
+
center = torch.nn.functional.normalize(center.float(), dim=0).view(1, -1)
|
| 41 |
+
lid = self.ensure_label_id(label_name)
|
| 42 |
+
self.centers = torch.cat([self.centers, center], dim=0)
|
| 43 |
+
self.labels = torch.cat([self.labels, torch.tensor([lid], dtype=torch.long)], dim=0)
|
| 44 |
+
return lid
|
| 45 |
+
|
| 46 |
+
def save(self, path: Optional[str | Path] = None) -> Path:
|
| 47 |
+
out = Path(path) if path is not None else self.source_path
|
| 48 |
+
if out is None:
|
| 49 |
+
raise ValueError("No output path specified for saving prototype DB.")
|
| 50 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 51 |
+
torch.save(
|
| 52 |
+
dict(
|
| 53 |
+
centers=self.centers.detach().cpu(),
|
| 54 |
+
labels=self.labels.detach().cpu(),
|
| 55 |
+
label_names=list(self.label_names),
|
| 56 |
+
),
|
| 57 |
+
str(out),
|
| 58 |
+
)
|
| 59 |
+
self.source_path = out
|
| 60 |
+
return out
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _infer_label_names_from_dataset(dataset_root: Path) -> Optional[List[str]]:
|
| 64 |
+
# `train_style_ddp.TriViewDataset` assigns IDs based on sorted directory names under dataset/<artist>.
|
| 65 |
+
if not dataset_root.exists():
|
| 66 |
+
return None
|
| 67 |
+
artists = sorted([p.name for p in dataset_root.iterdir() if p.is_dir()])
|
| 68 |
+
return artists if artists else None
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def load_prototype_db(path: str | Path, *, try_dataset_dir: str | Path = "dataset") -> PrototypeDB:
|
| 72 |
+
p = Path(path)
|
| 73 |
+
if not p.exists():
|
| 74 |
+
raise FileNotFoundError(str(p))
|
| 75 |
+
obj = torch.load(str(p), map_location="cpu")
|
| 76 |
+
if not isinstance(obj, dict) or "centers" not in obj or "labels" not in obj:
|
| 77 |
+
raise ValueError(f"Unsupported prototype file format: {p}")
|
| 78 |
+
|
| 79 |
+
centers = obj["centers"].float()
|
| 80 |
+
labels = obj["labels"].long()
|
| 81 |
+
|
| 82 |
+
label_names = obj.get("label_names")
|
| 83 |
+
if not isinstance(label_names, list) or not all(isinstance(x, str) for x in label_names):
|
| 84 |
+
inferred = _infer_label_names_from_dataset(Path(try_dataset_dir))
|
| 85 |
+
if inferred is None:
|
| 86 |
+
max_id = int(labels.max().item()) if labels.numel() else -1
|
| 87 |
+
label_names = [str(i) for i in range(max_id + 1)]
|
| 88 |
+
else:
|
| 89 |
+
label_names = inferred
|
| 90 |
+
|
| 91 |
+
return PrototypeDB(centers=centers, labels=labels, label_names=label_names, source_path=p)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def topk_predictions(
|
| 95 |
+
db: PrototypeDB,
|
| 96 |
+
z: torch.Tensor,
|
| 97 |
+
*,
|
| 98 |
+
topk: int = 5,
|
| 99 |
+
) -> List[Tuple[str, float]]:
|
| 100 |
+
"""
|
| 101 |
+
Returns [(label_name, score)] sorted by score desc (cosine similarity).
|
| 102 |
+
`z` is 1D embedding (D).
|
| 103 |
+
"""
|
| 104 |
+
if z.ndim != 1:
|
| 105 |
+
raise ValueError("z must be 1D.")
|
| 106 |
+
Z = torch.nn.functional.normalize(z.float(), dim=0).view(1, -1)
|
| 107 |
+
C = torch.nn.functional.normalize(db.centers.float(), dim=1)
|
| 108 |
+
sim = (Z @ C.t()).squeeze(0) # [N]
|
| 109 |
+
k = int(max(1, min(topk, sim.numel()))) if sim.numel() else 0
|
| 110 |
+
if k == 0:
|
| 111 |
+
return []
|
| 112 |
+
vals, idxs = torch.topk(sim, k=k)
|
| 113 |
+
out: List[Tuple[str, float]] = []
|
| 114 |
+
for v, i in zip(vals.tolist(), idxs.tolist()):
|
| 115 |
+
lid = int(db.labels[i].item())
|
| 116 |
+
out.append((db.id_to_name(lid), float(v)))
|
| 117 |
+
return out
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def topk_predictions_unique_labels(
|
| 121 |
+
db: PrototypeDB,
|
| 122 |
+
z: torch.Tensor,
|
| 123 |
+
*,
|
| 124 |
+
topk: int = 5,
|
| 125 |
+
) -> List[Tuple[str, float]]:
|
| 126 |
+
"""
|
| 127 |
+
Like topk_predictions(), but dedupes by label:
|
| 128 |
+
if a label has multiple prototypes, only the highest score is kept.
|
| 129 |
+
"""
|
| 130 |
+
if z.ndim != 1:
|
| 131 |
+
raise ValueError("z must be 1D.")
|
| 132 |
+
Z = torch.nn.functional.normalize(z.float(), dim=0).view(1, -1)
|
| 133 |
+
C = torch.nn.functional.normalize(db.centers.float(), dim=1)
|
| 134 |
+
sim = (Z @ C.t()).squeeze(0) # [N]
|
| 135 |
+
if sim.numel() == 0:
|
| 136 |
+
return []
|
| 137 |
+
|
| 138 |
+
best_by_label: dict[int, float] = {}
|
| 139 |
+
# iterate all prototypes once; keep max per label id
|
| 140 |
+
for i in range(sim.numel()):
|
| 141 |
+
lid = int(db.labels[i].item())
|
| 142 |
+
s = float(sim[i].item())
|
| 143 |
+
prev = best_by_label.get(lid)
|
| 144 |
+
if prev is None or s > prev:
|
| 145 |
+
best_by_label[lid] = s
|
| 146 |
+
|
| 147 |
+
items = sorted(best_by_label.items(), key=lambda kv: kv[1], reverse=True)
|
| 148 |
+
items = items[: max(1, int(topk))]
|
| 149 |
+
return [(db.id_to_name(lid), float(score)) for (lid, score) in items]
|
| 150 |
+
|
| 151 |
+
|
app/view_extractor.py
ADDED
|
@@ -0,0 +1,345 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import itertools
|
| 4 |
+
import sys
|
| 5 |
+
import threading
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Optional, Tuple
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
import torch
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _patch_torch_load_for_old_ckpt() -> None:
|
| 15 |
+
"""
|
| 16 |
+
Matches `anime_face_eye_extract._patch_torch_load_for_old_ckpt()` to load older YOLOv5 checkpoints
|
| 17 |
+
on newer torch versions.
|
| 18 |
+
"""
|
| 19 |
+
import numpy as _np
|
| 20 |
+
|
| 21 |
+
try:
|
| 22 |
+
torch.serialization.add_safe_globals([_np.core.multiarray._reconstruct, _np.ndarray])
|
| 23 |
+
except Exception:
|
| 24 |
+
pass
|
| 25 |
+
|
| 26 |
+
_orig_load = torch.load
|
| 27 |
+
|
| 28 |
+
def _patched_load(*args, **kwargs): # noqa: ANN001
|
| 29 |
+
kwargs.setdefault("weights_only", False)
|
| 30 |
+
return _orig_load(*args, **kwargs)
|
| 31 |
+
|
| 32 |
+
torch.load = _patched_load
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _pre(gray: np.ndarray) -> np.ndarray:
|
| 36 |
+
import cv2
|
| 37 |
+
|
| 38 |
+
gray = cv2.GaussianBlur(gray, (3, 3), 0)
|
| 39 |
+
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
|
| 40 |
+
return clahe.apply(gray)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _expand(box, margin: float, W: int, H: int):
|
| 44 |
+
x1, y1, x2, y2 = box
|
| 45 |
+
cx = (x1 + x2) / 2.0
|
| 46 |
+
cy = (y1 + y2) / 2.0
|
| 47 |
+
w = (x2 - x1) * (1 + margin)
|
| 48 |
+
h = (y2 - y1) * (1 + margin)
|
| 49 |
+
nx1 = int(round(cx - w / 2))
|
| 50 |
+
ny1 = int(round(cy - h / 2))
|
| 51 |
+
nx2 = int(round(cx + w / 2))
|
| 52 |
+
ny2 = int(round(cy + h / 2))
|
| 53 |
+
nx1 = max(0, min(W, nx1))
|
| 54 |
+
ny1 = max(0, min(H, ny1))
|
| 55 |
+
nx2 = max(0, min(W, nx2))
|
| 56 |
+
ny2 = max(0, min(H, ny2))
|
| 57 |
+
return nx1, ny1, nx2, ny2
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _shrink(img: np.ndarray, limit: int):
|
| 61 |
+
import cv2
|
| 62 |
+
|
| 63 |
+
h, w = img.shape[:2]
|
| 64 |
+
m = max(h, w)
|
| 65 |
+
if m <= limit:
|
| 66 |
+
return img, 1.0
|
| 67 |
+
s = limit / float(m)
|
| 68 |
+
nh, nw = int(h * s), int(w * s)
|
| 69 |
+
small = cv2.resize(img, (nw, nh), interpolation=cv2.INTER_AREA)
|
| 70 |
+
return small, s
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _best_pair(boxes, W: int, H: int):
|
| 74 |
+
clean = [(int(b[0]), int(b[1]), int(b[2]), int(b[3])) for b in boxes]
|
| 75 |
+
if len(clean) < 2:
|
| 76 |
+
return []
|
| 77 |
+
|
| 78 |
+
def cxcy(b):
|
| 79 |
+
x1, y1, x2, y2 = b
|
| 80 |
+
return (x1 + x2) / 2.0, (y1 + y2) / 2.0
|
| 81 |
+
|
| 82 |
+
def area(b):
|
| 83 |
+
x1, y1, x2, y2 = b
|
| 84 |
+
return max(1, (x2 - x1) * (y2 - y1))
|
| 85 |
+
|
| 86 |
+
best = None
|
| 87 |
+
best_s = 1e9
|
| 88 |
+
for b1, b2 in itertools.combinations(clean, 2):
|
| 89 |
+
c1x, c1y = cxcy(b1)
|
| 90 |
+
c2x, c2y = cxcy(b2)
|
| 91 |
+
a1, a2 = area(b1), area(b2)
|
| 92 |
+
horiz = 0.0 if c1x < c2x else 0.5
|
| 93 |
+
y_aln = abs(c1y - c2y) / max(1.0, H)
|
| 94 |
+
szsim = abs(a1 - a2) / float(max(a1, a2))
|
| 95 |
+
gap = abs(c2x - c1x) / max(1.0, W)
|
| 96 |
+
if 0.05 <= gap <= 0.5:
|
| 97 |
+
gap_pen = 0.0
|
| 98 |
+
else:
|
| 99 |
+
gap_pen = 0.5 * ((0.5 + abs(gap - 0.05) * 10) if gap < 0.05 else (gap - 0.5) * 2.0)
|
| 100 |
+
mean_y = (c1y + c2y) / 2.0 / max(1.0, H)
|
| 101 |
+
upper = 0.3 * max(0.0, (mean_y - 0.67) * 2.0)
|
| 102 |
+
s = y_aln + szsim + gap_pen + upper + horiz
|
| 103 |
+
if s < best_s:
|
| 104 |
+
best_s = s
|
| 105 |
+
best = (b1, b2)
|
| 106 |
+
|
| 107 |
+
if best is None:
|
| 108 |
+
return []
|
| 109 |
+
b1, b2 = best
|
| 110 |
+
left, right = (b1, b2) if (b1[0] + b1[2]) <= (b2[0] + b2[2]) else (b2, b1)
|
| 111 |
+
return [("left", left), ("right", right)]
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
@dataclass
|
| 115 |
+
class ExtractorCfg:
|
| 116 |
+
yolo_dir: Path
|
| 117 |
+
weights: Path
|
| 118 |
+
cascade: Path
|
| 119 |
+
imgsz: int = 640
|
| 120 |
+
conf: float = 0.5
|
| 121 |
+
iou: float = 0.5
|
| 122 |
+
yolo_device: str = "cpu" # "cpu" or "0"
|
| 123 |
+
eye_roi_frac: float = 0.70
|
| 124 |
+
eye_min_size: int = 12
|
| 125 |
+
eye_margin: float = 0.60
|
| 126 |
+
neighbors: int = 9
|
| 127 |
+
eye_downscale_limit_roi: int = 512
|
| 128 |
+
eye_downscale_limit_face: int = 768
|
| 129 |
+
eye_fallback_to_face: bool = True
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class AnimeFaceEyeExtractor:
|
| 133 |
+
"""
|
| 134 |
+
Single-image view extractor (whole -> face crop, eyes crop) based on `anime_face_eye_extract.py`.
|
| 135 |
+
Designed for use in the Gradio UI: caches YOLO model + Haar cascade.
|
| 136 |
+
"""
|
| 137 |
+
|
| 138 |
+
def __init__(self, cfg: ExtractorCfg):
|
| 139 |
+
self.cfg = cfg
|
| 140 |
+
self._model = None
|
| 141 |
+
self._device = None
|
| 142 |
+
self._stride = 32
|
| 143 |
+
self._tl = threading.local()
|
| 144 |
+
|
| 145 |
+
def _init_detector(self) -> None:
|
| 146 |
+
if self._model is not None:
|
| 147 |
+
return
|
| 148 |
+
|
| 149 |
+
ydir = self.cfg.yolo_dir.resolve()
|
| 150 |
+
if not ydir.exists():
|
| 151 |
+
raise RuntimeError(f"yolov5_anime dir not found: {ydir}")
|
| 152 |
+
if str(ydir) not in sys.path:
|
| 153 |
+
sys.path.insert(0, str(ydir))
|
| 154 |
+
|
| 155 |
+
_patch_torch_load_for_old_ckpt()
|
| 156 |
+
|
| 157 |
+
from models.experimental import attempt_load
|
| 158 |
+
from utils.torch_utils import select_device
|
| 159 |
+
|
| 160 |
+
self._device = select_device(self.cfg.yolo_device)
|
| 161 |
+
self._model = attempt_load(str(self.cfg.weights), map_location=self._device)
|
| 162 |
+
self._model.eval()
|
| 163 |
+
|
| 164 |
+
self._stride = int(self._model.stride.max())
|
| 165 |
+
s = int(self.cfg.imgsz)
|
| 166 |
+
s = int(np.ceil(s / self._stride) * self._stride)
|
| 167 |
+
self.cfg.imgsz = s
|
| 168 |
+
|
| 169 |
+
def _letterbox_compat(self, img0, new_shape, stride):
|
| 170 |
+
from utils.datasets import letterbox
|
| 171 |
+
try:
|
| 172 |
+
lb = letterbox(img0, new_shape, stride=stride, auto=False)
|
| 173 |
+
except TypeError:
|
| 174 |
+
try:
|
| 175 |
+
lb = letterbox(img0, new_shape, auto=False)
|
| 176 |
+
except TypeError:
|
| 177 |
+
lb = letterbox(img0, new_shape)
|
| 178 |
+
return lb[0]
|
| 179 |
+
|
| 180 |
+
def _detect_faces(self, rgb: np.ndarray):
|
| 181 |
+
import cv2
|
| 182 |
+
self._init_detector()
|
| 183 |
+
from utils.general import non_max_suppression, scale_coords
|
| 184 |
+
|
| 185 |
+
img0 = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)
|
| 186 |
+
h0, w0, _ = img0.shape
|
| 187 |
+
img = self._letterbox_compat(img0, self.cfg.imgsz, self._stride)
|
| 188 |
+
img = img[:, :, ::-1].transpose(2, 0, 1)
|
| 189 |
+
img = np.ascontiguousarray(img)
|
| 190 |
+
|
| 191 |
+
im = torch.from_numpy(img).to(self._device)
|
| 192 |
+
im = im.float() / 255.0
|
| 193 |
+
if im.ndim == 3:
|
| 194 |
+
im = im[None]
|
| 195 |
+
|
| 196 |
+
with torch.no_grad():
|
| 197 |
+
pred = self._model(im)[0]
|
| 198 |
+
pred = non_max_suppression(pred, conf_thres=self.cfg.conf, iou_thres=self.cfg.iou, classes=None, agnostic=False)
|
| 199 |
+
|
| 200 |
+
boxes = []
|
| 201 |
+
det = pred[0]
|
| 202 |
+
if det is not None and len(det):
|
| 203 |
+
det[:, :4] = scale_coords((self.cfg.imgsz, self.cfg.imgsz), det[:, :4], (h0, w0)).round()
|
| 204 |
+
for *xyxy, conf, cls in det.tolist():
|
| 205 |
+
x1, y1, x2, y2 = [int(v) for v in xyxy]
|
| 206 |
+
boxes.append((x1, y1, x2, y2))
|
| 207 |
+
return boxes
|
| 208 |
+
|
| 209 |
+
def _get_cascade(self):
|
| 210 |
+
import cv2
|
| 211 |
+
|
| 212 |
+
c = getattr(self._tl, "cascade", None)
|
| 213 |
+
if c is None:
|
| 214 |
+
c = cv2.CascadeClassifier(str(self.cfg.cascade))
|
| 215 |
+
if c.empty():
|
| 216 |
+
raise RuntimeError(f"cascade load fail: {self.cfg.cascade}")
|
| 217 |
+
self._tl.cascade = c
|
| 218 |
+
return c
|
| 219 |
+
|
| 220 |
+
def _detect_eyes_in_roi(self, rgb_roi: np.ndarray):
|
| 221 |
+
import cv2
|
| 222 |
+
|
| 223 |
+
gray = cv2.cvtColor(rgb_roi, cv2.COLOR_RGB2GRAY)
|
| 224 |
+
proc = _pre(gray)
|
| 225 |
+
H, W = proc.shape[:2]
|
| 226 |
+
min_side = max(1, min(W, H))
|
| 227 |
+
dyn_min = int(0.07 * min_side)
|
| 228 |
+
min_sz = max(8, int(self.cfg.eye_min_size), dyn_min)
|
| 229 |
+
|
| 230 |
+
cascade = self._get_cascade()
|
| 231 |
+
raw = cascade.detectMultiScale(
|
| 232 |
+
proc,
|
| 233 |
+
scaleFactor=1.15,
|
| 234 |
+
minNeighbors=int(self.cfg.neighbors),
|
| 235 |
+
minSize=(min_sz, min_sz),
|
| 236 |
+
flags=cv2.CASCADE_SCALE_IMAGE,
|
| 237 |
+
)
|
| 238 |
+
try:
|
| 239 |
+
arr = np.asarray(raw if not isinstance(raw, tuple) else raw[0])
|
| 240 |
+
except Exception:
|
| 241 |
+
arr = np.empty((0, 4), dtype=int)
|
| 242 |
+
if arr.size == 0:
|
| 243 |
+
return []
|
| 244 |
+
if arr.ndim == 1:
|
| 245 |
+
arr = arr.reshape(1, -1)
|
| 246 |
+
|
| 247 |
+
boxes = []
|
| 248 |
+
for r in arr:
|
| 249 |
+
x, y, w, h = [int(v) for v in r[:4]]
|
| 250 |
+
if w <= 0 or h <= 0:
|
| 251 |
+
continue
|
| 252 |
+
boxes.append((x, y, x + w, y + h))
|
| 253 |
+
return boxes
|
| 254 |
+
|
| 255 |
+
@staticmethod
|
| 256 |
+
def _pick_best_face(boxes):
|
| 257 |
+
if not boxes:
|
| 258 |
+
return None
|
| 259 |
+
# choose largest-area face
|
| 260 |
+
def area(b):
|
| 261 |
+
x1, y1, x2, y2 = b
|
| 262 |
+
return max(1, (x2 - x1) * (y2 - y1))
|
| 263 |
+
|
| 264 |
+
return max(boxes, key=area)
|
| 265 |
+
|
| 266 |
+
def extract(self, whole_rgb: np.ndarray) -> Tuple[Optional[np.ndarray], Optional[np.ndarray]]:
|
| 267 |
+
"""
|
| 268 |
+
Args:
|
| 269 |
+
whole_rgb: HWC RGB uint8
|
| 270 |
+
Returns:
|
| 271 |
+
(face_rgb, eyes_rgb) as RGB uint8 crops (or None if not found)
|
| 272 |
+
"""
|
| 273 |
+
import cv2
|
| 274 |
+
|
| 275 |
+
boxes = self._detect_faces(whole_rgb)
|
| 276 |
+
face_box = self._pick_best_face(boxes)
|
| 277 |
+
if face_box is None:
|
| 278 |
+
return None, None
|
| 279 |
+
|
| 280 |
+
x1, y1, x2, y2 = face_box
|
| 281 |
+
H0, W0 = whole_rgb.shape[:2]
|
| 282 |
+
x1 = max(0, min(W0, x1))
|
| 283 |
+
x2 = max(0, min(W0, x2))
|
| 284 |
+
y1 = max(0, min(H0, y1))
|
| 285 |
+
y2 = max(0, min(H0, y2))
|
| 286 |
+
if x2 <= x1 or y2 <= y1:
|
| 287 |
+
return None, None
|
| 288 |
+
|
| 289 |
+
face = whole_rgb[y1:y2, x1:x2].copy()
|
| 290 |
+
|
| 291 |
+
# eye detection on upper ROI
|
| 292 |
+
H, W = face.shape[:2]
|
| 293 |
+
roi_h = int(H * float(self.cfg.eye_roi_frac))
|
| 294 |
+
roi = face[0: max(1, roi_h), :]
|
| 295 |
+
|
| 296 |
+
roi_small, s_roi = _shrink(roi, int(self.cfg.eye_downscale_limit_roi))
|
| 297 |
+
face_small, s_face = _shrink(face, int(self.cfg.eye_downscale_limit_face))
|
| 298 |
+
|
| 299 |
+
eyes_roi = self._detect_eyes_in_roi(roi_small)
|
| 300 |
+
eyes_roi = [(int(a / s_roi), int(b / s_roi), int(c / s_roi), int(d / s_roi)) for (a, b, c, d) in eyes_roi]
|
| 301 |
+
labs = _best_pair(eyes_roi, W, roi.shape[0])
|
| 302 |
+
origin = "roi" if labs else None
|
| 303 |
+
|
| 304 |
+
eyes_full = []
|
| 305 |
+
if self.cfg.eye_fallback_to_face and (not labs):
|
| 306 |
+
eyes_full = self._detect_eyes_in_roi(face_small)
|
| 307 |
+
eyes_full = [(int(a / s_face), int(b / s_face), int(c / s_face), int(d / s_face)) for (a, b, c, d) in eyes_full]
|
| 308 |
+
if len(eyes_full) >= 2:
|
| 309 |
+
labs = _best_pair(eyes_full, W, H)
|
| 310 |
+
origin = "face" if labs else origin
|
| 311 |
+
|
| 312 |
+
if not labs:
|
| 313 |
+
cand = eyes_roi
|
| 314 |
+
cand_origin = "roi"
|
| 315 |
+
if self.cfg.eye_fallback_to_face and len(eyes_full) >= 1:
|
| 316 |
+
cand = eyes_full
|
| 317 |
+
cand_origin = "face"
|
| 318 |
+
if len(cand) >= 2:
|
| 319 |
+
top2 = sorted(cand, key=lambda b: (b[2] - b[0]) * (b[3] - b[1]), reverse=True)[:2]
|
| 320 |
+
top2 = sorted(top2, key=lambda b: (b[0] + b[2]))
|
| 321 |
+
labs = [("left", top2[0]), ("right", top2[1])]
|
| 322 |
+
origin = cand_origin
|
| 323 |
+
elif len(cand) == 1:
|
| 324 |
+
labs = [("left", cand[0])]
|
| 325 |
+
origin = cand_origin
|
| 326 |
+
|
| 327 |
+
eyes_crop = None
|
| 328 |
+
if labs:
|
| 329 |
+
src_img = roi if origin == "roi" else face
|
| 330 |
+
bound_h = roi.shape[0] if origin == "roi" else H
|
| 331 |
+
|
| 332 |
+
boxes_only = [b for _, b in labs]
|
| 333 |
+
# union of eye boxes -> single eyes crop (works for the "eyes" view encoder)
|
| 334 |
+
ux1 = min(b[0] for b in boxes_only)
|
| 335 |
+
uy1 = min(b[1] for b in boxes_only)
|
| 336 |
+
ux2 = max(b[2] for b in boxes_only)
|
| 337 |
+
uy2 = max(b[3] for b in boxes_only)
|
| 338 |
+
ex1, ey1, ex2, ey2 = _expand((ux1, uy1, ux2, uy2), float(self.cfg.eye_margin), W, bound_h)
|
| 339 |
+
crop = src_img[ey1:ey2, ex1:ex2]
|
| 340 |
+
if crop.size > 0 and min(crop.shape[0], crop.shape[1]) >= int(self.cfg.eye_min_size):
|
| 341 |
+
eyes_crop = crop.copy()
|
| 342 |
+
|
| 343 |
+
return face, eyes_crop
|
| 344 |
+
|
| 345 |
+
|
checkpoints_style/per_artist_prototypes_90_10_full.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:24476540fe0a5b4a169f52cc0c89842921ed133efdd3f5ea161cc6cad98ca7f9
|
| 3 |
+
size 8124525
|
checkpoints_style/stage3_epoch24.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:62ce08323ed10bb27acf42db4a8821f22ba5676a1a844a481513c8e68ea55e65
|
| 3 |
+
size 60103197
|
packages.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
libgl1
|
| 2 |
+
libglib2.0-0
|
requirements.txt
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
numpy>=1.25.2,<2
|
| 2 |
+
pillow
|
| 3 |
+
pyyaml
|
| 4 |
+
tqdm
|
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import os
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import List, Optional, Tuple
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
from PIL import Image
|
| 12 |
+
|
| 13 |
+
def _patch_fastapi_starlette_middleware_unpack() -> None:
|
| 14 |
+
"""
|
| 15 |
+
Work around FastAPI/Starlette version mismatches where Starlette's Middleware
|
| 16 |
+
iterates as (cls, args, kwargs) but FastAPI expects (cls, options).
|
| 17 |
+
|
| 18 |
+
The user reported: ValueError: too many values to unpack (expected 2)
|
| 19 |
+
in fastapi.applications.FastAPI.build_middleware_stack.
|
| 20 |
+
"""
|
| 21 |
+
try:
|
| 22 |
+
import fastapi.applications as fa
|
| 23 |
+
from starlette.middleware import Middleware as StarletteMiddleware
|
| 24 |
+
except Exception:
|
| 25 |
+
return
|
| 26 |
+
|
| 27 |
+
# Idempotent: don't patch multiple times.
|
| 28 |
+
if getattr(fa.FastAPI.build_middleware_stack, "_aec_patched", False):
|
| 29 |
+
return
|
| 30 |
+
|
| 31 |
+
orig = fa.FastAPI.build_middleware_stack
|
| 32 |
+
|
| 33 |
+
def patched_build_middleware_stack(self): # noqa: ANN001
|
| 34 |
+
# Mostly copied from FastAPI, but with robust handling of Middleware objects.
|
| 35 |
+
debug = self.debug
|
| 36 |
+
error_handler = None
|
| 37 |
+
exception_handlers = {}
|
| 38 |
+
if self.exception_handlers:
|
| 39 |
+
exception_handlers = self.exception_handlers
|
| 40 |
+
error_handler = exception_handlers.get(500) or exception_handlers.get(Exception)
|
| 41 |
+
|
| 42 |
+
from starlette.middleware.errors import ServerErrorMiddleware
|
| 43 |
+
from starlette.middleware.exceptions import ExceptionMiddleware
|
| 44 |
+
from fastapi.middleware.asyncexitstack import AsyncExitStackMiddleware
|
| 45 |
+
|
| 46 |
+
middleware = (
|
| 47 |
+
[StarletteMiddleware(ServerErrorMiddleware, handler=error_handler, debug=debug)]
|
| 48 |
+
+ self.user_middleware
|
| 49 |
+
+ [
|
| 50 |
+
StarletteMiddleware(ExceptionMiddleware, handlers=exception_handlers, debug=debug),
|
| 51 |
+
StarletteMiddleware(AsyncExitStackMiddleware),
|
| 52 |
+
]
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
app = self.router
|
| 56 |
+
for m in reversed(middleware):
|
| 57 |
+
# Starlette Middleware object
|
| 58 |
+
if hasattr(m, "cls") and hasattr(m, "args") and hasattr(m, "kwargs"):
|
| 59 |
+
app = m.cls(app=app, *list(m.args), **dict(m.kwargs))
|
| 60 |
+
continue
|
| 61 |
+
|
| 62 |
+
# Old-style tuple/list
|
| 63 |
+
if isinstance(m, (tuple, list)):
|
| 64 |
+
if len(m) == 2:
|
| 65 |
+
cls, options = m
|
| 66 |
+
app = cls(app=app, **options)
|
| 67 |
+
continue
|
| 68 |
+
if len(m) == 3:
|
| 69 |
+
cls, args, kwargs = m
|
| 70 |
+
app = cls(app=app, *list(args), **dict(kwargs))
|
| 71 |
+
continue
|
| 72 |
+
|
| 73 |
+
# Fallback to original behavior for unexpected types
|
| 74 |
+
return orig(self)
|
| 75 |
+
|
| 76 |
+
return app
|
| 77 |
+
|
| 78 |
+
patched_build_middleware_stack._aec_patched = True # type: ignore[attr-defined]
|
| 79 |
+
fa.FastAPI.build_middleware_stack = patched_build_middleware_stack
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
_patch_fastapi_starlette_middleware_unpack()
|
| 83 |
+
|
| 84 |
+
import gradio as gr
|
| 85 |
+
|
| 86 |
+
def _patch_gradio_client_bool_jsonschema() -> None:
|
| 87 |
+
"""
|
| 88 |
+
Work around gradio_client JSON-schema parsing bug where it assumes schema is a dict,
|
| 89 |
+
but JSON Schema allows booleans for additionalProperties (true/false).
|
| 90 |
+
|
| 91 |
+
Error seen:
|
| 92 |
+
TypeError: argument of type 'bool' is not iterable
|
| 93 |
+
in gradio_client/utils.py:get_type -> if "const" in schema:
|
| 94 |
+
"""
|
| 95 |
+
try:
|
| 96 |
+
import gradio_client.utils as gcu
|
| 97 |
+
except Exception:
|
| 98 |
+
return
|
| 99 |
+
|
| 100 |
+
# Idempotent: patch once.
|
| 101 |
+
if getattr(getattr(gcu, "get_type", None), "_aec_patched", False):
|
| 102 |
+
return
|
| 103 |
+
|
| 104 |
+
orig_get_type = gcu.get_type
|
| 105 |
+
|
| 106 |
+
def patched_get_type(schema): # noqa: ANN001
|
| 107 |
+
if isinstance(schema, bool):
|
| 108 |
+
# additionalProperties: false/true
|
| 109 |
+
return "object"
|
| 110 |
+
if schema is None:
|
| 111 |
+
return "object"
|
| 112 |
+
if not isinstance(schema, dict):
|
| 113 |
+
return "object"
|
| 114 |
+
return orig_get_type(schema)
|
| 115 |
+
|
| 116 |
+
patched_get_type._aec_patched = True # type: ignore[attr-defined]
|
| 117 |
+
gcu.get_type = patched_get_type
|
| 118 |
+
|
| 119 |
+
# Also patch the deeper helper that assumes schema is always a dict.
|
| 120 |
+
orig_inner = getattr(gcu, "_json_schema_to_python_type", None)
|
| 121 |
+
if callable(orig_inner) and not getattr(orig_inner, "_aec_patched", False):
|
| 122 |
+
def patched_inner(schema, defs=None): # noqa: ANN001
|
| 123 |
+
# JSON Schema allows boolean schemas: https://json-schema.org/
|
| 124 |
+
if isinstance(schema, bool):
|
| 125 |
+
return "typing.Any"
|
| 126 |
+
if schema is None:
|
| 127 |
+
return "typing.Any"
|
| 128 |
+
if not isinstance(schema, dict):
|
| 129 |
+
return "typing.Any"
|
| 130 |
+
return orig_inner(schema, defs)
|
| 131 |
+
|
| 132 |
+
patched_inner._aec_patched = True # type: ignore[attr-defined]
|
| 133 |
+
gcu._json_schema_to_python_type = patched_inner
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
_patch_gradio_client_bool_jsonschema()
|
| 137 |
+
|
| 138 |
+
from app.model_io import LoadedModel, embed_triview, load_style_model
|
| 139 |
+
from app.proto_db import PrototypeDB, load_prototype_db, topk_predictions_unique_labels
|
| 140 |
+
from app.view_extractor import AnimeFaceEyeExtractor, ExtractorCfg
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
ROOT = Path(__file__).resolve().parent
|
| 144 |
+
CKPT_DIR = ROOT / "checkpoints_style"
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def _list_pt_files(folder: Path) -> List[str]:
|
| 148 |
+
if not folder.exists():
|
| 149 |
+
return []
|
| 150 |
+
return [str(p) for p in sorted(folder.glob("*.pt"))]
|
| 151 |
+
|
| 152 |
+
def _list_ckpt_files(folder: Path) -> List[str]:
|
| 153 |
+
files = _list_pt_files(folder)
|
| 154 |
+
# heuristics: training checkpoints usually look like "stageX_epochY.pt"
|
| 155 |
+
ckpts = [f for f in files if "stage" in Path(f).name.lower() and "epoch" in Path(f).name.lower()]
|
| 156 |
+
return ckpts if ckpts else files
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def _list_proto_files(folder: Path) -> List[str]:
|
| 160 |
+
files = _list_pt_files(folder)
|
| 161 |
+
# heuristics: prototype db files usually contain "proto" in filename
|
| 162 |
+
protos = [f for f in files if "proto" in Path(f).name.lower()]
|
| 163 |
+
return protos if protos else files
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def _guess_default_ckpt(files: List[str]) -> Optional[str]:
|
| 167 |
+
# prefer stage3_epoch24.pt if present
|
| 168 |
+
for f in files:
|
| 169 |
+
if Path(f).name.lower() == "stage3_epoch24.pt":
|
| 170 |
+
return f
|
| 171 |
+
return files[-1] if files else None
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def _guess_default_proto(files: List[str]) -> Optional[str]:
|
| 175 |
+
# Prefer the strict 90/10 prototype DB if present.
|
| 176 |
+
for f in files:
|
| 177 |
+
if Path(f).name.lower() == "per_artist_prototypes_90_10_full.pt":
|
| 178 |
+
return f
|
| 179 |
+
# Otherwise, try to prefer a file with "proto" in name
|
| 180 |
+
for f in files:
|
| 181 |
+
if "proto" in Path(f).name.lower():
|
| 182 |
+
return f
|
| 183 |
+
return files[0] if files else None
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def _pil_to_tensor(im: Image.Image, T) -> torch.Tensor:
|
| 187 |
+
# `T` is torchvision transform pipeline from train_style_ddp.make_val_transforms
|
| 188 |
+
return T(im.convert("RGB"))
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
@dataclass
|
| 192 |
+
class State:
|
| 193 |
+
lm: Optional[LoadedModel] = None
|
| 194 |
+
ckpt_path: Optional[str] = None
|
| 195 |
+
db: Optional[PrototypeDB] = None
|
| 196 |
+
proto_path: Optional[str] = None
|
| 197 |
+
extractor: Optional[AnimeFaceEyeExtractor] = None
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
APP_STATE = State()
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def load_all(ckpt_path: str, proto_path: str, device: str) -> str:
|
| 204 |
+
if not ckpt_path:
|
| 205 |
+
return "❌ No checkpoint selected."
|
| 206 |
+
if not proto_path:
|
| 207 |
+
return "❌ No prototype DB selected."
|
| 208 |
+
try:
|
| 209 |
+
lm = load_style_model(ckpt_path, device=device)
|
| 210 |
+
db = load_prototype_db(proto_path, try_dataset_dir=str(ROOT / "dataset"))
|
| 211 |
+
except Exception as e:
|
| 212 |
+
return f"❌ Load failed: {e}"
|
| 213 |
+
|
| 214 |
+
if db.dim != lm.embed_dim:
|
| 215 |
+
return f"❌ Dim mismatch: model embed_dim={lm.embed_dim} but prototypes dim={db.dim}"
|
| 216 |
+
|
| 217 |
+
APP_STATE.lm = lm
|
| 218 |
+
APP_STATE.ckpt_path = ckpt_path
|
| 219 |
+
APP_STATE.db = db
|
| 220 |
+
APP_STATE.proto_path = proto_path
|
| 221 |
+
|
| 222 |
+
# initialize view extractor (whole -> face/eyes) with defaults
|
| 223 |
+
try:
|
| 224 |
+
cfg = ExtractorCfg(
|
| 225 |
+
yolo_dir=ROOT / "yolov5_anime",
|
| 226 |
+
weights=ROOT / "yolov5x_anime.pt",
|
| 227 |
+
cascade=ROOT / "anime-eyes-cascade.xml",
|
| 228 |
+
yolo_device=("0" if torch.cuda.is_available() else "cpu"),
|
| 229 |
+
)
|
| 230 |
+
APP_STATE.extractor = AnimeFaceEyeExtractor(cfg)
|
| 231 |
+
except Exception:
|
| 232 |
+
APP_STATE.extractor = None
|
| 233 |
+
|
| 234 |
+
return f"✅ Loaded checkpoint `{Path(ckpt_path).name}` (stage={lm.stage_i}) and proto DB `{Path(proto_path).name}` (N={db.centers.shape[0]})"
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def classify(
|
| 238 |
+
whole_img,
|
| 239 |
+
topk: int,
|
| 240 |
+
):
|
| 241 |
+
"""
|
| 242 |
+
Classify using auto-extracted face/eyes from whole image.
|
| 243 |
+
Returns: status, table_rows, face_preview, eyes_preview
|
| 244 |
+
"""
|
| 245 |
+
if APP_STATE.lm is None or APP_STATE.db is None:
|
| 246 |
+
return "❌ Click **Load** first.", [], None, None
|
| 247 |
+
|
| 248 |
+
lm = APP_STATE.lm
|
| 249 |
+
db = APP_STATE.db
|
| 250 |
+
ex = APP_STATE.extractor
|
| 251 |
+
|
| 252 |
+
def _to_pil(x):
|
| 253 |
+
if x is None:
|
| 254 |
+
return None
|
| 255 |
+
if isinstance(x, Image.Image):
|
| 256 |
+
return x
|
| 257 |
+
return Image.fromarray(x)
|
| 258 |
+
|
| 259 |
+
w = _to_pil(whole_img)
|
| 260 |
+
if w is None:
|
| 261 |
+
return "❌ Provide a whole image.", [], None, None
|
| 262 |
+
|
| 263 |
+
try:
|
| 264 |
+
face_pil = None
|
| 265 |
+
eyes_pil = None
|
| 266 |
+
if ex is not None:
|
| 267 |
+
rgb = np.array(w.convert("RGB"))
|
| 268 |
+
face_rgb, eyes_rgb = ex.extract(rgb)
|
| 269 |
+
if face_rgb is not None:
|
| 270 |
+
face_pil = Image.fromarray(face_rgb)
|
| 271 |
+
if eyes_rgb is not None:
|
| 272 |
+
eyes_pil = Image.fromarray(eyes_rgb)
|
| 273 |
+
|
| 274 |
+
wt = _pil_to_tensor(w, lm.T_w)
|
| 275 |
+
ft = _pil_to_tensor(face_pil, lm.T_f) if face_pil is not None else None
|
| 276 |
+
et = _pil_to_tensor(eyes_pil, lm.T_e) if eyes_pil is not None else None
|
| 277 |
+
z = embed_triview(lm, whole=wt, face=ft, eyes=et)
|
| 278 |
+
preds = topk_predictions_unique_labels(db, z, topk=int(topk))
|
| 279 |
+
except Exception as ex:
|
| 280 |
+
return f"❌ Inference failed: {ex}", [], None, None
|
| 281 |
+
|
| 282 |
+
rows = [[name, float(score)] for (name, score) in preds]
|
| 283 |
+
return "✅ OK", rows, (face_pil if "face_pil" in locals() else None), (eyes_pil if "eyes_pil" in locals() else None)
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def add_prototype(
|
| 287 |
+
label_name: str,
|
| 288 |
+
images: List,
|
| 289 |
+
save_back: bool,
|
| 290 |
+
) -> str:
|
| 291 |
+
if APP_STATE.lm is None or APP_STATE.db is None:
|
| 292 |
+
return "❌ Click **Load** first."
|
| 293 |
+
lm = APP_STATE.lm
|
| 294 |
+
db = APP_STATE.db
|
| 295 |
+
ex = APP_STATE.extractor
|
| 296 |
+
|
| 297 |
+
label_name = (label_name or "").strip()
|
| 298 |
+
if not label_name:
|
| 299 |
+
return "❌ Label name is required."
|
| 300 |
+
if not images:
|
| 301 |
+
return "❌ Upload at least 1 image."
|
| 302 |
+
|
| 303 |
+
zs: List[torch.Tensor] = []
|
| 304 |
+
for x in images:
|
| 305 |
+
try:
|
| 306 |
+
im = x if isinstance(x, Image.Image) else Image.fromarray(x)
|
| 307 |
+
face_pil = None
|
| 308 |
+
eyes_pil = None
|
| 309 |
+
if ex is not None:
|
| 310 |
+
rgb = np.array(im.convert("RGB"))
|
| 311 |
+
face_rgb, eyes_rgb = ex.extract(rgb)
|
| 312 |
+
if face_rgb is not None:
|
| 313 |
+
face_pil = Image.fromarray(face_rgb)
|
| 314 |
+
if eyes_rgb is not None:
|
| 315 |
+
eyes_pil = Image.fromarray(eyes_rgb)
|
| 316 |
+
|
| 317 |
+
wt = _pil_to_tensor(im, lm.T_w)
|
| 318 |
+
ft = _pil_to_tensor(face_pil, lm.T_f) if face_pil is not None else None
|
| 319 |
+
et = _pil_to_tensor(eyes_pil, lm.T_e) if eyes_pil is not None else None
|
| 320 |
+
z = embed_triview(lm, whole=wt, face=ft, eyes=et)
|
| 321 |
+
zs.append(z)
|
| 322 |
+
except Exception:
|
| 323 |
+
continue
|
| 324 |
+
|
| 325 |
+
if not zs:
|
| 326 |
+
return "❌ Could not embed any uploaded images."
|
| 327 |
+
|
| 328 |
+
center = torch.stack(zs, dim=0).mean(dim=0)
|
| 329 |
+
lid = db.add_center(label_name, center)
|
| 330 |
+
|
| 331 |
+
msg = f"✅ Added prototype for `{label_name}` (label_id={lid}). DB now N={db.centers.shape[0]}."
|
| 332 |
+
|
| 333 |
+
if save_back:
|
| 334 |
+
out_path = db.save(APP_STATE.proto_path)
|
| 335 |
+
msg += f" Saved to `{out_path}`."
|
| 336 |
+
return msg
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def save_db_as(path_text: str) -> str:
|
| 340 |
+
if APP_STATE.db is None:
|
| 341 |
+
return "❌ Nothing loaded."
|
| 342 |
+
out = (path_text or "").strip()
|
| 343 |
+
if not out:
|
| 344 |
+
return "❌ Provide an output path."
|
| 345 |
+
out_path = Path(out)
|
| 346 |
+
if not out_path.is_absolute():
|
| 347 |
+
out_path = (CKPT_DIR / out_path).resolve()
|
| 348 |
+
APP_STATE.db.save(out_path)
|
| 349 |
+
APP_STATE.proto_path = str(out_path)
|
| 350 |
+
return f"✅ Saved prototype DB to `{out_path}`"
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def build_ui() -> gr.Blocks:
|
| 354 |
+
ckpts = _list_ckpt_files(CKPT_DIR)
|
| 355 |
+
protos = _list_proto_files(CKPT_DIR)
|
| 356 |
+
|
| 357 |
+
with gr.Blocks(title="ArtistEmbeddingClassifier") as demo:
|
| 358 |
+
gr.Markdown("### ArtistEmbeddingClassifier — Gradio UI\nLoads checkpoint + prototype DB from `./checkpoints_style/`.")
|
| 359 |
+
|
| 360 |
+
with gr.Row():
|
| 361 |
+
ckpt_dd = gr.Dropdown(choices=ckpts, value=_guess_default_ckpt(ckpts), label="Checkpoint (.pt)")
|
| 362 |
+
proto_dd = gr.Dropdown(choices=protos, value=_guess_default_proto(protos), label="Prototype DB (.pt)")
|
| 363 |
+
device_dd = gr.Dropdown(choices=["auto", "cpu"], value="auto", label="Device")
|
| 364 |
+
load_btn = gr.Button("Load", variant="primary")
|
| 365 |
+
|
| 366 |
+
status = gr.Markdown("")
|
| 367 |
+
load_btn.click(load_all, inputs=[ckpt_dd, proto_dd, device_dd], outputs=[status])
|
| 368 |
+
|
| 369 |
+
with gr.Tab("Classify"):
|
| 370 |
+
with gr.Row():
|
| 371 |
+
whole = gr.Image(label="Whole image (required)", type="pil")
|
| 372 |
+
face_prev = gr.Image(label="Extracted face (auto)", type="pil")
|
| 373 |
+
eyes_prev = gr.Image(label="Extracted eyes (auto)", type="pil")
|
| 374 |
+
with gr.Row():
|
| 375 |
+
topk = gr.Slider(1, 20, value=5, step=1, label="Top-K")
|
| 376 |
+
run_btn = gr.Button("Run", variant="primary")
|
| 377 |
+
|
| 378 |
+
out_status = gr.Markdown("")
|
| 379 |
+
table = gr.Dataframe(headers=["label", "cosine_sim"], datatype=["str", "number"], interactive=False)
|
| 380 |
+
run_btn.click(classify, inputs=[whole, topk], outputs=[out_status, table, face_prev, eyes_prev])
|
| 381 |
+
|
| 382 |
+
with gr.Tab("Add prototype"):
|
| 383 |
+
gr.Markdown(
|
| 384 |
+
"Add a new prototype to the loaded prototype DB by averaging embeddings of uploaded whole images.\n"
|
| 385 |
+
"Multiple prototypes per label are allowed."
|
| 386 |
+
)
|
| 387 |
+
label = gr.Textbox(label="Label name (artist)", placeholder="e.g. new_artist")
|
| 388 |
+
imgs = gr.Gallery(label="Whole images (1+)", columns=4, rows=2, height=240, allow_preview=True)
|
| 389 |
+
uploader = gr.Files(label="Upload image files (whole)", file_types=["image"], file_count="multiple")
|
| 390 |
+
save_back = gr.Checkbox(value=True, label="Save back to selected prototype DB file after adding")
|
| 391 |
+
add_btn = gr.Button("Add prototype", variant="primary")
|
| 392 |
+
add_status = gr.Markdown("")
|
| 393 |
+
|
| 394 |
+
def _files_to_gallery(files):
|
| 395 |
+
if not files:
|
| 396 |
+
return []
|
| 397 |
+
out = []
|
| 398 |
+
for f in files:
|
| 399 |
+
try:
|
| 400 |
+
im = Image.open(f.name).convert("RGB")
|
| 401 |
+
out.append(im)
|
| 402 |
+
except Exception:
|
| 403 |
+
continue
|
| 404 |
+
return out
|
| 405 |
+
|
| 406 |
+
uploader.change(_files_to_gallery, inputs=[uploader], outputs=[imgs])
|
| 407 |
+
add_btn.click(add_prototype, inputs=[label, imgs, save_back], outputs=[add_status])
|
| 408 |
+
|
| 409 |
+
gr.Markdown("Save DB as (optional):")
|
| 410 |
+
save_path = gr.Textbox(label="Output path (relative paths go under ./checkpoints_style/)", placeholder="prototypes_custom.pt")
|
| 411 |
+
save_btn = gr.Button("Save As")
|
| 412 |
+
save_btn.click(save_db_as, inputs=[save_path], outputs=[add_status])
|
| 413 |
+
|
| 414 |
+
return demo
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
if __name__ == "__main__":
|
| 418 |
+
CKPT_DIR.mkdir(parents=True, exist_ok=True)
|
| 419 |
+
demo = build_ui()
|
| 420 |
+
|
| 421 |
+
ap = argparse.ArgumentParser(description="ArtistEmbeddingClassifier Gradio UI")
|
| 422 |
+
# Hugging Face Spaces runs behind a proxy and expects binding to 0.0.0.0:$PORT.
|
| 423 |
+
default_host = os.getenv("GRADIO_SERVER_NAME")
|
| 424 |
+
if not default_host:
|
| 425 |
+
default_host = "0.0.0.0" if os.getenv("SPACE_ID") or os.getenv("HF_SPACE") else "127.0.0.1"
|
| 426 |
+
default_port = int(os.getenv("PORT") or os.getenv("GRADIO_SERVER_PORT") or "7860")
|
| 427 |
+
|
| 428 |
+
ap.add_argument("--host", type=str, default=default_host)
|
| 429 |
+
ap.add_argument("--port", type=int, default=default_port)
|
| 430 |
+
ap.add_argument("--share", action="store_true", help="Create a public share link")
|
| 431 |
+
args = ap.parse_args()
|
| 432 |
+
|
| 433 |
+
# Re-apply patch right before launching (in case import order changed).
|
| 434 |
+
_patch_fastapi_starlette_middleware_unpack()
|
| 435 |
+
|
| 436 |
+
try:
|
| 437 |
+
demo.launch(server_name=args.host, server_port=args.port, show_api=False, share=args.share)
|
| 438 |
+
except ValueError as e:
|
| 439 |
+
# Some environments block localhost checks; fall back to share link.
|
| 440 |
+
msg = str(e)
|
| 441 |
+
if "localhost is not accessible" in msg and not args.share:
|
| 442 |
+
demo.launch(server_name=args.host, server_port=args.port, show_api=False, share=True)
|
| 443 |
+
else:
|
| 444 |
+
raise
|
| 445 |
+
|
| 446 |
+
|
yolov5_anime/.dockerignore
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Repo-specific DockerIgnore -------------------------------------------------------------------------------------------
|
| 2 |
+
# .git
|
| 3 |
+
.cache
|
| 4 |
+
.idea
|
| 5 |
+
runs
|
| 6 |
+
output
|
| 7 |
+
coco
|
| 8 |
+
storage.googleapis.com
|
| 9 |
+
|
| 10 |
+
data/samples/*
|
| 11 |
+
**/results*.txt
|
| 12 |
+
*.jpg
|
| 13 |
+
|
| 14 |
+
# Neural Network weights -----------------------------------------------------------------------------------------------
|
| 15 |
+
**/*.weights
|
| 16 |
+
**/*.pt
|
| 17 |
+
**/*.pth
|
| 18 |
+
**/*.onnx
|
| 19 |
+
**/*.mlmodel
|
| 20 |
+
**/*.torchscript
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# Below Copied From .gitignore -----------------------------------------------------------------------------------------
|
| 24 |
+
# Below Copied From .gitignore -----------------------------------------------------------------------------------------
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# GitHub Python GitIgnore ----------------------------------------------------------------------------------------------
|
| 28 |
+
# Byte-compiled / optimized / DLL files
|
| 29 |
+
__pycache__/
|
| 30 |
+
*.py[cod]
|
| 31 |
+
*$py.class
|
| 32 |
+
|
| 33 |
+
# C extensions
|
| 34 |
+
*.so
|
| 35 |
+
|
| 36 |
+
# Distribution / packaging
|
| 37 |
+
.Python
|
| 38 |
+
env/
|
| 39 |
+
build/
|
| 40 |
+
develop-eggs/
|
| 41 |
+
dist/
|
| 42 |
+
downloads/
|
| 43 |
+
eggs/
|
| 44 |
+
.eggs/
|
| 45 |
+
lib/
|
| 46 |
+
lib64/
|
| 47 |
+
parts/
|
| 48 |
+
sdist/
|
| 49 |
+
var/
|
| 50 |
+
wheels/
|
| 51 |
+
*.egg-info/
|
| 52 |
+
.installed.cfg
|
| 53 |
+
*.egg
|
| 54 |
+
|
| 55 |
+
# PyInstaller
|
| 56 |
+
# Usually these files are written by a python script from a template
|
| 57 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
| 58 |
+
*.manifest
|
| 59 |
+
*.spec
|
| 60 |
+
|
| 61 |
+
# Installer logs
|
| 62 |
+
pip-log.txt
|
| 63 |
+
pip-delete-this-directory.txt
|
| 64 |
+
|
| 65 |
+
# Unit test / coverage reports
|
| 66 |
+
htmlcov/
|
| 67 |
+
.tox/
|
| 68 |
+
.coverage
|
| 69 |
+
.coverage.*
|
| 70 |
+
.cache
|
| 71 |
+
nosetests.xml
|
| 72 |
+
coverage.xml
|
| 73 |
+
*.cover
|
| 74 |
+
.hypothesis/
|
| 75 |
+
|
| 76 |
+
# Translations
|
| 77 |
+
*.mo
|
| 78 |
+
*.pot
|
| 79 |
+
|
| 80 |
+
# Django stuff:
|
| 81 |
+
*.log
|
| 82 |
+
local_settings.py
|
| 83 |
+
|
| 84 |
+
# Flask stuff:
|
| 85 |
+
instance/
|
| 86 |
+
.webassets-cache
|
| 87 |
+
|
| 88 |
+
# Scrapy stuff:
|
| 89 |
+
.scrapy
|
| 90 |
+
|
| 91 |
+
# Sphinx documentation
|
| 92 |
+
docs/_build/
|
| 93 |
+
|
| 94 |
+
# PyBuilder
|
| 95 |
+
target/
|
| 96 |
+
|
| 97 |
+
# Jupyter Notebook
|
| 98 |
+
.ipynb_checkpoints
|
| 99 |
+
|
| 100 |
+
# pyenv
|
| 101 |
+
.python-version
|
| 102 |
+
|
| 103 |
+
# celery beat schedule file
|
| 104 |
+
celerybeat-schedule
|
| 105 |
+
|
| 106 |
+
# SageMath parsed files
|
| 107 |
+
*.sage.py
|
| 108 |
+
|
| 109 |
+
# dotenv
|
| 110 |
+
.env
|
| 111 |
+
|
| 112 |
+
# virtualenv
|
| 113 |
+
.venv
|
| 114 |
+
venv/
|
| 115 |
+
ENV/
|
| 116 |
+
|
| 117 |
+
# Spyder project settings
|
| 118 |
+
.spyderproject
|
| 119 |
+
.spyproject
|
| 120 |
+
|
| 121 |
+
# Rope project settings
|
| 122 |
+
.ropeproject
|
| 123 |
+
|
| 124 |
+
# mkdocs documentation
|
| 125 |
+
/site
|
| 126 |
+
|
| 127 |
+
# mypy
|
| 128 |
+
.mypy_cache/
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
# https://github.com/github/gitignore/blob/master/Global/macOS.gitignore -----------------------------------------------
|
| 132 |
+
|
| 133 |
+
# General
|
| 134 |
+
.DS_Store
|
| 135 |
+
.AppleDouble
|
| 136 |
+
.LSOverride
|
| 137 |
+
|
| 138 |
+
# Icon must end with two \r
|
| 139 |
+
Icon
|
| 140 |
+
Icon?
|
| 141 |
+
|
| 142 |
+
# Thumbnails
|
| 143 |
+
._*
|
| 144 |
+
|
| 145 |
+
# Files that might appear in the root of a volume
|
| 146 |
+
.DocumentRevisions-V100
|
| 147 |
+
.fseventsd
|
| 148 |
+
.Spotlight-V100
|
| 149 |
+
.TemporaryItems
|
| 150 |
+
.Trashes
|
| 151 |
+
.VolumeIcon.icns
|
| 152 |
+
.com.apple.timemachine.donotpresent
|
| 153 |
+
|
| 154 |
+
# Directories potentially created on remote AFP share
|
| 155 |
+
.AppleDB
|
| 156 |
+
.AppleDesktop
|
| 157 |
+
Network Trash Folder
|
| 158 |
+
Temporary Items
|
| 159 |
+
.apdisk
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
# https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore
|
| 163 |
+
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
|
| 164 |
+
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
| 165 |
+
|
| 166 |
+
# User-specific stuff:
|
| 167 |
+
.idea/*
|
| 168 |
+
.idea/**/workspace.xml
|
| 169 |
+
.idea/**/tasks.xml
|
| 170 |
+
.idea/dictionaries
|
| 171 |
+
.html # Bokeh Plots
|
| 172 |
+
.pg # TensorFlow Frozen Graphs
|
| 173 |
+
.avi # videos
|
| 174 |
+
|
| 175 |
+
# Sensitive or high-churn files:
|
| 176 |
+
.idea/**/dataSources/
|
| 177 |
+
.idea/**/dataSources.ids
|
| 178 |
+
.idea/**/dataSources.local.xml
|
| 179 |
+
.idea/**/sqlDataSources.xml
|
| 180 |
+
.idea/**/dynamic.xml
|
| 181 |
+
.idea/**/uiDesigner.xml
|
| 182 |
+
|
| 183 |
+
# Gradle:
|
| 184 |
+
.idea/**/gradle.xml
|
| 185 |
+
.idea/**/libraries
|
| 186 |
+
|
| 187 |
+
# CMake
|
| 188 |
+
cmake-build-debug/
|
| 189 |
+
cmake-build-release/
|
| 190 |
+
|
| 191 |
+
# Mongo Explorer plugin:
|
| 192 |
+
.idea/**/mongoSettings.xml
|
| 193 |
+
|
| 194 |
+
## File-based project format:
|
| 195 |
+
*.iws
|
| 196 |
+
|
| 197 |
+
## Plugin-specific files:
|
| 198 |
+
|
| 199 |
+
# IntelliJ
|
| 200 |
+
out/
|
| 201 |
+
|
| 202 |
+
# mpeltonen/sbt-idea plugin
|
| 203 |
+
.idea_modules/
|
| 204 |
+
|
| 205 |
+
# JIRA plugin
|
| 206 |
+
atlassian-ide-plugin.xml
|
| 207 |
+
|
| 208 |
+
# Cursive Clojure plugin
|
| 209 |
+
.idea/replstate.xml
|
| 210 |
+
|
| 211 |
+
# Crashlytics plugin (for Android Studio and IntelliJ)
|
| 212 |
+
com_crashlytics_export_strings.xml
|
| 213 |
+
crashlytics.properties
|
| 214 |
+
crashlytics-build.properties
|
| 215 |
+
fabric.properties
|
yolov5_anime/.gitattributes
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# this drop notebooks from GitHub language stats
|
| 2 |
+
*.ipynb linguist-vendored
|
yolov5_anime/LICENSE
ADDED
|
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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>.
|
yolov5_anime/README.md
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# yolov5_anime
|
| 2 |
+
An anime face detector based on [yolov5](https://github.com/ultralytics/yolov5).
|
| 3 |
+
|
| 4 |
+
The training set used contains 5845 manually selected and annotated anime pictures from pixiv. The test set encompasses 655 randomly selected pictures from the [daily rankings on pixiv](https://www.pixiv.net/ranking.php).
|
| 5 |
+
|
| 6 |
+
Two separate models based on the configuration of yolov5x and yolov5s respectively are provided. Performance distinctions can be found in the [demo](#Demo) section.
|
| 7 |
+
|
| 8 |
+
## Requirements
|
| 9 |
+
Python 3.8 or later with all [requirements.txt](https://github.com/zymk9/yolov5_anime/blob/master/requirements.txt) dependencies installed.
|
| 10 |
+
|
| 11 |
+
## Usage
|
| 12 |
+
1. Clone the repository and run install requirements. **Beware that the weights and models provided here may be only compatible to the [yolov5 2.0 release](https://github.com/ultralytics/yolov5/releases/tag/v2.0).**
|
| 13 |
+
|
| 14 |
+
Update: the models are still compatible with [release 3.0](https://github.com/ultralytics/yolov5/releases/tag/v3.0)
|
| 15 |
+
```bash
|
| 16 |
+
$ git clone https://github.com/zymk9/yolov5_anime.git
|
| 17 |
+
$ cd yolov5_anime
|
| 18 |
+
$ pip install -qr requirements.txt # install dependencies
|
| 19 |
+
```
|
| 20 |
+
2. Retrieve yolov5x weights from [Google Drive](https://drive.google.com/file/d/1-MO9RYPZxnBfpNiGY6GdsqCeQWYNxBdl/view?usp=sharing) or use the following code.
|
| 21 |
+
```python
|
| 22 |
+
# retrieve weights for model based on yolov5x
|
| 23 |
+
from utils.google_utils import gdrive_download
|
| 24 |
+
gdrive_download('1-MO9RYPZxnBfpNiGY6GdsqCeQWYNxBdl','yolov5x_anime.pt')
|
| 25 |
+
```
|
| 26 |
+
The weights for yolov5s can be found in the [weights](https://github.com/zymk9/yolov5_anime/tree/master/weights) folder.
|
| 27 |
+
3. Run detection on your data.
|
| 28 |
+
```bash
|
| 29 |
+
$ python detect.py --weights path/to/model --source path/to/images --output path/to/output/folder
|
| 30 |
+
```
|
| 31 |
+
You can also set `--conf-thres` and `--iou-thres`, or enable test time augmentation using `--augment` (no significant performance gain on test set). Refer to [detect.py](https://github.com/zymk9/yolov5_anime/blob/master/detect.py) for more arguments.
|
| 32 |
+
|
| 33 |
+
For yolov5x, the recommended and default threshold for confidence is 0.8 if high resolution faces are desidered. However, if you want to detect more varieties, scales or angles of faces, 0.5 can be a reasonable value.
|
| 34 |
+
|
| 35 |
+
For yolov5s, you may need to lower `--conf-thres` to 0.5.
|
| 36 |
+
|
| 37 |
+
## Demo
|
| 38 |
+
The performance on test set using [test.py](https://github.com/zymk9/yolov5_anime/blob/master/test.py) with `--conf-thres=0.5 --ious-thres=0.5`
|
| 39 |
+
```
|
| 40 |
+
performance of yolov5x_anime
|
| 41 |
+
--------------------------------------------------------------------------------------------------
|
| 42 |
+
Images Targets P R [email protected] [email protected]:.95
|
| 43 |
+
655 873 0.964 0.95 0.947 0.518
|
| 44 |
+
|
| 45 |
+
Speed: 22.6/1.5/24.1 ms inference/NMS/total per 640x640 image at batch-size 32, using a Tesla P100
|
| 46 |
+
--------------------------------------------------------------------------------------------------
|
| 47 |
+
|
| 48 |
+
performance of yolov5s_anime
|
| 49 |
+
--------------------------------------------------------------------------------------------------
|
| 50 |
+
Images Targets P R [email protected] [email protected]:.95
|
| 51 |
+
655 873 0.959 0.955 0.953 0.582
|
| 52 |
+
|
| 53 |
+
Speed: 3.4/1.3/4.6 ms inference/NMS/total per 640x640 image at batch-size 32, using a Tesla P100
|
| 54 |
+
--------------------------------------------------------------------------------------------------
|
| 55 |
+
```
|
| 56 |
+
The performances are comparible. However, with a higher confidence threshold, yolov5x can significantly outperform yolov5s.
|
| 57 |
+
|
| 58 |
+
The model works with multi-scale, multi-view faces, including manga and other styles. Pictures are taken from yolov5x output.
|
| 59 |
+
|
| 60 |
+

|
| 61 |
+
Origin: [【PFT】-月華祭-](https://www.pixiv.net/artworks/55817439) by [swd3e2](https://www.pixiv.net/users/660788)
|
| 62 |
+

|
| 63 |
+
Origin: [新年愉悦](https://www.pixiv.net/artworks/67321023) by [Liduke(日子)](https://www.pixiv.net/users/38088)
|
| 64 |
+

|
| 65 |
+
Origin: [Tales of abyss Only cover](https://www.pixiv.net/artworks/66546900) by [Liduke(日子)](https://www.pixiv.net/users/38088)
|
| 66 |
+

|
| 67 |
+
Origin: [いつものふたり](https://www.pixiv.net/artworks/82867235) by [うにょーん](https://www.pixiv.net/users/123423)
|
| 68 |
+

|
| 69 |
+
Origin: *an omnipresence in wired/『lain』 安倍吉俊画集 オムニプレゼンス* by 安倍 吉俊
|
| 70 |
+
|
| 71 |
+
## Training
|
| 72 |
+
An official toturial from Ultralytics can be found [here](https://github.com/ultralytics/yolov5/issues/12) if you want to train your own model.
|
| 73 |
+
|
| 74 |
+
The yolov5x_anime was trained for about 40h on a single Tesla P100 for 326 epochs, using SGD and without multi-scale training. The script is following
|
| 75 |
+
```bash
|
| 76 |
+
$ python train.py --hyp ./data/hyp.finetune.yaml --single-cls --cache-images --batch-size 16 --epochs 360 --data ./data/anime.yaml --cfg ./models/yolov5x.yaml --weights yolov5x.pt
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
The model of yolov5s_anime underwent 480 epochs in 14h, using `--adam` and `--multi-scale`.
|
| 80 |
+
|
| 81 |
+
|
yolov5_anime/README.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Optional: clone YOLOv5-anime repo here and place weights at project root (e.g., ./yolov5x_anime.pt).
|
| 2 |
+
If not provided, the app will still run using the whole image (and any existing face/eyes).
|
yolov5_anime/data/anime.yaml
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
train: ../anime/images/train
|
| 2 |
+
val: ../anime/images/val
|
| 3 |
+
|
| 4 |
+
nc: 1
|
| 5 |
+
|
| 6 |
+
names: ['face']
|
yolov5_anime/data/coco.yaml
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# COCO 2017 dataset http://cocodataset.org
|
| 2 |
+
# Train command: python train.py --data coco.yaml
|
| 3 |
+
# Default dataset location is next to /yolov5:
|
| 4 |
+
# /parent_folder
|
| 5 |
+
# /coco
|
| 6 |
+
# /yolov5
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
# download command/URL (optional)
|
| 10 |
+
download: bash data/scripts/get_coco.sh
|
| 11 |
+
|
| 12 |
+
# train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
|
| 13 |
+
train: ../coco/train2017.txt # 118287 images
|
| 14 |
+
val: ../coco/val2017.txt # 5000 images
|
| 15 |
+
test: ../coco/test-dev2017.txt # 20288 of 40670 images, submit to https://competitions.codalab.org/competitions/20794
|
| 16 |
+
|
| 17 |
+
# number of classes
|
| 18 |
+
nc: 80
|
| 19 |
+
|
| 20 |
+
# class names
|
| 21 |
+
names: ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
|
| 22 |
+
'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
|
| 23 |
+
'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
|
| 24 |
+
'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
|
| 25 |
+
'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
|
| 26 |
+
'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
|
| 27 |
+
'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
|
| 28 |
+
'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
|
| 29 |
+
'hair drier', 'toothbrush']
|
| 30 |
+
|
| 31 |
+
# Print classes
|
| 32 |
+
# with open('data/coco.yaml') as f:
|
| 33 |
+
# d = yaml.load(f, Loader=yaml.FullLoader) # dict
|
| 34 |
+
# for i, x in enumerate(d['names']):
|
| 35 |
+
# print(i, x)
|
yolov5_anime/data/coco128.yaml
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# COCO 2017 dataset http://cocodataset.org - first 128 training images
|
| 2 |
+
# Train command: python train.py --data coco128.yaml
|
| 3 |
+
# Default dataset location is next to /yolov5:
|
| 4 |
+
# /parent_folder
|
| 5 |
+
# /coco128
|
| 6 |
+
# /yolov5
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
# download command/URL (optional)
|
| 10 |
+
download: https://github.com/ultralytics/yolov5/releases/download/v1.0/coco128.zip
|
| 11 |
+
|
| 12 |
+
# train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
|
| 13 |
+
train: ../coco128/images/train2017/ # 128 images
|
| 14 |
+
val: ../coco128/images/train2017/ # 128 images
|
| 15 |
+
|
| 16 |
+
# number of classes
|
| 17 |
+
nc: 80
|
| 18 |
+
|
| 19 |
+
# class names
|
| 20 |
+
names: ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
|
| 21 |
+
'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
|
| 22 |
+
'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
|
| 23 |
+
'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
|
| 24 |
+
'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
|
| 25 |
+
'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
|
| 26 |
+
'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
|
| 27 |
+
'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
|
| 28 |
+
'hair drier', 'toothbrush']
|
yolov5_anime/data/hyp.finetune.yaml
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Hyperparameters for VOC fine-tuning
|
| 2 |
+
# python train.py --batch 64 --cfg '' --weights yolov5m.pt --data voc.yaml --img 512 --epochs 50
|
| 3 |
+
# See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
|
| 7 |
+
momentum: 0.937 # SGD momentum/Adam beta1
|
| 8 |
+
weight_decay: 0.0005 # optimizer weight decay 5e-4
|
| 9 |
+
giou: 0.05 # GIoU loss gain
|
| 10 |
+
cls: 0.5 # cls loss gain
|
| 11 |
+
cls_pw: 1.0 # cls BCELoss positive_weight
|
| 12 |
+
obj: 1.0 # obj loss gain (scale with pixels)
|
| 13 |
+
obj_pw: 1.0 # obj BCELoss positive_weight
|
| 14 |
+
iou_t: 0.20 # IoU training threshold
|
| 15 |
+
anchor_t: 4.0 # anchor-multiple threshold
|
| 16 |
+
fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
|
| 17 |
+
hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
|
| 18 |
+
hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
|
| 19 |
+
hsv_v: 0.4 # image HSV-Value augmentation (fraction)
|
| 20 |
+
degrees: 0.0 # image rotation (+/- deg)
|
| 21 |
+
translate: 0.5 # image translation (+/- fraction)
|
| 22 |
+
scale: 0.5 # image scale (+/- gain)
|
| 23 |
+
shear: 0.0 # image shear (+/- deg)
|
| 24 |
+
perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
|
| 25 |
+
flipud: 0.0 # image flip up-down (probability)
|
| 26 |
+
fliplr: 0.5 # image flip left-right (probability)
|
| 27 |
+
mixup: 0.0 # image mixup (probability)
|
yolov5_anime/data/hyp.scratch.yaml
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Hyperparameters for COCO training from scratch
|
| 2 |
+
# python train.py --batch 40 --cfg yolov5m.yaml --weights '' --data coco.yaml --img 640 --epochs 300
|
| 3 |
+
# See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
|
| 7 |
+
momentum: 0.937 # SGD momentum/Adam beta1
|
| 8 |
+
weight_decay: 0.0005 # optimizer weight decay 5e-4
|
| 9 |
+
giou: 0.05 # GIoU loss gain
|
| 10 |
+
cls: 0.5 # cls loss gain
|
| 11 |
+
cls_pw: 1.0 # cls BCELoss positive_weight
|
| 12 |
+
obj: 1.0 # obj loss gain (scale with pixels)
|
| 13 |
+
obj_pw: 1.0 # obj BCELoss positive_weight
|
| 14 |
+
iou_t: 0.20 # IoU training threshold
|
| 15 |
+
anchor_t: 4.0 # anchor-multiple threshold
|
| 16 |
+
fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
|
| 17 |
+
hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
|
| 18 |
+
hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
|
| 19 |
+
hsv_v: 0.4 # image HSV-Value augmentation (fraction)
|
| 20 |
+
degrees: 0.0 # image rotation (+/- deg)
|
| 21 |
+
translate: 0.5 # image translation (+/- fraction)
|
| 22 |
+
scale: 0.5 # image scale (+/- gain)
|
| 23 |
+
shear: 0.0 # image shear (+/- deg)
|
| 24 |
+
perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
|
| 25 |
+
flipud: 0.0 # image flip up-down (probability)
|
| 26 |
+
fliplr: 0.5 # image flip left-right (probability)
|
| 27 |
+
mixup: 0.0 # image mixup (probability)
|
yolov5_anime/data/scripts/get_coco.sh
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# COCO 2017 dataset http://cocodataset.org
|
| 3 |
+
# Download command: bash data/scripts/get_coco.sh
|
| 4 |
+
# Train command: python train.py --data coco.yaml
|
| 5 |
+
# Default dataset location is next to /yolov5:
|
| 6 |
+
# /parent_folder
|
| 7 |
+
# /coco
|
| 8 |
+
# /yolov5
|
| 9 |
+
|
| 10 |
+
# Download/unzip labels
|
| 11 |
+
echo 'Downloading COCO 2017 labels ...'
|
| 12 |
+
d='../' # unzip directory
|
| 13 |
+
f='coco2017labels.zip' && curl -L https://github.com/ultralytics/yolov5/releases/download/v1.0/$f -o $f
|
| 14 |
+
unzip -q $f -d $d && rm $f
|
| 15 |
+
|
| 16 |
+
# Download/unzip images
|
| 17 |
+
echo 'Downloading COCO 2017 images ...'
|
| 18 |
+
d='../coco/images' # unzip directory
|
| 19 |
+
f='train2017.zip' && curl http://images.cocodataset.org/zips/$f -o $f && unzip -q $f -d $d && rm $f # 19G, 118k images
|
| 20 |
+
f='val2017.zip' && curl http://images.cocodataset.org/zips/$f -o $f && unzip -q $f -d $d && rm $f # 1G, 5k images
|
| 21 |
+
# f='test2017.zip' && curl http://images.cocodataset.org/zips/$f -o $f && unzip -q $f -d $d && rm $f # 7G, 41k images
|
yolov5_anime/data/scripts/get_voc.sh
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# PASCAL VOC dataset http://host.robots.ox.ac.uk/pascal/VOC/
|
| 3 |
+
# Download command: bash data/scripts/get_voc.sh
|
| 4 |
+
# Train command: python train.py --data voc.yaml
|
| 5 |
+
# Default dataset location is next to /yolov5:
|
| 6 |
+
# /parent_folder
|
| 7 |
+
# /VOC
|
| 8 |
+
# /yolov5
|
| 9 |
+
|
| 10 |
+
start=$(date +%s)
|
| 11 |
+
|
| 12 |
+
# handle optional download dir
|
| 13 |
+
if [ -z "$1" ]; then
|
| 14 |
+
# navigate to ~/tmp
|
| 15 |
+
echo "navigating to ../tmp/ ..."
|
| 16 |
+
mkdir -p ../tmp
|
| 17 |
+
cd ../tmp/
|
| 18 |
+
else
|
| 19 |
+
# check if is valid directory
|
| 20 |
+
if [ ! -d $1 ]; then
|
| 21 |
+
echo $1 "is not a valid directory"
|
| 22 |
+
exit 0
|
| 23 |
+
fi
|
| 24 |
+
echo "navigating to" $1 "..."
|
| 25 |
+
cd $1
|
| 26 |
+
fi
|
| 27 |
+
|
| 28 |
+
echo "Downloading VOC2007 trainval ..."
|
| 29 |
+
# Download data
|
| 30 |
+
curl -LO http://host.robots.ox.ac.uk/pascal/VOC/voc2007/VOCtrainval_06-Nov-2007.tar
|
| 31 |
+
echo "Downloading VOC2007 test data ..."
|
| 32 |
+
curl -LO http://host.robots.ox.ac.uk/pascal/VOC/voc2007/VOCtest_06-Nov-2007.tar
|
| 33 |
+
echo "Done downloading."
|
| 34 |
+
|
| 35 |
+
# Extract data
|
| 36 |
+
echo "Extracting trainval ..."
|
| 37 |
+
tar -xf VOCtrainval_06-Nov-2007.tar
|
| 38 |
+
echo "Extracting test ..."
|
| 39 |
+
tar -xf VOCtest_06-Nov-2007.tar
|
| 40 |
+
echo "removing tars ..."
|
| 41 |
+
rm VOCtrainval_06-Nov-2007.tar
|
| 42 |
+
rm VOCtest_06-Nov-2007.tar
|
| 43 |
+
|
| 44 |
+
end=$(date +%s)
|
| 45 |
+
runtime=$((end - start))
|
| 46 |
+
|
| 47 |
+
echo "Completed in" $runtime "seconds"
|
| 48 |
+
|
| 49 |
+
start=$(date +%s)
|
| 50 |
+
|
| 51 |
+
# handle optional download dir
|
| 52 |
+
if [ -z "$1" ]; then
|
| 53 |
+
# navigate to ~/tmp
|
| 54 |
+
echo "navigating to ../tmp/ ..."
|
| 55 |
+
mkdir -p ../tmp
|
| 56 |
+
cd ../tmp/
|
| 57 |
+
else
|
| 58 |
+
# check if is valid directory
|
| 59 |
+
if [ ! -d $1 ]; then
|
| 60 |
+
echo $1 "is not a valid directory"
|
| 61 |
+
exit 0
|
| 62 |
+
fi
|
| 63 |
+
echo "navigating to" $1 "..."
|
| 64 |
+
cd $1
|
| 65 |
+
fi
|
| 66 |
+
|
| 67 |
+
echo "Downloading VOC2012 trainval ..."
|
| 68 |
+
# Download data
|
| 69 |
+
curl -LO http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar
|
| 70 |
+
echo "Done downloading."
|
| 71 |
+
|
| 72 |
+
# Extract data
|
| 73 |
+
echo "Extracting trainval ..."
|
| 74 |
+
tar -xf VOCtrainval_11-May-2012.tar
|
| 75 |
+
echo "removing tar ..."
|
| 76 |
+
rm VOCtrainval_11-May-2012.tar
|
| 77 |
+
|
| 78 |
+
end=$(date +%s)
|
| 79 |
+
runtime=$((end - start))
|
| 80 |
+
|
| 81 |
+
echo "Completed in" $runtime "seconds"
|
| 82 |
+
|
| 83 |
+
cd ../tmp
|
| 84 |
+
echo "Spliting dataset..."
|
| 85 |
+
python3 - "$@" <<END
|
| 86 |
+
import xml.etree.ElementTree as ET
|
| 87 |
+
import pickle
|
| 88 |
+
import os
|
| 89 |
+
from os import listdir, getcwd
|
| 90 |
+
from os.path import join
|
| 91 |
+
|
| 92 |
+
sets=[('2012', 'train'), ('2012', 'val'), ('2007', 'train'), ('2007', 'val'), ('2007', 'test')]
|
| 93 |
+
|
| 94 |
+
classes = ["aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"]
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def convert(size, box):
|
| 98 |
+
dw = 1./(size[0])
|
| 99 |
+
dh = 1./(size[1])
|
| 100 |
+
x = (box[0] + box[1])/2.0 - 1
|
| 101 |
+
y = (box[2] + box[3])/2.0 - 1
|
| 102 |
+
w = box[1] - box[0]
|
| 103 |
+
h = box[3] - box[2]
|
| 104 |
+
x = x*dw
|
| 105 |
+
w = w*dw
|
| 106 |
+
y = y*dh
|
| 107 |
+
h = h*dh
|
| 108 |
+
return (x,y,w,h)
|
| 109 |
+
|
| 110 |
+
def convert_annotation(year, image_id):
|
| 111 |
+
in_file = open('VOCdevkit/VOC%s/Annotations/%s.xml'%(year, image_id))
|
| 112 |
+
out_file = open('VOCdevkit/VOC%s/labels/%s.txt'%(year, image_id), 'w')
|
| 113 |
+
tree=ET.parse(in_file)
|
| 114 |
+
root = tree.getroot()
|
| 115 |
+
size = root.find('size')
|
| 116 |
+
w = int(size.find('width').text)
|
| 117 |
+
h = int(size.find('height').text)
|
| 118 |
+
|
| 119 |
+
for obj in root.iter('object'):
|
| 120 |
+
difficult = obj.find('difficult').text
|
| 121 |
+
cls = obj.find('name').text
|
| 122 |
+
if cls not in classes or int(difficult)==1:
|
| 123 |
+
continue
|
| 124 |
+
cls_id = classes.index(cls)
|
| 125 |
+
xmlbox = obj.find('bndbox')
|
| 126 |
+
b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text), float(xmlbox.find('ymax').text))
|
| 127 |
+
bb = convert((w,h), b)
|
| 128 |
+
out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
|
| 129 |
+
|
| 130 |
+
wd = getcwd()
|
| 131 |
+
|
| 132 |
+
for year, image_set in sets:
|
| 133 |
+
if not os.path.exists('VOCdevkit/VOC%s/labels/'%(year)):
|
| 134 |
+
os.makedirs('VOCdevkit/VOC%s/labels/'%(year))
|
| 135 |
+
image_ids = open('VOCdevkit/VOC%s/ImageSets/Main/%s.txt'%(year, image_set)).read().strip().split()
|
| 136 |
+
list_file = open('%s_%s.txt'%(year, image_set), 'w')
|
| 137 |
+
for image_id in image_ids:
|
| 138 |
+
list_file.write('%s/VOCdevkit/VOC%s/JPEGImages/%s.jpg\n'%(wd, year, image_id))
|
| 139 |
+
convert_annotation(year, image_id)
|
| 140 |
+
list_file.close()
|
| 141 |
+
|
| 142 |
+
END
|
| 143 |
+
|
| 144 |
+
cat 2007_train.txt 2007_val.txt 2012_train.txt 2012_val.txt >train.txt
|
| 145 |
+
cat 2007_train.txt 2007_val.txt 2007_test.txt 2012_train.txt 2012_val.txt >train.all.txt
|
| 146 |
+
|
| 147 |
+
python3 - "$@" <<END
|
| 148 |
+
|
| 149 |
+
import shutil
|
| 150 |
+
import os
|
| 151 |
+
os.system('mkdir ../VOC/')
|
| 152 |
+
os.system('mkdir ../VOC/images')
|
| 153 |
+
os.system('mkdir ../VOC/images/train')
|
| 154 |
+
os.system('mkdir ../VOC/images/val')
|
| 155 |
+
|
| 156 |
+
os.system('mkdir ../VOC/labels')
|
| 157 |
+
os.system('mkdir ../VOC/labels/train')
|
| 158 |
+
os.system('mkdir ../VOC/labels/val')
|
| 159 |
+
|
| 160 |
+
import os
|
| 161 |
+
print(os.path.exists('../tmp/train.txt'))
|
| 162 |
+
f = open('../tmp/train.txt', 'r')
|
| 163 |
+
lines = f.readlines()
|
| 164 |
+
|
| 165 |
+
for line in lines:
|
| 166 |
+
#print(line.split('/')[-1][:-1])
|
| 167 |
+
line = "/".join(line.split('/')[2:])
|
| 168 |
+
#print(line)
|
| 169 |
+
if (os.path.exists("../" + line[:-1])):
|
| 170 |
+
os.system("cp ../"+ line[:-1] + " ../VOC/images/train")
|
| 171 |
+
|
| 172 |
+
print(os.path.exists('../tmp/train.txt'))
|
| 173 |
+
f = open('../tmp/train.txt', 'r')
|
| 174 |
+
lines = f.readlines()
|
| 175 |
+
|
| 176 |
+
for line in lines:
|
| 177 |
+
#print(line.split('/')[-1][:-1])
|
| 178 |
+
line = "/".join(line.split('/')[2:])
|
| 179 |
+
line = line.replace('JPEGImages', 'labels')
|
| 180 |
+
line = line.replace('jpg', 'txt')
|
| 181 |
+
#print(line)
|
| 182 |
+
if (os.path.exists("../" + line[:-1])):
|
| 183 |
+
os.system("cp ../"+ line[:-1] + " ../VOC/labels/train")
|
| 184 |
+
|
| 185 |
+
print(os.path.exists('../tmp/2007_test.txt'))
|
| 186 |
+
f = open('../tmp/2007_test.txt', 'r')
|
| 187 |
+
lines = f.readlines()
|
| 188 |
+
|
| 189 |
+
for line in lines:
|
| 190 |
+
#print(line.split('/')[-1][:-1])
|
| 191 |
+
line = "/".join(line.split('/')[2:])
|
| 192 |
+
|
| 193 |
+
if (os.path.exists("../" + line[:-1])):
|
| 194 |
+
os.system("cp ../"+ line[:-1] + " ../VOC/images/val")
|
| 195 |
+
|
| 196 |
+
print(os.path.exists('../tmp/2007_test.txt'))
|
| 197 |
+
f = open('../tmp/2007_test.txt', 'r')
|
| 198 |
+
lines = f.readlines()
|
| 199 |
+
|
| 200 |
+
for line in lines:
|
| 201 |
+
#print(line.split('/')[-1][:-1])
|
| 202 |
+
line = "/".join(line.split('/')[2:])
|
| 203 |
+
line = line.replace('JPEGImages', 'labels')
|
| 204 |
+
line = line.replace('jpg', 'txt')
|
| 205 |
+
#print(line)
|
| 206 |
+
if (os.path.exists("../" + line[:-1])):
|
| 207 |
+
os.system("cp ../"+ line[:-1] + " ../VOC/labels/val")
|
| 208 |
+
|
| 209 |
+
END
|
| 210 |
+
|
| 211 |
+
rm -rf ../tmp # remove temporary directory
|
| 212 |
+
echo "VOC download done."
|
yolov5_anime/data/voc.yaml
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# PASCAL VOC dataset http://host.robots.ox.ac.uk/pascal/VOC/
|
| 2 |
+
# Train command: python train.py --data voc.yaml
|
| 3 |
+
# Default dataset location is next to /yolov5:
|
| 4 |
+
# /parent_folder
|
| 5 |
+
# /VOC
|
| 6 |
+
# /yolov5
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
# download command/URL (optional)
|
| 10 |
+
download: bash data/scripts/get_voc.sh
|
| 11 |
+
|
| 12 |
+
# train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
|
| 13 |
+
train: ../VOC/images/train/ # 16551 images
|
| 14 |
+
val: ../VOC/images/val/ # 4952 images
|
| 15 |
+
|
| 16 |
+
# number of classes
|
| 17 |
+
nc: 20
|
| 18 |
+
|
| 19 |
+
# class names
|
| 20 |
+
names: ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog',
|
| 21 |
+
'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor']
|
yolov5_anime/detect.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import os
|
| 3 |
+
import platform
|
| 4 |
+
import shutil
|
| 5 |
+
import time
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import cv2
|
| 9 |
+
import torch
|
| 10 |
+
import torch.backends.cudnn as cudnn
|
| 11 |
+
from numpy import random
|
| 12 |
+
|
| 13 |
+
from models.experimental import attempt_load
|
| 14 |
+
from utils.datasets import LoadStreams, LoadImages
|
| 15 |
+
from utils.general import (
|
| 16 |
+
check_img_size, non_max_suppression, apply_classifier, scale_coords, xyxy2xywh, plot_one_box, strip_optimizer)
|
| 17 |
+
from utils.torch_utils import select_device, load_classifier, time_synchronized
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def detect(save_img=False):
|
| 21 |
+
out, source, weights, view_img, save_txt, imgsz = \
|
| 22 |
+
opt.output, opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size
|
| 23 |
+
webcam = source == '0' or source.startswith('rtsp') or source.startswith('http') or source.endswith('.txt')
|
| 24 |
+
|
| 25 |
+
# Initialize
|
| 26 |
+
device = select_device(opt.device)
|
| 27 |
+
if os.path.exists(out):
|
| 28 |
+
shutil.rmtree(out) # delete output folder
|
| 29 |
+
os.makedirs(out) # make new output folder
|
| 30 |
+
half = device.type != 'cpu' # half precision only supported on CUDA
|
| 31 |
+
|
| 32 |
+
# Load model
|
| 33 |
+
model = attempt_load(weights, map_location=device) # load FP32 model
|
| 34 |
+
imgsz = check_img_size(imgsz, s=model.stride.max()) # check img_size
|
| 35 |
+
if half:
|
| 36 |
+
model.half() # to FP16
|
| 37 |
+
|
| 38 |
+
# Second-stage classifier
|
| 39 |
+
classify = False
|
| 40 |
+
if classify:
|
| 41 |
+
modelc = load_classifier(name='resnet101', n=2) # initialize
|
| 42 |
+
modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']) # load weights
|
| 43 |
+
modelc.to(device).eval()
|
| 44 |
+
|
| 45 |
+
# Set Dataloader
|
| 46 |
+
vid_path, vid_writer = None, None
|
| 47 |
+
if webcam:
|
| 48 |
+
view_img = True
|
| 49 |
+
cudnn.benchmark = True # set True to speed up constant image size inference
|
| 50 |
+
dataset = LoadStreams(source, img_size=imgsz)
|
| 51 |
+
else:
|
| 52 |
+
save_img = True
|
| 53 |
+
dataset = LoadImages(source, img_size=imgsz)
|
| 54 |
+
|
| 55 |
+
# Get names and colors
|
| 56 |
+
names = model.module.names if hasattr(model, 'module') else model.names
|
| 57 |
+
colors = [[random.randint(0, 255) for _ in range(3)] for _ in range(len(names))]
|
| 58 |
+
|
| 59 |
+
# Run inference
|
| 60 |
+
t0 = time.time()
|
| 61 |
+
img = torch.zeros((1, 3, imgsz, imgsz), device=device) # init img
|
| 62 |
+
_ = model(img.half() if half else img) if device.type != 'cpu' else None # run once
|
| 63 |
+
for path, img, im0s, vid_cap in dataset:
|
| 64 |
+
img = torch.from_numpy(img).to(device)
|
| 65 |
+
img = img.half() if half else img.float() # uint8 to fp16/32
|
| 66 |
+
img /= 255.0 # 0 - 255 to 0.0 - 1.0
|
| 67 |
+
if img.ndimension() == 3:
|
| 68 |
+
img = img.unsqueeze(0)
|
| 69 |
+
|
| 70 |
+
# Inference
|
| 71 |
+
t1 = time_synchronized()
|
| 72 |
+
pred = model(img, augment=opt.augment)[0]
|
| 73 |
+
|
| 74 |
+
# Apply NMS
|
| 75 |
+
pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms)
|
| 76 |
+
t2 = time_synchronized()
|
| 77 |
+
|
| 78 |
+
# Apply Classifier
|
| 79 |
+
if classify:
|
| 80 |
+
pred = apply_classifier(pred, modelc, img, im0s)
|
| 81 |
+
|
| 82 |
+
# Process detections
|
| 83 |
+
for i, det in enumerate(pred): # detections per image
|
| 84 |
+
if webcam: # batch_size >= 1
|
| 85 |
+
p, s, im0 = path[i], '%g: ' % i, im0s[i].copy()
|
| 86 |
+
else:
|
| 87 |
+
p, s, im0 = path, '', im0s
|
| 88 |
+
|
| 89 |
+
save_path = str(Path(out) / Path(p).name)
|
| 90 |
+
txt_path = str(Path(out) / Path(p).stem) + ('_%g' % dataset.frame if dataset.mode == 'video' else '')
|
| 91 |
+
s += '%gx%g ' % img.shape[2:] # print string
|
| 92 |
+
gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
|
| 93 |
+
if det is not None and len(det):
|
| 94 |
+
# Rescale boxes from img_size to im0 size
|
| 95 |
+
det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
|
| 96 |
+
|
| 97 |
+
# Print results
|
| 98 |
+
for c in det[:, -1].unique():
|
| 99 |
+
n = (det[:, -1] == c).sum() # detections per class
|
| 100 |
+
s += '%g %ss, ' % (n, names[int(c)]) # add to string
|
| 101 |
+
|
| 102 |
+
# Write results
|
| 103 |
+
for *xyxy, conf, cls in det:
|
| 104 |
+
if save_txt: # Write to file
|
| 105 |
+
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
|
| 106 |
+
with open(txt_path + '.txt', 'a') as f:
|
| 107 |
+
f.write(('%g ' * 5 + '\n') % (cls, *xywh)) # label format
|
| 108 |
+
|
| 109 |
+
if save_img or view_img: # Add bbox to image
|
| 110 |
+
label = '%s %.2f' % (names[int(cls)], conf)
|
| 111 |
+
plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)
|
| 112 |
+
|
| 113 |
+
# Print time (inference + NMS)
|
| 114 |
+
print('%sDone. (%.3fs)' % (s, t2 - t1))
|
| 115 |
+
|
| 116 |
+
# Stream results
|
| 117 |
+
if view_img:
|
| 118 |
+
cv2.imshow(p, im0)
|
| 119 |
+
if cv2.waitKey(1) == ord('q'): # q to quit
|
| 120 |
+
raise StopIteration
|
| 121 |
+
|
| 122 |
+
# Save results (image with detections)
|
| 123 |
+
if save_img:
|
| 124 |
+
if dataset.mode == 'images':
|
| 125 |
+
cv2.imwrite(save_path, im0)
|
| 126 |
+
else:
|
| 127 |
+
if vid_path != save_path: # new video
|
| 128 |
+
vid_path = save_path
|
| 129 |
+
if isinstance(vid_writer, cv2.VideoWriter):
|
| 130 |
+
vid_writer.release() # release previous video writer
|
| 131 |
+
|
| 132 |
+
fourcc = 'mp4v' # output video codec
|
| 133 |
+
fps = vid_cap.get(cv2.CAP_PROP_FPS)
|
| 134 |
+
w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
| 135 |
+
h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
| 136 |
+
vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*fourcc), fps, (w, h))
|
| 137 |
+
vid_writer.write(im0)
|
| 138 |
+
|
| 139 |
+
if save_txt or save_img:
|
| 140 |
+
print('Results saved to %s' % Path(out))
|
| 141 |
+
if platform == 'darwin' and not opt.update: # MacOS
|
| 142 |
+
os.system('open ' + save_path)
|
| 143 |
+
|
| 144 |
+
print('Done. (%.3fs)' % (time.time() - t0))
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
if __name__ == '__main__':
|
| 148 |
+
parser = argparse.ArgumentParser()
|
| 149 |
+
parser.add_argument('--weights', nargs='+', type=str, default='yolov5s.pt', help='model.pt path(s)')
|
| 150 |
+
parser.add_argument('--source', type=str, default='inference/images', help='source') # file/folder, 0 for webcam
|
| 151 |
+
parser.add_argument('--output', type=str, default='inference/output', help='output folder') # output folder
|
| 152 |
+
parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
|
| 153 |
+
parser.add_argument('--conf-thres', type=float, default=0.4, help='object confidence threshold')
|
| 154 |
+
parser.add_argument('--iou-thres', type=float, default=0.5, help='IOU threshold for NMS')
|
| 155 |
+
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
|
| 156 |
+
parser.add_argument('--view-img', action='store_true', help='display results')
|
| 157 |
+
parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
|
| 158 |
+
parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
|
| 159 |
+
parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
|
| 160 |
+
parser.add_argument('--augment', action='store_true', help='augmented inference')
|
| 161 |
+
parser.add_argument('--update', action='store_true', help='update all models')
|
| 162 |
+
opt = parser.parse_args()
|
| 163 |
+
print(opt)
|
| 164 |
+
|
| 165 |
+
with torch.no_grad():
|
| 166 |
+
if opt.update: # update all models (to fix SourceChangeWarning)
|
| 167 |
+
for opt.weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']:
|
| 168 |
+
detect()
|
| 169 |
+
strip_optimizer(opt.weights)
|
| 170 |
+
else:
|
| 171 |
+
detect()
|
yolov5_anime/hubconf.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""File for accessing YOLOv5 via PyTorch Hub https://pytorch.org/hub/
|
| 2 |
+
|
| 3 |
+
Usage:
|
| 4 |
+
import torch
|
| 5 |
+
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True, channels=3, classes=80)
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
dependencies = ['torch', 'yaml']
|
| 9 |
+
import os
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
|
| 13 |
+
from models.yolo import Model
|
| 14 |
+
from utils.google_utils import attempt_download
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def create(name, pretrained, channels, classes):
|
| 18 |
+
"""Creates a specified YOLOv5 model
|
| 19 |
+
|
| 20 |
+
Arguments:
|
| 21 |
+
name (str): name of model, i.e. 'yolov5s'
|
| 22 |
+
pretrained (bool): load pretrained weights into the model
|
| 23 |
+
channels (int): number of input channels
|
| 24 |
+
classes (int): number of model classes
|
| 25 |
+
|
| 26 |
+
Returns:
|
| 27 |
+
pytorch model
|
| 28 |
+
"""
|
| 29 |
+
config = os.path.join(os.path.dirname(__file__), 'models', '%s.yaml' % name) # model.yaml path
|
| 30 |
+
try:
|
| 31 |
+
model = Model(config, channels, classes)
|
| 32 |
+
if pretrained:
|
| 33 |
+
ckpt = '%s.pt' % name # checkpoint filename
|
| 34 |
+
attempt_download(ckpt) # download if not found locally
|
| 35 |
+
state_dict = torch.load(ckpt, map_location=torch.device('cpu'))['model'].float().state_dict() # to FP32
|
| 36 |
+
state_dict = {k: v for k, v in state_dict.items() if model.state_dict()[k].shape == v.shape} # filter
|
| 37 |
+
model.load_state_dict(state_dict, strict=False) # load
|
| 38 |
+
return model
|
| 39 |
+
|
| 40 |
+
except Exception as e:
|
| 41 |
+
help_url = 'https://github.com/ultralytics/yolov5/issues/36'
|
| 42 |
+
s = 'Cache maybe be out of date, deleting cache and retrying may solve this. See %s for help.' % help_url
|
| 43 |
+
raise Exception(s) from e
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def yolov5s(pretrained=False, channels=3, classes=80):
|
| 47 |
+
"""YOLOv5-small model from https://github.com/ultralytics/yolov5
|
| 48 |
+
|
| 49 |
+
Arguments:
|
| 50 |
+
pretrained (bool): load pretrained weights into the model, default=False
|
| 51 |
+
channels (int): number of input channels, default=3
|
| 52 |
+
classes (int): number of model classes, default=80
|
| 53 |
+
|
| 54 |
+
Returns:
|
| 55 |
+
pytorch model
|
| 56 |
+
"""
|
| 57 |
+
return create('yolov5s', pretrained, channels, classes)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def yolov5m(pretrained=False, channels=3, classes=80):
|
| 61 |
+
"""YOLOv5-medium model from https://github.com/ultralytics/yolov5
|
| 62 |
+
|
| 63 |
+
Arguments:
|
| 64 |
+
pretrained (bool): load pretrained weights into the model, default=False
|
| 65 |
+
channels (int): number of input channels, default=3
|
| 66 |
+
classes (int): number of model classes, default=80
|
| 67 |
+
|
| 68 |
+
Returns:
|
| 69 |
+
pytorch model
|
| 70 |
+
"""
|
| 71 |
+
return create('yolov5m', pretrained, channels, classes)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def yolov5l(pretrained=False, channels=3, classes=80):
|
| 75 |
+
"""YOLOv5-large model from https://github.com/ultralytics/yolov5
|
| 76 |
+
|
| 77 |
+
Arguments:
|
| 78 |
+
pretrained (bool): load pretrained weights into the model, default=False
|
| 79 |
+
channels (int): number of input channels, default=3
|
| 80 |
+
classes (int): number of model classes, default=80
|
| 81 |
+
|
| 82 |
+
Returns:
|
| 83 |
+
pytorch model
|
| 84 |
+
"""
|
| 85 |
+
return create('yolov5l', pretrained, channels, classes)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def yolov5x(pretrained=False, channels=3, classes=80):
|
| 89 |
+
"""YOLOv5-xlarge model from https://github.com/ultralytics/yolov5
|
| 90 |
+
|
| 91 |
+
Arguments:
|
| 92 |
+
pretrained (bool): load pretrained weights into the model, default=False
|
| 93 |
+
channels (int): number of input channels, default=3
|
| 94 |
+
classes (int): number of model classes, default=80
|
| 95 |
+
|
| 96 |
+
Returns:
|
| 97 |
+
pytorch model
|
| 98 |
+
"""
|
| 99 |
+
return create('yolov5x', pretrained, channels, classes)
|
yolov5_anime/models/__init__.py
ADDED
|
File without changes
|
yolov5_anime/models/common.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file contains modules common to various models
|
| 2 |
+
import math
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def autopad(k, p=None): # kernel, padding
|
| 9 |
+
# Pad to 'same'
|
| 10 |
+
if p is None:
|
| 11 |
+
p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
|
| 12 |
+
return p
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def DWConv(c1, c2, k=1, s=1, act=True):
|
| 16 |
+
# Depthwise convolution
|
| 17 |
+
return Conv(c1, c2, k, s, g=math.gcd(c1, c2), act=act)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class Conv(nn.Module):
|
| 21 |
+
# Standard convolution
|
| 22 |
+
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
|
| 23 |
+
super(Conv, self).__init__()
|
| 24 |
+
self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False)
|
| 25 |
+
self.bn = nn.BatchNorm2d(c2)
|
| 26 |
+
self.act = nn.LeakyReLU(0.1, inplace=True) if act else nn.Identity()
|
| 27 |
+
|
| 28 |
+
def forward(self, x):
|
| 29 |
+
return self.act(self.bn(self.conv(x)))
|
| 30 |
+
|
| 31 |
+
def fuseforward(self, x):
|
| 32 |
+
return self.act(self.conv(x))
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class Bottleneck(nn.Module):
|
| 36 |
+
# Standard bottleneck
|
| 37 |
+
def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
|
| 38 |
+
super(Bottleneck, self).__init__()
|
| 39 |
+
c_ = int(c2 * e) # hidden channels
|
| 40 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
| 41 |
+
self.cv2 = Conv(c_, c2, 3, 1, g=g)
|
| 42 |
+
self.add = shortcut and c1 == c2
|
| 43 |
+
|
| 44 |
+
def forward(self, x):
|
| 45 |
+
return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class BottleneckCSP(nn.Module):
|
| 49 |
+
# CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
|
| 50 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
|
| 51 |
+
super(BottleneckCSP, self).__init__()
|
| 52 |
+
c_ = int(c2 * e) # hidden channels
|
| 53 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
| 54 |
+
self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)
|
| 55 |
+
self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)
|
| 56 |
+
self.cv4 = Conv(2 * c_, c2, 1, 1)
|
| 57 |
+
self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3)
|
| 58 |
+
self.act = nn.LeakyReLU(0.1, inplace=True)
|
| 59 |
+
self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
|
| 60 |
+
|
| 61 |
+
def forward(self, x):
|
| 62 |
+
y1 = self.cv3(self.m(self.cv1(x)))
|
| 63 |
+
y2 = self.cv2(x)
|
| 64 |
+
return self.cv4(self.act(self.bn(torch.cat((y1, y2), dim=1))))
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class SPP(nn.Module):
|
| 68 |
+
# Spatial pyramid pooling layer used in YOLOv3-SPP
|
| 69 |
+
def __init__(self, c1, c2, k=(5, 9, 13)):
|
| 70 |
+
super(SPP, self).__init__()
|
| 71 |
+
c_ = c1 // 2 # hidden channels
|
| 72 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
| 73 |
+
self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)
|
| 74 |
+
self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
|
| 75 |
+
|
| 76 |
+
def forward(self, x):
|
| 77 |
+
x = self.cv1(x)
|
| 78 |
+
return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class Focus(nn.Module):
|
| 82 |
+
# Focus wh information into c-space
|
| 83 |
+
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
|
| 84 |
+
super(Focus, self).__init__()
|
| 85 |
+
self.conv = Conv(c1 * 4, c2, k, s, p, g, act)
|
| 86 |
+
|
| 87 |
+
def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
|
| 88 |
+
return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1))
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class Concat(nn.Module):
|
| 92 |
+
# Concatenate a list of tensors along dimension
|
| 93 |
+
def __init__(self, dimension=1):
|
| 94 |
+
super(Concat, self).__init__()
|
| 95 |
+
self.d = dimension
|
| 96 |
+
|
| 97 |
+
def forward(self, x):
|
| 98 |
+
return torch.cat(x, self.d)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class Flatten(nn.Module):
|
| 102 |
+
# Use after nn.AdaptiveAvgPool2d(1) to remove last 2 dimensions
|
| 103 |
+
@staticmethod
|
| 104 |
+
def forward(x):
|
| 105 |
+
return x.view(x.size(0), -1)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
class Classify(nn.Module):
|
| 109 |
+
# Classification head, i.e. x(b,c1,20,20) to x(b,c2)
|
| 110 |
+
def __init__(self, c1, c2, k=1, s=1, p=None, g=1): # ch_in, ch_out, kernel, stride, padding, groups
|
| 111 |
+
super(Classify, self).__init__()
|
| 112 |
+
self.aap = nn.AdaptiveAvgPool2d(1) # to x(b,c1,1,1)
|
| 113 |
+
self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False) # to x(b,c2,1,1)
|
| 114 |
+
self.flat = Flatten()
|
| 115 |
+
|
| 116 |
+
def forward(self, x):
|
| 117 |
+
z = torch.cat([self.aap(y) for y in (x if isinstance(x, list) else [x])], 1) # cat if list
|
| 118 |
+
return self.flat(self.conv(z)) # flatten to x(b,c2)
|
yolov5_anime/models/experimental.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file contains experimental modules
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
|
| 7 |
+
from models.common import Conv, DWConv
|
| 8 |
+
from utils.google_utils import attempt_download
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class CrossConv(nn.Module):
|
| 12 |
+
# Cross Convolution Downsample
|
| 13 |
+
def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):
|
| 14 |
+
# ch_in, ch_out, kernel, stride, groups, expansion, shortcut
|
| 15 |
+
super(CrossConv, self).__init__()
|
| 16 |
+
c_ = int(c2 * e) # hidden channels
|
| 17 |
+
self.cv1 = Conv(c1, c_, (1, k), (1, s))
|
| 18 |
+
self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)
|
| 19 |
+
self.add = shortcut and c1 == c2
|
| 20 |
+
|
| 21 |
+
def forward(self, x):
|
| 22 |
+
return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class C3(nn.Module):
|
| 26 |
+
# Cross Convolution CSP
|
| 27 |
+
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
|
| 28 |
+
super(C3, self).__init__()
|
| 29 |
+
c_ = int(c2 * e) # hidden channels
|
| 30 |
+
self.cv1 = Conv(c1, c_, 1, 1)
|
| 31 |
+
self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)
|
| 32 |
+
self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)
|
| 33 |
+
self.cv4 = Conv(2 * c_, c2, 1, 1)
|
| 34 |
+
self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3)
|
| 35 |
+
self.act = nn.LeakyReLU(0.1, inplace=True)
|
| 36 |
+
self.m = nn.Sequential(*[CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)])
|
| 37 |
+
|
| 38 |
+
def forward(self, x):
|
| 39 |
+
y1 = self.cv3(self.m(self.cv1(x)))
|
| 40 |
+
y2 = self.cv2(x)
|
| 41 |
+
return self.cv4(self.act(self.bn(torch.cat((y1, y2), dim=1))))
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class Sum(nn.Module):
|
| 45 |
+
# Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
|
| 46 |
+
def __init__(self, n, weight=False): # n: number of inputs
|
| 47 |
+
super(Sum, self).__init__()
|
| 48 |
+
self.weight = weight # apply weights boolean
|
| 49 |
+
self.iter = range(n - 1) # iter object
|
| 50 |
+
if weight:
|
| 51 |
+
self.w = nn.Parameter(-torch.arange(1., n) / 2, requires_grad=True) # layer weights
|
| 52 |
+
|
| 53 |
+
def forward(self, x):
|
| 54 |
+
y = x[0] # no weight
|
| 55 |
+
if self.weight:
|
| 56 |
+
w = torch.sigmoid(self.w) * 2
|
| 57 |
+
for i in self.iter:
|
| 58 |
+
y = y + x[i + 1] * w[i]
|
| 59 |
+
else:
|
| 60 |
+
for i in self.iter:
|
| 61 |
+
y = y + x[i + 1]
|
| 62 |
+
return y
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class GhostConv(nn.Module):
|
| 66 |
+
# Ghost Convolution https://github.com/huawei-noah/ghostnet
|
| 67 |
+
def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups
|
| 68 |
+
super(GhostConv, self).__init__()
|
| 69 |
+
c_ = c2 // 2 # hidden channels
|
| 70 |
+
self.cv1 = Conv(c1, c_, k, s, g, act)
|
| 71 |
+
self.cv2 = Conv(c_, c_, 5, 1, c_, act)
|
| 72 |
+
|
| 73 |
+
def forward(self, x):
|
| 74 |
+
y = self.cv1(x)
|
| 75 |
+
return torch.cat([y, self.cv2(y)], 1)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class GhostBottleneck(nn.Module):
|
| 79 |
+
# Ghost Bottleneck https://github.com/huawei-noah/ghostnet
|
| 80 |
+
def __init__(self, c1, c2, k, s):
|
| 81 |
+
super(GhostBottleneck, self).__init__()
|
| 82 |
+
c_ = c2 // 2
|
| 83 |
+
self.conv = nn.Sequential(GhostConv(c1, c_, 1, 1), # pw
|
| 84 |
+
DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw
|
| 85 |
+
GhostConv(c_, c2, 1, 1, act=False)) # pw-linear
|
| 86 |
+
self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False),
|
| 87 |
+
Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity()
|
| 88 |
+
|
| 89 |
+
def forward(self, x):
|
| 90 |
+
return self.conv(x) + self.shortcut(x)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class MixConv2d(nn.Module):
|
| 94 |
+
# Mixed Depthwise Conv https://arxiv.org/abs/1907.09595
|
| 95 |
+
def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True):
|
| 96 |
+
super(MixConv2d, self).__init__()
|
| 97 |
+
groups = len(k)
|
| 98 |
+
if equal_ch: # equal c_ per group
|
| 99 |
+
i = torch.linspace(0, groups - 1E-6, c2).floor() # c2 indices
|
| 100 |
+
c_ = [(i == g).sum() for g in range(groups)] # intermediate channels
|
| 101 |
+
else: # equal weight.numel() per group
|
| 102 |
+
b = [c2] + [0] * groups
|
| 103 |
+
a = np.eye(groups + 1, groups, k=-1)
|
| 104 |
+
a -= np.roll(a, 1, axis=1)
|
| 105 |
+
a *= np.array(k) ** 2
|
| 106 |
+
a[0] = 1
|
| 107 |
+
c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
|
| 108 |
+
|
| 109 |
+
self.m = nn.ModuleList([nn.Conv2d(c1, int(c_[g]), k[g], s, k[g] // 2, bias=False) for g in range(groups)])
|
| 110 |
+
self.bn = nn.BatchNorm2d(c2)
|
| 111 |
+
self.act = nn.LeakyReLU(0.1, inplace=True)
|
| 112 |
+
|
| 113 |
+
def forward(self, x):
|
| 114 |
+
return x + self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class Ensemble(nn.ModuleList):
|
| 118 |
+
# Ensemble of models
|
| 119 |
+
def __init__(self):
|
| 120 |
+
super(Ensemble, self).__init__()
|
| 121 |
+
|
| 122 |
+
def forward(self, x, augment=False):
|
| 123 |
+
y = []
|
| 124 |
+
for module in self:
|
| 125 |
+
y.append(module(x, augment)[0])
|
| 126 |
+
# y = torch.stack(y).max(0)[0] # max ensemble
|
| 127 |
+
# y = torch.cat(y, 1) # nms ensemble
|
| 128 |
+
y = torch.stack(y).mean(0) # mean ensemble
|
| 129 |
+
return y, None # inference, train output
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def attempt_load(weights, map_location=None):
|
| 133 |
+
# Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a
|
| 134 |
+
model = Ensemble()
|
| 135 |
+
for w in weights if isinstance(weights, list) else [weights]:
|
| 136 |
+
attempt_download(w)
|
| 137 |
+
model.append(torch.load(w, map_location=map_location)['model'].float().fuse().eval()) # load FP32 model
|
| 138 |
+
|
| 139 |
+
if len(model) == 1:
|
| 140 |
+
return model[-1] # return model
|
| 141 |
+
else:
|
| 142 |
+
print('Ensemble created with %s\n' % weights)
|
| 143 |
+
for k in ['names', 'stride']:
|
| 144 |
+
setattr(model, k, getattr(model[-1], k))
|
| 145 |
+
return model # return ensemble
|
yolov5_anime/models/export.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exports a YOLOv5 *.pt model to ONNX and TorchScript formats
|
| 2 |
+
|
| 3 |
+
Usage:
|
| 4 |
+
$ export PYTHONPATH="$PWD" && python models/export.py --weights ./weights/yolov5s.pt --img 640 --batch 1
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import argparse
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
from utils.google_utils import attempt_download
|
| 12 |
+
|
| 13 |
+
if __name__ == '__main__':
|
| 14 |
+
parser = argparse.ArgumentParser()
|
| 15 |
+
parser.add_argument('--weights', type=str, default='./yolov5s.pt', help='weights path')
|
| 16 |
+
parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image size')
|
| 17 |
+
parser.add_argument('--batch-size', type=int, default=1, help='batch size')
|
| 18 |
+
opt = parser.parse_args()
|
| 19 |
+
opt.img_size *= 2 if len(opt.img_size) == 1 else 1 # expand
|
| 20 |
+
print(opt)
|
| 21 |
+
|
| 22 |
+
# Input
|
| 23 |
+
img = torch.zeros((opt.batch_size, 3, *opt.img_size)) # image size(1,3,320,192) iDetection
|
| 24 |
+
|
| 25 |
+
# Load PyTorch model
|
| 26 |
+
attempt_download(opt.weights)
|
| 27 |
+
model = torch.load(opt.weights, map_location=torch.device('cpu'))['model'].float()
|
| 28 |
+
model.eval()
|
| 29 |
+
model.model[-1].export = True # set Detect() layer export=True
|
| 30 |
+
y = model(img) # dry run
|
| 31 |
+
|
| 32 |
+
# TorchScript export
|
| 33 |
+
try:
|
| 34 |
+
print('\nStarting TorchScript export with torch %s...' % torch.__version__)
|
| 35 |
+
f = opt.weights.replace('.pt', '.torchscript.pt') # filename
|
| 36 |
+
ts = torch.jit.trace(model, img)
|
| 37 |
+
ts.save(f)
|
| 38 |
+
print('TorchScript export success, saved as %s' % f)
|
| 39 |
+
except Exception as e:
|
| 40 |
+
print('TorchScript export failure: %s' % e)
|
| 41 |
+
|
| 42 |
+
# ONNX export
|
| 43 |
+
try:
|
| 44 |
+
import onnx
|
| 45 |
+
|
| 46 |
+
print('\nStarting ONNX export with onnx %s...' % onnx.__version__)
|
| 47 |
+
f = opt.weights.replace('.pt', '.onnx') # filename
|
| 48 |
+
model.fuse() # only for ONNX
|
| 49 |
+
torch.onnx.export(model, img, f, verbose=False, opset_version=12, input_names=['images'],
|
| 50 |
+
output_names=['classes', 'boxes'] if y is None else ['output'])
|
| 51 |
+
|
| 52 |
+
# Checks
|
| 53 |
+
onnx_model = onnx.load(f) # load onnx model
|
| 54 |
+
onnx.checker.check_model(onnx_model) # check onnx model
|
| 55 |
+
print(onnx.helper.printable_graph(onnx_model.graph)) # print a human readable model
|
| 56 |
+
print('ONNX export success, saved as %s' % f)
|
| 57 |
+
except Exception as e:
|
| 58 |
+
print('ONNX export failure: %s' % e)
|
| 59 |
+
|
| 60 |
+
# CoreML export
|
| 61 |
+
try:
|
| 62 |
+
import coremltools as ct
|
| 63 |
+
|
| 64 |
+
print('\nStarting CoreML export with coremltools %s...' % ct.__version__)
|
| 65 |
+
# convert model from torchscript and apply pixel scaling as per detect.py
|
| 66 |
+
model = ct.convert(ts, inputs=[ct.ImageType(name='images', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])])
|
| 67 |
+
f = opt.weights.replace('.pt', '.mlmodel') # filename
|
| 68 |
+
model.save(f)
|
| 69 |
+
print('CoreML export success, saved as %s' % f)
|
| 70 |
+
except Exception as e:
|
| 71 |
+
print('CoreML export failure: %s' % e)
|
| 72 |
+
|
| 73 |
+
# Finish
|
| 74 |
+
print('\nExport complete. Visualize with https://github.com/lutzroeder/netron.')
|
yolov5_anime/models/hub/yolov3-spp.yaml
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# parameters
|
| 2 |
+
nc: 80 # number of classes
|
| 3 |
+
depth_multiple: 1.0 # model depth multiple
|
| 4 |
+
width_multiple: 1.0 # layer channel multiple
|
| 5 |
+
|
| 6 |
+
# anchors
|
| 7 |
+
anchors:
|
| 8 |
+
- [10,13, 16,30, 33,23] # P3/8
|
| 9 |
+
- [30,61, 62,45, 59,119] # P4/16
|
| 10 |
+
- [116,90, 156,198, 373,326] # P5/32
|
| 11 |
+
|
| 12 |
+
# darknet53 backbone
|
| 13 |
+
backbone:
|
| 14 |
+
# [from, number, module, args]
|
| 15 |
+
[[-1, 1, Conv, [32, 3, 1]], # 0
|
| 16 |
+
[-1, 1, Conv, [64, 3, 2]], # 1-P1/2
|
| 17 |
+
[-1, 1, Bottleneck, [64]],
|
| 18 |
+
[-1, 1, Conv, [128, 3, 2]], # 3-P2/4
|
| 19 |
+
[-1, 2, Bottleneck, [128]],
|
| 20 |
+
[-1, 1, Conv, [256, 3, 2]], # 5-P3/8
|
| 21 |
+
[-1, 8, Bottleneck, [256]],
|
| 22 |
+
[-1, 1, Conv, [512, 3, 2]], # 7-P4/16
|
| 23 |
+
[-1, 8, Bottleneck, [512]],
|
| 24 |
+
[-1, 1, Conv, [1024, 3, 2]], # 9-P5/32
|
| 25 |
+
[-1, 4, Bottleneck, [1024]], # 10
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
# YOLOv3-SPP head
|
| 29 |
+
head:
|
| 30 |
+
[[-1, 1, Bottleneck, [1024, False]],
|
| 31 |
+
[-1, 1, SPP, [512, [5, 9, 13]]],
|
| 32 |
+
[-1, 1, Conv, [1024, 3, 1]],
|
| 33 |
+
[-1, 1, Conv, [512, 1, 1]],
|
| 34 |
+
[-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large)
|
| 35 |
+
|
| 36 |
+
[-2, 1, Conv, [256, 1, 1]],
|
| 37 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
| 38 |
+
[[-1, 8], 1, Concat, [1]], # cat backbone P4
|
| 39 |
+
[-1, 1, Bottleneck, [512, False]],
|
| 40 |
+
[-1, 1, Bottleneck, [512, False]],
|
| 41 |
+
[-1, 1, Conv, [256, 1, 1]],
|
| 42 |
+
[-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium)
|
| 43 |
+
|
| 44 |
+
[-2, 1, Conv, [128, 1, 1]],
|
| 45 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
| 46 |
+
[[-1, 6], 1, Concat, [1]], # cat backbone P3
|
| 47 |
+
[-1, 1, Bottleneck, [256, False]],
|
| 48 |
+
[-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small)
|
| 49 |
+
|
| 50 |
+
[[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
|
| 51 |
+
]
|
yolov5_anime/models/hub/yolov5-fpn.yaml
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# parameters
|
| 2 |
+
nc: 80 # number of classes
|
| 3 |
+
depth_multiple: 1.0 # model depth multiple
|
| 4 |
+
width_multiple: 1.0 # layer channel multiple
|
| 5 |
+
|
| 6 |
+
# anchors
|
| 7 |
+
anchors:
|
| 8 |
+
- [10,13, 16,30, 33,23] # P3/8
|
| 9 |
+
- [30,61, 62,45, 59,119] # P4/16
|
| 10 |
+
- [116,90, 156,198, 373,326] # P5/32
|
| 11 |
+
|
| 12 |
+
# YOLOv5 backbone
|
| 13 |
+
backbone:
|
| 14 |
+
# [from, number, module, args]
|
| 15 |
+
[[-1, 1, Focus, [64, 3]], # 0-P1/2
|
| 16 |
+
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
| 17 |
+
[-1, 3, Bottleneck, [128]],
|
| 18 |
+
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
| 19 |
+
[-1, 9, BottleneckCSP, [256]],
|
| 20 |
+
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
| 21 |
+
[-1, 9, BottleneckCSP, [512]],
|
| 22 |
+
[-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
|
| 23 |
+
[-1, 1, SPP, [1024, [5, 9, 13]]],
|
| 24 |
+
[-1, 6, BottleneckCSP, [1024]], # 9
|
| 25 |
+
]
|
| 26 |
+
|
| 27 |
+
# YOLOv5 FPN head
|
| 28 |
+
head:
|
| 29 |
+
[[-1, 3, BottleneckCSP, [1024, False]], # 10 (P5/32-large)
|
| 30 |
+
|
| 31 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
| 32 |
+
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
| 33 |
+
[-1, 1, Conv, [512, 1, 1]],
|
| 34 |
+
[-1, 3, BottleneckCSP, [512, False]], # 14 (P4/16-medium)
|
| 35 |
+
|
| 36 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
| 37 |
+
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
| 38 |
+
[-1, 1, Conv, [256, 1, 1]],
|
| 39 |
+
[-1, 3, BottleneckCSP, [256, False]], # 18 (P3/8-small)
|
| 40 |
+
|
| 41 |
+
[[18, 14, 10], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
|
| 42 |
+
]
|
yolov5_anime/models/hub/yolov5-panet.yaml
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# parameters
|
| 2 |
+
nc: 80 # number of classes
|
| 3 |
+
depth_multiple: 1.0 # model depth multiple
|
| 4 |
+
width_multiple: 1.0 # layer channel multiple
|
| 5 |
+
|
| 6 |
+
# anchors
|
| 7 |
+
anchors:
|
| 8 |
+
- [116,90, 156,198, 373,326] # P5/32
|
| 9 |
+
- [30,61, 62,45, 59,119] # P4/16
|
| 10 |
+
- [10,13, 16,30, 33,23] # P3/8
|
| 11 |
+
|
| 12 |
+
# YOLOv5 backbone
|
| 13 |
+
backbone:
|
| 14 |
+
# [from, number, module, args]
|
| 15 |
+
[[-1, 1, Focus, [64, 3]], # 0-P1/2
|
| 16 |
+
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
| 17 |
+
[-1, 3, BottleneckCSP, [128]],
|
| 18 |
+
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
| 19 |
+
[-1, 9, BottleneckCSP, [256]],
|
| 20 |
+
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
| 21 |
+
[-1, 9, BottleneckCSP, [512]],
|
| 22 |
+
[-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
|
| 23 |
+
[-1, 1, SPP, [1024, [5, 9, 13]]],
|
| 24 |
+
[-1, 3, BottleneckCSP, [1024, False]], # 9
|
| 25 |
+
]
|
| 26 |
+
|
| 27 |
+
# YOLOv5 PANet head
|
| 28 |
+
head:
|
| 29 |
+
[[-1, 1, Conv, [512, 1, 1]],
|
| 30 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
| 31 |
+
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
| 32 |
+
[-1, 3, BottleneckCSP, [512, False]], # 13
|
| 33 |
+
|
| 34 |
+
[-1, 1, Conv, [256, 1, 1]],
|
| 35 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
| 36 |
+
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
| 37 |
+
[-1, 3, BottleneckCSP, [256, False]], # 17 (P3/8-small)
|
| 38 |
+
|
| 39 |
+
[-1, 1, Conv, [256, 3, 2]],
|
| 40 |
+
[[-1, 14], 1, Concat, [1]], # cat head P4
|
| 41 |
+
[-1, 3, BottleneckCSP, [512, False]], # 20 (P4/16-medium)
|
| 42 |
+
|
| 43 |
+
[-1, 1, Conv, [512, 3, 2]],
|
| 44 |
+
[[-1, 10], 1, Concat, [1]], # cat head P5
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import math
|
| 3 |
+
from copy import deepcopy
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
|
| 9 |
+
from models.common import Conv, Bottleneck, SPP, DWConv, Focus, BottleneckCSP, Concat
|
| 10 |
+
from models.experimental import MixConv2d, CrossConv, C3
|
| 11 |
+
from utils.general import check_anchor_order, make_divisible, check_file
|
| 12 |
+
from utils.torch_utils import (
|
| 13 |
+
time_synchronized, fuse_conv_and_bn, model_info, scale_img, initialize_weights, select_device)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class Detect(nn.Module):
|
| 17 |
+
def __init__(self, nc=80, anchors=(), ch=()): # detection layer
|
| 18 |
+
super(Detect, self).__init__()
|
| 19 |
+
self.stride = None # strides computed during build
|
| 20 |
+
self.nc = nc # number of classes
|
| 21 |
+
self.no = nc + 5 # number of outputs per anchor
|
| 22 |
+
self.nl = len(anchors) # number of detection layers
|
| 23 |
+
self.na = len(anchors[0]) // 2 # number of anchors
|
| 24 |
+
self.grid = [torch.zeros(1)] * self.nl # init grid
|
| 25 |
+
a = torch.tensor(anchors).float().view(self.nl, -1, 2)
|
| 26 |
+
self.register_buffer('anchors', a) # shape(nl,na,2)
|
| 27 |
+
self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2)
|
| 28 |
+
self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
|
| 29 |
+
self.export = False # onnx export
|
| 30 |
+
|
| 31 |
+
def forward(self, x):
|
| 32 |
+
# x = x.copy() # for profiling
|
| 33 |
+
z = [] # inference output
|
| 34 |
+
self.training |= self.export
|
| 35 |
+
for i in range(self.nl):
|
| 36 |
+
x[i] = self.m[i](x[i]) # conv
|
| 37 |
+
bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
|
| 38 |
+
x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
|
| 39 |
+
|
| 40 |
+
if not self.training: # inference
|
| 41 |
+
if self.grid[i].shape[2:4] != x[i].shape[2:4]:
|
| 42 |
+
self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
|
| 43 |
+
|
| 44 |
+
y = x[i].sigmoid()
|
| 45 |
+
y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i].to(x[i].device)) * self.stride[i] # xy
|
| 46 |
+
y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
|
| 47 |
+
z.append(y.view(bs, -1, self.no))
|
| 48 |
+
|
| 49 |
+
return x if self.training else (torch.cat(z, 1), x)
|
| 50 |
+
|
| 51 |
+
@staticmethod
|
| 52 |
+
def _make_grid(nx=20, ny=20):
|
| 53 |
+
yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
|
| 54 |
+
return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class Model(nn.Module):
|
| 58 |
+
def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None): # model, input channels, number of classes
|
| 59 |
+
super(Model, self).__init__()
|
| 60 |
+
if isinstance(cfg, dict):
|
| 61 |
+
self.yaml = cfg # model dict
|
| 62 |
+
else: # is *.yaml
|
| 63 |
+
import yaml # for torch hub
|
| 64 |
+
self.yaml_file = Path(cfg).name
|
| 65 |
+
with open(cfg) as f:
|
| 66 |
+
self.yaml = yaml.load(f, Loader=yaml.FullLoader) # model dict
|
| 67 |
+
|
| 68 |
+
# Define model
|
| 69 |
+
if nc and nc != self.yaml['nc']:
|
| 70 |
+
print('Overriding %s nc=%g with nc=%g' % (cfg, self.yaml['nc'], nc))
|
| 71 |
+
self.yaml['nc'] = nc # override yaml value
|
| 72 |
+
self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist, ch_out
|
| 73 |
+
# print([x.shape for x in self.forward(torch.zeros(1, ch, 64, 64))])
|
| 74 |
+
|
| 75 |
+
# Build strides, anchors
|
| 76 |
+
m = self.model[-1] # Detect()
|
| 77 |
+
if isinstance(m, Detect):
|
| 78 |
+
s = 128 # 2x min stride
|
| 79 |
+
m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward
|
| 80 |
+
m.anchors /= m.stride.view(-1, 1, 1)
|
| 81 |
+
check_anchor_order(m)
|
| 82 |
+
self.stride = m.stride
|
| 83 |
+
self._initialize_biases() # only run once
|
| 84 |
+
# print('Strides: %s' % m.stride.tolist())
|
| 85 |
+
|
| 86 |
+
# Init weights, biases
|
| 87 |
+
initialize_weights(self)
|
| 88 |
+
self.info()
|
| 89 |
+
print('')
|
| 90 |
+
|
| 91 |
+
def forward(self, x, augment=False, profile=False):
|
| 92 |
+
if augment:
|
| 93 |
+
img_size = x.shape[-2:] # height, width
|
| 94 |
+
s = [1, 0.83, 0.67] # scales
|
| 95 |
+
f = [None, 3, None] # flips (2-ud, 3-lr)
|
| 96 |
+
y = [] # outputs
|
| 97 |
+
for si, fi in zip(s, f):
|
| 98 |
+
xi = scale_img(x.flip(fi) if fi else x, si)
|
| 99 |
+
yi = self.forward_once(xi)[0] # forward
|
| 100 |
+
# cv2.imwrite('img%g.jpg' % s, 255 * xi[0].numpy().transpose((1, 2, 0))[:, :, ::-1]) # save
|
| 101 |
+
yi[..., :4] /= si # de-scale
|
| 102 |
+
if fi == 2:
|
| 103 |
+
yi[..., 1] = img_size[0] - yi[..., 1] # de-flip ud
|
| 104 |
+
elif fi == 3:
|
| 105 |
+
yi[..., 0] = img_size[1] - yi[..., 0] # de-flip lr
|
| 106 |
+
y.append(yi)
|
| 107 |
+
return torch.cat(y, 1), None # augmented inference, train
|
| 108 |
+
else:
|
| 109 |
+
return self.forward_once(x, profile) # single-scale inference, train
|
| 110 |
+
|
| 111 |
+
def forward_once(self, x, profile=False):
|
| 112 |
+
y, dt = [], [] # outputs
|
| 113 |
+
for m in self.model:
|
| 114 |
+
if m.f != -1: # if not from previous layer
|
| 115 |
+
x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
|
| 116 |
+
|
| 117 |
+
if profile:
|
| 118 |
+
try:
|
| 119 |
+
import thop
|
| 120 |
+
o = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # FLOPS
|
| 121 |
+
except:
|
| 122 |
+
o = 0
|
| 123 |
+
t = time_synchronized()
|
| 124 |
+
for _ in range(10):
|
| 125 |
+
_ = m(x)
|
| 126 |
+
dt.append((time_synchronized() - t) * 100)
|
| 127 |
+
print('%10.1f%10.0f%10.1fms %-40s' % (o, m.np, dt[-1], m.type))
|
| 128 |
+
|
| 129 |
+
x = m(x) # run
|
| 130 |
+
y.append(x if m.i in self.save else None) # save output
|
| 131 |
+
|
| 132 |
+
if profile:
|
| 133 |
+
print('%.1fms total' % sum(dt))
|
| 134 |
+
return x
|
| 135 |
+
|
| 136 |
+
def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency
|
| 137 |
+
# cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
|
| 138 |
+
m = self.model[-1] # Detect() module
|
| 139 |
+
for mi, s in zip(m.m, m.stride): # from
|
| 140 |
+
b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
|
| 141 |
+
b[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
|
| 142 |
+
b[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls
|
| 143 |
+
mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
|
| 144 |
+
|
| 145 |
+
def _print_biases(self):
|
| 146 |
+
m = self.model[-1] # Detect() module
|
| 147 |
+
for mi in m.m: # from
|
| 148 |
+
b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85)
|
| 149 |
+
print(('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean()))
|
| 150 |
+
|
| 151 |
+
# def _print_weights(self):
|
| 152 |
+
# for m in self.model.modules():
|
| 153 |
+
# if type(m) is Bottleneck:
|
| 154 |
+
# print('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights
|
| 155 |
+
|
| 156 |
+
def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
|
| 157 |
+
print('Fusing layers... ', end='')
|
| 158 |
+
for m in self.model.modules():
|
| 159 |
+
if type(m) is Conv:
|
| 160 |
+
m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatability
|
| 161 |
+
m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
|
| 162 |
+
m.bn = None # remove batchnorm
|
| 163 |
+
m.forward = m.fuseforward # update forward
|
| 164 |
+
self.info()
|
| 165 |
+
return self
|
| 166 |
+
|
| 167 |
+
def info(self): # print model information
|
| 168 |
+
model_info(self)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def parse_model(d, ch): # model_dict, input_channels(3)
|
| 172 |
+
print('\n%3s%18s%3s%10s %-40s%-30s' % ('', 'from', 'n', 'params', 'module', 'arguments'))
|
| 173 |
+
anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']
|
| 174 |
+
na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
|
| 175 |
+
no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
|
| 176 |
+
|
| 177 |
+
layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
|
| 178 |
+
for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
|
| 179 |
+
m = eval(m) if isinstance(m, str) else m # eval strings
|
| 180 |
+
for j, a in enumerate(args):
|
| 181 |
+
try:
|
| 182 |
+
args[j] = eval(a) if isinstance(a, str) else a # eval strings
|
| 183 |
+
except:
|
| 184 |
+
pass
|
| 185 |
+
|
| 186 |
+
n = max(round(n * gd), 1) if n > 1 else n # depth gain
|
| 187 |
+
if m in [nn.Conv2d, Conv, Bottleneck, SPP, DWConv, MixConv2d, Focus, CrossConv, BottleneckCSP, C3]:
|
| 188 |
+
c1, c2 = ch[f], args[0]
|
| 189 |
+
|
| 190 |
+
# Normal
|
| 191 |
+
# if i > 0 and args[0] != no: # channel expansion factor
|
| 192 |
+
# ex = 1.75 # exponential (default 2.0)
|
| 193 |
+
# e = math.log(c2 / ch[1]) / math.log(2)
|
| 194 |
+
# c2 = int(ch[1] * ex ** e)
|
| 195 |
+
# if m != Focus:
|
| 196 |
+
|
| 197 |
+
c2 = make_divisible(c2 * gw, 8) if c2 != no else c2
|
| 198 |
+
|
| 199 |
+
# Experimental
|
| 200 |
+
# if i > 0 and args[0] != no: # channel expansion factor
|
| 201 |
+
# ex = 1 + gw # exponential (default 2.0)
|
| 202 |
+
# ch1 = 32 # ch[1]
|
| 203 |
+
# e = math.log(c2 / ch1) / math.log(2) # level 1-n
|
| 204 |
+
# c2 = int(ch1 * ex ** e)
|
| 205 |
+
# if m != Focus:
|
| 206 |
+
# c2 = make_divisible(c2, 8) if c2 != no else c2
|
| 207 |
+
|
| 208 |
+
args = [c1, c2, *args[1:]]
|
| 209 |
+
if m in [BottleneckCSP, C3]:
|
| 210 |
+
args.insert(2, n)
|
| 211 |
+
n = 1
|
| 212 |
+
elif m is nn.BatchNorm2d:
|
| 213 |
+
args = [ch[f]]
|
| 214 |
+
elif m is Concat:
|
| 215 |
+
c2 = sum([ch[-1 if x == -1 else x + 1] for x in f])
|
| 216 |
+
elif m is Detect:
|
| 217 |
+
args.append([ch[x + 1] for x in f])
|
| 218 |
+
if isinstance(args[1], int): # number of anchors
|
| 219 |
+
args[1] = [list(range(args[1] * 2))] * len(f)
|
| 220 |
+
else:
|
| 221 |
+
c2 = ch[f]
|
| 222 |
+
|
| 223 |
+
m_ = nn.Sequential(*[m(*args) for _ in range(n)]) if n > 1 else m(*args) # module
|
| 224 |
+
t = str(m)[8:-2].replace('__main__.', '') # module type
|
| 225 |
+
np = sum([x.numel() for x in m_.parameters()]) # number params
|
| 226 |
+
m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
|
| 227 |
+
print('%3s%18s%3s%10.0f %-40s%-30s' % (i, f, n, np, t, args)) # print
|
| 228 |
+
save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
|
| 229 |
+
layers.append(m_)
|
| 230 |
+
ch.append(c2)
|
| 231 |
+
return nn.Sequential(*layers), sorted(save)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
if __name__ == '__main__':
|
| 235 |
+
parser = argparse.ArgumentParser()
|
| 236 |
+
parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml')
|
| 237 |
+
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
|
| 238 |
+
opt = parser.parse_args()
|
| 239 |
+
opt.cfg = check_file(opt.cfg) # check file
|
| 240 |
+
device = select_device(opt.device)
|
| 241 |
+
|
| 242 |
+
# Create model
|
| 243 |
+
model = Model(opt.cfg).to(device)
|
| 244 |
+
model.train()
|
| 245 |
+
|
| 246 |
+
# Profile
|
| 247 |
+
# img = torch.rand(8 if torch.cuda.is_available() else 1, 3, 640, 640).to(device)
|
| 248 |
+
# y = model(img, profile=True)
|
| 249 |
+
|
| 250 |
+
# ONNX export
|
| 251 |
+
# model.model[-1].export = True
|
| 252 |
+
# torch.onnx.export(model, img, opt.cfg.replace('.yaml', '.onnx'), verbose=True, opset_version=11)
|
| 253 |
+
|
| 254 |
+
# Tensorboard
|
| 255 |
+
# from torch.utils.tensorboard import SummaryWriter
|
| 256 |
+
# tb_writer = SummaryWriter()
|
| 257 |
+
# print("Run 'tensorboard --logdir=models/runs' to view tensorboard at http://localhost:6006/")
|
| 258 |
+
# tb_writer.add_graph(model.model, img) # add model to tensorboard
|
| 259 |
+
# tb_writer.add_image('test', img[0], dataformats='CWH') # add model to tensorboard
|
yolov5_anime/models/yolov5l.yaml
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# parameters
|
| 2 |
+
nc: 80 # number of classes
|
| 3 |
+
depth_multiple: 1.0 # model depth multiple
|
| 4 |
+
width_multiple: 1.0 # layer channel multiple
|
| 5 |
+
|
| 6 |
+
# anchors
|
| 7 |
+
anchors:
|
| 8 |
+
- [10,13, 16,30, 33,23] # P3/8
|
| 9 |
+
- [30,61, 62,45, 59,119] # P4/16
|
| 10 |
+
- [116,90, 156,198, 373,326] # P5/32
|
| 11 |
+
|
| 12 |
+
# YOLOv5 backbone
|
| 13 |
+
backbone:
|
| 14 |
+
# [from, number, module, args]
|
| 15 |
+
[[-1, 1, Focus, [64, 3]], # 0-P1/2
|
| 16 |
+
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
| 17 |
+
[-1, 3, BottleneckCSP, [128]],
|
| 18 |
+
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
| 19 |
+
[-1, 9, BottleneckCSP, [256]],
|
| 20 |
+
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
| 21 |
+
[-1, 9, BottleneckCSP, [512]],
|
| 22 |
+
[-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
|
| 23 |
+
[-1, 1, SPP, [1024, [5, 9, 13]]],
|
| 24 |
+
[-1, 3, BottleneckCSP, [1024, False]], # 9
|
| 25 |
+
]
|
| 26 |
+
|
| 27 |
+
# YOLOv5 head
|
| 28 |
+
head:
|
| 29 |
+
[[-1, 1, Conv, [512, 1, 1]],
|
| 30 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
| 31 |
+
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
| 32 |
+
[-1, 3, BottleneckCSP, [512, False]], # 13
|
| 33 |
+
|
| 34 |
+
[-1, 1, Conv, [256, 1, 1]],
|
| 35 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
| 36 |
+
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
| 37 |
+
[-1, 3, BottleneckCSP, [256, False]], # 17 (P3/8-small)
|
| 38 |
+
|
| 39 |
+
[-1, 1, Conv, [256, 3, 2]],
|
| 40 |
+
[[-1, 14], 1, Concat, [1]], # cat head P4
|
| 41 |
+
[-1, 3, BottleneckCSP, [512, False]], # 20 (P4/16-medium)
|
| 42 |
+
|
| 43 |
+
[-1, 1, Conv, [512, 3, 2]],
|
| 44 |
+
[[-1, 10], 1, Concat, [1]], # cat head P5
|
| 45 |
+
[-1, 3, BottleneckCSP, [1024, False]], # 23 (P5/32-large)
|
| 46 |
+
|
| 47 |
+
[[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
|
| 48 |
+
]
|
yolov5_anime/models/yolov5m.yaml
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# parameters
|
| 2 |
+
nc: 80 # number of classes
|
| 3 |
+
depth_multiple: 0.67 # model depth multiple
|
| 4 |
+
width_multiple: 0.75 # layer channel multiple
|
| 5 |
+
|
| 6 |
+
# anchors
|
| 7 |
+
anchors:
|
| 8 |
+
- [10,13, 16,30, 33,23] # P3/8
|
| 9 |
+
- [30,61, 62,45, 59,119] # P4/16
|
| 10 |
+
- [116,90, 156,198, 373,326] # P5/32
|
| 11 |
+
|
| 12 |
+
# YOLOv5 backbone
|
| 13 |
+
backbone:
|
| 14 |
+
# [from, number, module, args]
|
| 15 |
+
[[-1, 1, Focus, [64, 3]], # 0-P1/2
|
| 16 |
+
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
| 17 |
+
[-1, 3, BottleneckCSP, [128]],
|
| 18 |
+
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
| 19 |
+
[-1, 9, BottleneckCSP, [256]],
|
| 20 |
+
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
| 21 |
+
[-1, 9, BottleneckCSP, [512]],
|
| 22 |
+
[-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
|
| 23 |
+
[-1, 1, SPP, [1024, [5, 9, 13]]],
|
| 24 |
+
[-1, 3, BottleneckCSP, [1024, False]], # 9
|
| 25 |
+
]
|
| 26 |
+
|
| 27 |
+
# YOLOv5 head
|
| 28 |
+
head:
|
| 29 |
+
[[-1, 1, Conv, [512, 1, 1]],
|
| 30 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
| 31 |
+
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
| 32 |
+
[-1, 3, BottleneckCSP, [512, False]], # 13
|
| 33 |
+
|
| 34 |
+
[-1, 1, Conv, [256, 1, 1]],
|
| 35 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
| 36 |
+
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
| 37 |
+
[-1, 3, BottleneckCSP, [256, False]], # 17 (P3/8-small)
|
| 38 |
+
|
| 39 |
+
[-1, 1, Conv, [256, 3, 2]],
|
| 40 |
+
[[-1, 14], 1, Concat, [1]], # cat head P4
|
| 41 |
+
[-1, 3, BottleneckCSP, [512, False]], # 20 (P4/16-medium)
|
| 42 |
+
|
| 43 |
+
[-1, 1, Conv, [512, 3, 2]],
|
| 44 |
+
[[-1, 10], 1, Concat, [1]], # cat head P5
|
| 45 |
+
[-1, 3, BottleneckCSP, [1024, False]], # 23 (P5/32-large)
|
| 46 |
+
|
| 47 |
+
[[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
|
| 48 |
+
]
|
yolov5_anime/models/yolov5s.yaml
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# parameters
|
| 2 |
+
nc: 80 # number of classes
|
| 3 |
+
depth_multiple: 0.33 # model depth multiple
|
| 4 |
+
width_multiple: 0.50 # layer channel multiple
|
| 5 |
+
|
| 6 |
+
# anchors
|
| 7 |
+
anchors:
|
| 8 |
+
- [10,13, 16,30, 33,23] # P3/8
|
| 9 |
+
- [30,61, 62,45, 59,119] # P4/16
|
| 10 |
+
- [116,90, 156,198, 373,326] # P5/32
|
| 11 |
+
|
| 12 |
+
# YOLOv5 backbone
|
| 13 |
+
backbone:
|
| 14 |
+
# [from, number, module, args]
|
| 15 |
+
[[-1, 1, Focus, [64, 3]], # 0-P1/2
|
| 16 |
+
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
| 17 |
+
[-1, 3, BottleneckCSP, [128]],
|
| 18 |
+
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
| 19 |
+
[-1, 9, BottleneckCSP, [256]],
|
| 20 |
+
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
| 21 |
+
[-1, 9, BottleneckCSP, [512]],
|
| 22 |
+
[-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
|
| 23 |
+
[-1, 1, SPP, [1024, [5, 9, 13]]],
|
| 24 |
+
[-1, 3, BottleneckCSP, [1024, False]], # 9
|
| 25 |
+
]
|
| 26 |
+
|
| 27 |
+
# YOLOv5 head
|
| 28 |
+
head:
|
| 29 |
+
[[-1, 1, Conv, [512, 1, 1]],
|
| 30 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
| 31 |
+
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
| 32 |
+
[-1, 3, BottleneckCSP, [512, False]], # 13
|
| 33 |
+
|
| 34 |
+
[-1, 1, Conv, [256, 1, 1]],
|
| 35 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
| 36 |
+
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
| 37 |
+
[-1, 3, BottleneckCSP, [256, False]], # 17 (P3/8-small)
|
| 38 |
+
|
| 39 |
+
[-1, 1, Conv, [256, 3, 2]],
|
| 40 |
+
[[-1, 14], 1, Concat, [1]], # cat head P4
|
| 41 |
+
[-1, 3, BottleneckCSP, [512, False]], # 20 (P4/16-medium)
|
| 42 |
+
|
| 43 |
+
[-1, 1, Conv, [512, 3, 2]],
|
| 44 |
+
[[-1, 10], 1, Concat, [1]], # cat head P5
|
| 45 |
+
[-1, 3, BottleneckCSP, [1024, False]], # 23 (P5/32-large)
|
| 46 |
+
|
| 47 |
+
[[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
|
| 48 |
+
]
|
yolov5_anime/models/yolov5x.yaml
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# parameters
|
| 2 |
+
nc: 1 # number of classes
|
| 3 |
+
depth_multiple: 1.33 # model depth multiple
|
| 4 |
+
width_multiple: 1.25 # layer channel multiple
|
| 5 |
+
|
| 6 |
+
# anchors
|
| 7 |
+
anchors:
|
| 8 |
+
- [10,13, 16,30, 33,23] # P3/8
|
| 9 |
+
- [30,61, 62,45, 59,119] # P4/16
|
| 10 |
+
- [116,90, 156,198, 373,326] # P5/32
|
| 11 |
+
|
| 12 |
+
# YOLOv5 backbone
|
| 13 |
+
backbone:
|
| 14 |
+
# [from, number, module, args]
|
| 15 |
+
[[-1, 1, Focus, [64, 3]], # 0-P1/2
|
| 16 |
+
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
| 17 |
+
[-1, 3, BottleneckCSP, [128]],
|
| 18 |
+
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
| 19 |
+
[-1, 9, BottleneckCSP, [256]],
|
| 20 |
+
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
| 21 |
+
[-1, 9, BottleneckCSP, [512]],
|
| 22 |
+
[-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
|
| 23 |
+
[-1, 1, SPP, [1024, [5, 9, 13]]],
|
| 24 |
+
[-1, 3, BottleneckCSP, [1024, False]], # 9
|
| 25 |
+
]
|
| 26 |
+
|
| 27 |
+
# YOLOv5 head
|
| 28 |
+
head:
|
| 29 |
+
[[-1, 1, Conv, [512, 1, 1]],
|
| 30 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
| 31 |
+
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
| 32 |
+
[-1, 3, BottleneckCSP, [512, False]], # 13
|
| 33 |
+
|
| 34 |
+
[-1, 1, Conv, [256, 1, 1]],
|
| 35 |
+
[-1, 1, nn.Upsample, [None, 2, 'nearest']],
|
| 36 |
+
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
| 37 |
+
[-1, 3, BottleneckCSP, [256, False]], # 17 (P3/8-small)
|
| 38 |
+
|
| 39 |
+
[-1, 1, Conv, [256, 3, 2]],
|
| 40 |
+
[[-1, 14], 1, Concat, [1]], # cat head P4
|
| 41 |
+
[-1, 3, BottleneckCSP, [512, False]], # 20 (P4/16-medium)
|
| 42 |
+
|
| 43 |
+
[-1, 1, Conv, [512, 3, 2]],
|
| 44 |
+
[[-1, 10], 1, Concat, [1]], # cat head P5
|
| 45 |
+
[-1, 3, BottleneckCSP, [1024, False]], # 23 (P5/32-large)
|
| 46 |
+
|
| 47 |
+
[[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
|
| 48 |
+
]
|
yolov5_anime/requirements.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# pip install -r requirements.txt
|
| 2 |
+
Cython
|
| 3 |
+
matplotlib>=3.2.2
|
| 4 |
+
numpy>=1.18.5
|
| 5 |
+
opencv-python>=4.1.2
|
| 6 |
+
pillow
|
| 7 |
+
# pycocotools>=2.0
|
| 8 |
+
PyYAML>=5.3
|
| 9 |
+
scipy>=1.4.1
|
| 10 |
+
tensorboard>=2.2
|
| 11 |
+
torch>=1.6.0
|
| 12 |
+
torchvision>=0.7.0
|
| 13 |
+
tqdm>=4.41.0
|
| 14 |
+
|
| 15 |
+
# Conda commands (in place of pip) ---------------------------------------------
|
| 16 |
+
# conda update -yn base -c defaults conda
|
| 17 |
+
# conda install -yc anaconda numpy opencv matplotlib tqdm pillow ipython
|
| 18 |
+
# conda install -yc conda-forge scikit-image pycocotools tensorboard
|
| 19 |
+
# conda install -yc spyder-ide spyder-line-profiler
|
| 20 |
+
# conda install -yc pytorch pytorch torchvision
|
| 21 |
+
# conda install -yc conda-forge protobuf numpy && pip install onnx==1.6.0 # https://github.com/onnx/on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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import glob
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import shutil
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import torch
|
| 10 |
+
import yaml
|
| 11 |
+
from tqdm import tqdm
|
| 12 |
+
|
| 13 |
+
from models.experimental import attempt_load
|
| 14 |
+
from utils.datasets import create_dataloader
|
| 15 |
+
from utils.general import (
|
| 16 |
+
coco80_to_coco91_class, check_dataset, check_file, check_img_size, compute_loss, non_max_suppression,
|
| 17 |
+
scale_coords, xyxy2xywh, clip_coords, plot_images, xywh2xyxy, box_iou, output_to_target, ap_per_class)
|
| 18 |
+
from utils.torch_utils import select_device, time_synchronized
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def test(data,
|
| 22 |
+
weights=None,
|
| 23 |
+
batch_size=16,
|
| 24 |
+
imgsz=640,
|
| 25 |
+
conf_thres=0.001,
|
| 26 |
+
iou_thres=0.6, # for NMS
|
| 27 |
+
save_json=False,
|
| 28 |
+
single_cls=False,
|
| 29 |
+
augment=False,
|
| 30 |
+
verbose=False,
|
| 31 |
+
model=None,
|
| 32 |
+
dataloader=None,
|
| 33 |
+
save_dir='',
|
| 34 |
+
merge=False,
|
| 35 |
+
save_txt=False):
|
| 36 |
+
# Initialize/load model and set device
|
| 37 |
+
training = model is not None
|
| 38 |
+
if training: # called by train.py
|
| 39 |
+
device = next(model.parameters()).device # get model device
|
| 40 |
+
|
| 41 |
+
else: # called directly
|
| 42 |
+
device = select_device(opt.device, batch_size=batch_size)
|
| 43 |
+
merge, save_txt = opt.merge, opt.save_txt # use Merge NMS, save *.txt labels
|
| 44 |
+
if save_txt:
|
| 45 |
+
out = Path('inference/output')
|
| 46 |
+
if os.path.exists(out):
|
| 47 |
+
shutil.rmtree(out) # delete output folder
|
| 48 |
+
os.makedirs(out) # make new output folder
|
| 49 |
+
|
| 50 |
+
# Remove previous
|
| 51 |
+
for f in glob.glob(str(Path(save_dir) / 'test_batch*.jpg')):
|
| 52 |
+
os.remove(f)
|
| 53 |
+
|
| 54 |
+
# Load model
|
| 55 |
+
model = attempt_load(weights, map_location=device) # load FP32 model
|
| 56 |
+
imgsz = check_img_size(imgsz, s=model.stride.max()) # check img_size
|
| 57 |
+
|
| 58 |
+
# Multi-GPU disabled, incompatible with .half() https://github.com/ultralytics/yolov5/issues/99
|
| 59 |
+
# if device.type != 'cpu' and torch.cuda.device_count() > 1:
|
| 60 |
+
# model = nn.DataParallel(model)
|
| 61 |
+
|
| 62 |
+
# Half
|
| 63 |
+
half = device.type != 'cpu' # half precision only supported on CUDA
|
| 64 |
+
if half:
|
| 65 |
+
model.half()
|
| 66 |
+
|
| 67 |
+
# Configure
|
| 68 |
+
model.eval()
|
| 69 |
+
with open(data) as f:
|
| 70 |
+
data = yaml.load(f, Loader=yaml.FullLoader) # model dict
|
| 71 |
+
check_dataset(data) # check
|
| 72 |
+
nc = 1 if single_cls else int(data['nc']) # number of classes
|
| 73 |
+
iouv = torch.linspace(0.5, 0.95, 10).to(device) # iou vector for [email protected]:0.95
|
| 74 |
+
niou = iouv.numel()
|
| 75 |
+
|
| 76 |
+
# Dataloader
|
| 77 |
+
if not training:
|
| 78 |
+
img = torch.zeros((1, 3, imgsz, imgsz), device=device) # init img
|
| 79 |
+
_ = model(img.half() if half else img) if device.type != 'cpu' else None # run once
|
| 80 |
+
path = data['test'] if opt.task == 'test' else data['val'] # path to val/test images
|
| 81 |
+
dataloader = create_dataloader(path, imgsz, batch_size, model.stride.max(), opt,
|
| 82 |
+
hyp=None, augment=False, cache=False, pad=0.5, rect=True)[0]
|
| 83 |
+
|
| 84 |
+
seen = 0
|
| 85 |
+
names = model.names if hasattr(model, 'names') else model.module.names
|
| 86 |
+
coco91class = coco80_to_coco91_class()
|
| 87 |
+
s = ('%20s' + '%12s' * 6) % ('Class', 'Images', 'Targets', 'P', 'R', '[email protected]', '[email protected]:.95')
|
| 88 |
+
p, r, f1, mp, mr, map50, map, t0, t1 = 0., 0., 0., 0., 0., 0., 0., 0., 0.
|
| 89 |
+
loss = torch.zeros(3, device=device)
|
| 90 |
+
jdict, stats, ap, ap_class = [], [], [], []
|
| 91 |
+
for batch_i, (img, targets, paths, shapes) in enumerate(tqdm(dataloader, desc=s)):
|
| 92 |
+
img = img.to(device, non_blocking=True)
|
| 93 |
+
img = img.half() if half else img.float() # uint8 to fp16/32
|
| 94 |
+
img /= 255.0 # 0 - 255 to 0.0 - 1.0
|
| 95 |
+
targets = targets.to(device)
|
| 96 |
+
nb, _, height, width = img.shape # batch size, channels, height, width
|
| 97 |
+
whwh = torch.Tensor([width, height, width, height]).to(device)
|
| 98 |
+
|
| 99 |
+
# Disable gradients
|
| 100 |
+
with torch.no_grad():
|
| 101 |
+
# Run model
|
| 102 |
+
t = time_synchronized()
|
| 103 |
+
inf_out, train_out = model(img, augment=augment) # inference and training outputs
|
| 104 |
+
t0 += time_synchronized() - t
|
| 105 |
+
|
| 106 |
+
# Compute loss
|
| 107 |
+
if training: # if model has loss hyperparameters
|
| 108 |
+
loss += compute_loss([x.float() for x in train_out], targets, model)[1][:3] # GIoU, obj, cls
|
| 109 |
+
|
| 110 |
+
# Run NMS
|
| 111 |
+
t = time_synchronized()
|
| 112 |
+
output = non_max_suppression(inf_out, conf_thres=conf_thres, iou_thres=iou_thres, merge=merge)
|
| 113 |
+
t1 += time_synchronized() - t
|
| 114 |
+
|
| 115 |
+
# Statistics per image
|
| 116 |
+
for si, pred in enumerate(output):
|
| 117 |
+
labels = targets[targets[:, 0] == si, 1:]
|
| 118 |
+
nl = len(labels)
|
| 119 |
+
tcls = labels[:, 0].tolist() if nl else [] # target class
|
| 120 |
+
seen += 1
|
| 121 |
+
|
| 122 |
+
if pred is None:
|
| 123 |
+
if nl:
|
| 124 |
+
stats.append((torch.zeros(0, niou, dtype=torch.bool), torch.Tensor(), torch.Tensor(), tcls))
|
| 125 |
+
continue
|
| 126 |
+
|
| 127 |
+
# Append to text file
|
| 128 |
+
if save_txt:
|
| 129 |
+
gn = torch.tensor(shapes[si][0])[[1, 0, 1, 0]] # normalization gain whwh
|
| 130 |
+
txt_path = str(out / Path(paths[si]).stem)
|
| 131 |
+
pred[:, :4] = scale_coords(img[si].shape[1:], pred[:, :4], shapes[si][0], shapes[si][1]) # to original
|
| 132 |
+
for *xyxy, conf, cls in pred:
|
| 133 |
+
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
|
| 134 |
+
with open(txt_path + '.txt', 'a') as f:
|
| 135 |
+
f.write(('%g ' * 5 + '\n') % (cls, *xywh)) # label format
|
| 136 |
+
|
| 137 |
+
# Clip boxes to image bounds
|
| 138 |
+
clip_coords(pred, (height, width))
|
| 139 |
+
|
| 140 |
+
# Append to pycocotools JSON dictionary
|
| 141 |
+
if save_json:
|
| 142 |
+
# [{"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236}, ...
|
| 143 |
+
image_id = Path(paths[si]).stem
|
| 144 |
+
box = pred[:, :4].clone() # xyxy
|
| 145 |
+
scale_coords(img[si].shape[1:], box, shapes[si][0], shapes[si][1]) # to original shape
|
| 146 |
+
box = xyxy2xywh(box) # xywh
|
| 147 |
+
box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner
|
| 148 |
+
for p, b in zip(pred.tolist(), box.tolist()):
|
| 149 |
+
jdict.append({'image_id': int(image_id) if image_id.isnumeric() else image_id,
|
| 150 |
+
'category_id': coco91class[int(p[5])],
|
| 151 |
+
'bbox': [round(x, 3) for x in b],
|
| 152 |
+
'score': round(p[4], 5)})
|
| 153 |
+
|
| 154 |
+
# Assign all predictions as incorrect
|
| 155 |
+
correct = torch.zeros(pred.shape[0], niou, dtype=torch.bool, device=device)
|
| 156 |
+
if nl:
|
| 157 |
+
detected = [] # target indices
|
| 158 |
+
tcls_tensor = labels[:, 0]
|
| 159 |
+
|
| 160 |
+
# target boxes
|
| 161 |
+
tbox = xywh2xyxy(labels[:, 1:5]) * whwh
|
| 162 |
+
|
| 163 |
+
# Per target class
|
| 164 |
+
for cls in torch.unique(tcls_tensor):
|
| 165 |
+
ti = (cls == tcls_tensor).nonzero(as_tuple=False).view(-1) # prediction indices
|
| 166 |
+
pi = (cls == pred[:, 5]).nonzero(as_tuple=False).view(-1) # target indices
|
| 167 |
+
|
| 168 |
+
# Search for detections
|
| 169 |
+
if pi.shape[0]:
|
| 170 |
+
# Prediction to target ious
|
| 171 |
+
ious, i = box_iou(pred[pi, :4], tbox[ti]).max(1) # best ious, indices
|
| 172 |
+
|
| 173 |
+
# Append detections
|
| 174 |
+
for j in (ious > iouv[0]).nonzero(as_tuple=False):
|
| 175 |
+
d = ti[i[j]] # detected target
|
| 176 |
+
if d not in detected:
|
| 177 |
+
detected.append(d)
|
| 178 |
+
correct[pi[j]] = ious[j] > iouv # iou_thres is 1xn
|
| 179 |
+
if len(detected) == nl: # all targets already located in image
|
| 180 |
+
break
|
| 181 |
+
|
| 182 |
+
# Append statistics (correct, conf, pcls, tcls)
|
| 183 |
+
stats.append((correct.cpu(), pred[:, 4].cpu(), pred[:, 5].cpu(), tcls))
|
| 184 |
+
|
| 185 |
+
# Plot images
|
| 186 |
+
if batch_i < 1:
|
| 187 |
+
f = Path(save_dir) / ('test_batch%g_gt.jpg' % batch_i) # filename
|
| 188 |
+
plot_images(img, targets, paths, str(f), names) # ground truth
|
| 189 |
+
f = Path(save_dir) / ('test_batch%g_pred.jpg' % batch_i)
|
| 190 |
+
plot_images(img, output_to_target(output, width, height), paths, str(f), names) # predictions
|
| 191 |
+
|
| 192 |
+
# Compute statistics
|
| 193 |
+
stats = [np.concatenate(x, 0) for x in zip(*stats)] # to numpy
|
| 194 |
+
if len(stats) and stats[0].any():
|
| 195 |
+
p, r, ap, f1, ap_class = ap_per_class(*stats)
|
| 196 |
+
p, r, ap50, ap = p[:, 0], r[:, 0], ap[:, 0], ap.mean(1) # [P, R, [email protected], [email protected]:0.95]
|
| 197 |
+
mp, mr, map50, map = p.mean(), r.mean(), ap50.mean(), ap.mean()
|
| 198 |
+
nt = np.bincount(stats[3].astype(np.int64), minlength=nc) # number of targets per class
|
| 199 |
+
else:
|
| 200 |
+
nt = torch.zeros(1)
|
| 201 |
+
|
| 202 |
+
# Print results
|
| 203 |
+
pf = '%20s' + '%12.3g' * 6 # print format
|
| 204 |
+
print(pf % ('all', seen, nt.sum(), mp, mr, map50, map))
|
| 205 |
+
|
| 206 |
+
# Print results per class
|
| 207 |
+
if verbose and nc > 1 and len(stats):
|
| 208 |
+
for i, c in enumerate(ap_class):
|
| 209 |
+
print(pf % (names[c], seen, nt[c], p[i], r[i], ap50[i], ap[i]))
|
| 210 |
+
|
| 211 |
+
# Print speeds
|
| 212 |
+
t = tuple(x / seen * 1E3 for x in (t0, t1, t0 + t1)) + (imgsz, imgsz, batch_size) # tuple
|
| 213 |
+
if not training:
|
| 214 |
+
print('Speed: %.1f/%.1f/%.1f ms inference/NMS/total per %gx%g image at batch-size %g' % t)
|
| 215 |
+
|
| 216 |
+
# Save JSON
|
| 217 |
+
if save_json and len(jdict):
|
| 218 |
+
f = 'detections_val2017_%s_results.json' % \
|
| 219 |
+
(weights.split(os.sep)[-1].replace('.pt', '') if isinstance(weights, str) else '') # filename
|
| 220 |
+
print('\nCOCO mAP with pycocotools... saving %s...' % f)
|
| 221 |
+
with open(f, 'w') as file:
|
| 222 |
+
json.dump(jdict, file)
|
| 223 |
+
|
| 224 |
+
try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb
|
| 225 |
+
from pycocotools.coco import COCO
|
| 226 |
+
from pycocotools.cocoeval import COCOeval
|
| 227 |
+
|
| 228 |
+
imgIds = [int(Path(x).stem) for x in dataloader.dataset.img_files]
|
| 229 |
+
cocoGt = COCO(glob.glob('../coco/annotations/instances_val*.json')[0]) # initialize COCO ground truth api
|
| 230 |
+
cocoDt = cocoGt.loadRes(f) # initialize COCO pred api
|
| 231 |
+
cocoEval = COCOeval(cocoGt, cocoDt, 'bbox')
|
| 232 |
+
cocoEval.params.imgIds = imgIds # image IDs to evaluate
|
| 233 |
+
cocoEval.evaluate()
|
| 234 |
+
cocoEval.accumulate()
|
| 235 |
+
cocoEval.summarize()
|
| 236 |
+
map, map50 = cocoEval.stats[:2] # update results ([email protected]:0.95, [email protected])
|
| 237 |
+
except Exception as e:
|
| 238 |
+
print('ERROR: pycocotools unable to run: %s' % e)
|
| 239 |
+
|
| 240 |
+
# Return results
|
| 241 |
+
model.float() # for training
|
| 242 |
+
maps = np.zeros(nc) + map
|
| 243 |
+
for i, c in enumerate(ap_class):
|
| 244 |
+
maps[c] = ap[i]
|
| 245 |
+
return (mp, mr, map50, map, *(loss.cpu() / len(dataloader)).tolist()), maps, t
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
if __name__ == '__main__':
|
| 249 |
+
parser = argparse.ArgumentParser(prog='test.py')
|
| 250 |
+
parser.add_argument('--weights', nargs='+', type=str, default='yolov5s.pt', help='model.pt path(s)')
|
| 251 |
+
parser.add_argument('--data', type=str, default='data/coco128.yaml', help='*.data path')
|
| 252 |
+
parser.add_argument('--batch-size', type=int, default=32, help='size of each image batch')
|
| 253 |
+
parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
|
| 254 |
+
parser.add_argument('--conf-thres', type=float, default=0.001, help='object confidence threshold')
|
| 255 |
+
parser.add_argument('--iou-thres', type=float, default=0.65, help='IOU threshold for NMS')
|
| 256 |
+
parser.add_argument('--save-json', action='store_true', help='save a cocoapi-compatible JSON results file')
|
| 257 |
+
parser.add_argument('--task', default='val', help="'val', 'test', 'study'")
|
| 258 |
+
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
|
| 259 |
+
parser.add_argument('--single-cls', action='store_true', help='treat as single-class dataset')
|
| 260 |
+
parser.add_argument('--augment', action='store_true', help='augmented inference')
|
| 261 |
+
parser.add_argument('--merge', action='store_true', help='use Merge NMS')
|
| 262 |
+
parser.add_argument('--verbose', action='store_true', help='report mAP by class')
|
| 263 |
+
parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
|
| 264 |
+
opt = parser.parse_args()
|
| 265 |
+
opt.save_json |= opt.data.endswith('coco.yaml')
|
| 266 |
+
opt.data = check_file(opt.data) # check file
|
| 267 |
+
print(opt)
|
| 268 |
+
|
| 269 |
+
if opt.task in ['val', 'test']: # run normally
|
| 270 |
+
test(opt.data,
|
| 271 |
+
opt.weights,
|
| 272 |
+
opt.batch_size,
|
| 273 |
+
opt.img_size,
|
| 274 |
+
opt.conf_thres,
|
| 275 |
+
opt.iou_thres,
|
| 276 |
+
opt.save_json,
|
| 277 |
+
opt.single_cls,
|
| 278 |
+
opt.augment,
|
| 279 |
+
opt.verbose)
|
| 280 |
+
|
| 281 |
+
elif opt.task == 'study': # run over a range of settings and save/plot
|
| 282 |
+
for weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt', 'yolov3-spp.pt']:
|
| 283 |
+
f = 'study_%s_%s.txt' % (Path(opt.data).stem, Path(weights).stem) # filename to save to
|
| 284 |
+
x = list(range(352, 832, 64)) # x axis
|
| 285 |
+
y = [] # y axis
|
| 286 |
+
for i in x: # img-size
|
| 287 |
+
print('\nRunning %s point %s...' % (f, i))
|
| 288 |
+
r, _, t = test(opt.data, weights, opt.batch_size, i, opt.conf_thres, opt.iou_thres, opt.save_json)
|
| 289 |
+
y.append(r + t) # results and times
|
| 290 |
+
np.savetxt(f, y, fmt='%10.4g') # save
|
| 291 |
+
os.system('zip -r study.zip study_*.txt')
|
| 292 |
+
# plot_study_txt(f, x) # plot
|
yolov5_anime/train.py
ADDED
|
@@ -0,0 +1,516 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import math
|
| 3 |
+
import os
|
| 4 |
+
import random
|
| 5 |
+
import time
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import torch.distributed as dist
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
import torch.optim as optim
|
| 12 |
+
import torch.optim.lr_scheduler as lr_scheduler
|
| 13 |
+
import torch.utils.data
|
| 14 |
+
import yaml
|
| 15 |
+
from torch.cuda import amp
|
| 16 |
+
from torch.nn.parallel import DistributedDataParallel as DDP
|
| 17 |
+
from torch.utils.tensorboard import SummaryWriter
|
| 18 |
+
from tqdm import tqdm
|
| 19 |
+
|
| 20 |
+
import test # import test.py to get mAP after each epoch
|
| 21 |
+
from models.yolo import Model
|
| 22 |
+
from utils.datasets import create_dataloader
|
| 23 |
+
from utils.general import (
|
| 24 |
+
torch_distributed_zero_first, labels_to_class_weights, plot_labels, check_anchors, labels_to_image_weights,
|
| 25 |
+
compute_loss, plot_images, fitness, strip_optimizer, plot_results, get_latest_run, check_dataset, check_file,
|
| 26 |
+
check_git_status, check_img_size, increment_dir, print_mutation, plot_evolution)
|
| 27 |
+
from utils.google_utils import attempt_download
|
| 28 |
+
from utils.torch_utils import init_seeds, ModelEMA, select_device, intersect_dicts
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def train(hyp, opt, device, tb_writer=None):
|
| 32 |
+
print(f'Hyperparameters {hyp}')
|
| 33 |
+
log_dir = Path(tb_writer.log_dir) if tb_writer else Path(opt.logdir) / 'evolve' # logging directory
|
| 34 |
+
wdir = str(log_dir / 'weights') + os.sep # weights directory
|
| 35 |
+
os.makedirs(wdir, exist_ok=True)
|
| 36 |
+
last = wdir + 'last.pt'
|
| 37 |
+
best = wdir + 'best.pt'
|
| 38 |
+
results_file = str(log_dir / 'results.txt')
|
| 39 |
+
epochs, batch_size, total_batch_size, weights, rank = \
|
| 40 |
+
opt.epochs, opt.batch_size, opt.total_batch_size, opt.weights, opt.global_rank
|
| 41 |
+
|
| 42 |
+
# TODO: Use DDP logging. Only the first process is allowed to log.
|
| 43 |
+
# Save run settings
|
| 44 |
+
with open(log_dir / 'hyp.yaml', 'w') as f:
|
| 45 |
+
yaml.dump(hyp, f, sort_keys=False)
|
| 46 |
+
with open(log_dir / 'opt.yaml', 'w') as f:
|
| 47 |
+
yaml.dump(vars(opt), f, sort_keys=False)
|
| 48 |
+
|
| 49 |
+
# Configure
|
| 50 |
+
cuda = device.type != 'cpu'
|
| 51 |
+
init_seeds(2 + rank)
|
| 52 |
+
with open(opt.data) as f:
|
| 53 |
+
data_dict = yaml.load(f, Loader=yaml.FullLoader) # model dict
|
| 54 |
+
with torch_distributed_zero_first(rank):
|
| 55 |
+
check_dataset(data_dict) # check
|
| 56 |
+
train_path = data_dict['train']
|
| 57 |
+
test_path = data_dict['val']
|
| 58 |
+
nc, names = (1, ['item']) if opt.single_cls else (int(data_dict['nc']), data_dict['names']) # number classes, names
|
| 59 |
+
assert len(names) == nc, '%g names found for nc=%g dataset in %s' % (len(names), nc, opt.data) # check
|
| 60 |
+
|
| 61 |
+
# Model
|
| 62 |
+
pretrained = weights.endswith('.pt')
|
| 63 |
+
if pretrained:
|
| 64 |
+
with torch_distributed_zero_first(rank):
|
| 65 |
+
attempt_download(weights) # download if not found locally
|
| 66 |
+
ckpt = torch.load(weights, map_location=device) # load checkpoint
|
| 67 |
+
model = Model(opt.cfg or ckpt['model'].yaml, ch=3, nc=nc).to(device) # create
|
| 68 |
+
exclude = ['anchor'] if opt.cfg else [] # exclude keys
|
| 69 |
+
state_dict = ckpt['model'].float().state_dict() # to FP32
|
| 70 |
+
state_dict = intersect_dicts(state_dict, model.state_dict(), exclude=exclude) # intersect
|
| 71 |
+
model.load_state_dict(state_dict, strict=False) # load
|
| 72 |
+
print('Transferred %g/%g items from %s' % (len(state_dict), len(model.state_dict()), weights)) # report
|
| 73 |
+
else:
|
| 74 |
+
model = Model(opt.cfg, ch=3, nc=nc).to(device) # create
|
| 75 |
+
|
| 76 |
+
# Optimizer
|
| 77 |
+
nbs = 64 # nominal batch size
|
| 78 |
+
accumulate = max(round(nbs / total_batch_size), 1) # accumulate loss before optimizing
|
| 79 |
+
hyp['weight_decay'] *= total_batch_size * accumulate / nbs # scale weight_decay
|
| 80 |
+
|
| 81 |
+
pg0, pg1, pg2 = [], [], [] # optimizer parameter groups
|
| 82 |
+
for k, v in model.named_parameters():
|
| 83 |
+
v.requires_grad = True
|
| 84 |
+
if '.bias' in k:
|
| 85 |
+
pg2.append(v) # biases
|
| 86 |
+
elif '.weight' in k and '.bn' not in k:
|
| 87 |
+
pg1.append(v) # apply weight decay
|
| 88 |
+
else:
|
| 89 |
+
pg0.append(v) # all else
|
| 90 |
+
|
| 91 |
+
if opt.adam:
|
| 92 |
+
optimizer = optim.Adam(pg0, lr=hyp['lr0'], betas=(hyp['momentum'], 0.999)) # adjust beta1 to momentum
|
| 93 |
+
else:
|
| 94 |
+
optimizer = optim.SGD(pg0, lr=hyp['lr0'], momentum=hyp['momentum'], nesterov=True)
|
| 95 |
+
|
| 96 |
+
optimizer.add_param_group({'params': pg1, 'weight_decay': hyp['weight_decay']}) # add pg1 with weight_decay
|
| 97 |
+
optimizer.add_param_group({'params': pg2}) # add pg2 (biases)
|
| 98 |
+
print('Optimizer groups: %g .bias, %g conv.weight, %g other' % (len(pg2), len(pg1), len(pg0)))
|
| 99 |
+
del pg0, pg1, pg2
|
| 100 |
+
|
| 101 |
+
# Scheduler https://arxiv.org/pdf/1812.01187.pdf
|
| 102 |
+
# https://pytorch.org/docs/stable/_modules/torch/optim/lr_scheduler.html#OneCycleLR
|
| 103 |
+
lf = lambda x: (((1 + math.cos(x * math.pi / epochs)) / 2) ** 1.0) * 0.8 + 0.2 # cosine
|
| 104 |
+
scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf)
|
| 105 |
+
# plot_lr_scheduler(optimizer, scheduler, epochs)
|
| 106 |
+
|
| 107 |
+
# Resume
|
| 108 |
+
start_epoch, best_fitness = 0, 0.0
|
| 109 |
+
if pretrained:
|
| 110 |
+
# Optimizer
|
| 111 |
+
if ckpt['optimizer'] is not None:
|
| 112 |
+
optimizer.load_state_dict(ckpt['optimizer'])
|
| 113 |
+
best_fitness = ckpt['best_fitness']
|
| 114 |
+
|
| 115 |
+
# Results
|
| 116 |
+
if ckpt.get('training_results') is not None:
|
| 117 |
+
with open(results_file, 'w') as file:
|
| 118 |
+
file.write(ckpt['training_results']) # write results.txt
|
| 119 |
+
|
| 120 |
+
# Epochs
|
| 121 |
+
start_epoch = ckpt['epoch'] + 1
|
| 122 |
+
if epochs < start_epoch:
|
| 123 |
+
print('%s has been trained for %g epochs. Fine-tuning for %g additional epochs.' %
|
| 124 |
+
(weights, ckpt['epoch'], epochs))
|
| 125 |
+
epochs += ckpt['epoch'] # finetune additional epochs
|
| 126 |
+
|
| 127 |
+
del ckpt, state_dict
|
| 128 |
+
|
| 129 |
+
# Image sizes
|
| 130 |
+
gs = int(max(model.stride)) # grid size (max stride)
|
| 131 |
+
imgsz, imgsz_test = [check_img_size(x, gs) for x in opt.img_size] # verify imgsz are gs-multiples
|
| 132 |
+
|
| 133 |
+
# DP mode
|
| 134 |
+
if cuda and rank == -1 and torch.cuda.device_count() > 1:
|
| 135 |
+
model = torch.nn.DataParallel(model)
|
| 136 |
+
|
| 137 |
+
# SyncBatchNorm
|
| 138 |
+
if opt.sync_bn and cuda and rank != -1:
|
| 139 |
+
model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model).to(device)
|
| 140 |
+
print('Using SyncBatchNorm()')
|
| 141 |
+
|
| 142 |
+
# Exponential moving average
|
| 143 |
+
ema = ModelEMA(model) if rank in [-1, 0] else None
|
| 144 |
+
|
| 145 |
+
# DDP mode
|
| 146 |
+
if cuda and rank != -1:
|
| 147 |
+
model = DDP(model, device_ids=[opt.local_rank], output_device=(opt.local_rank))
|
| 148 |
+
|
| 149 |
+
# Trainloader
|
| 150 |
+
dataloader, dataset = create_dataloader(train_path, imgsz, batch_size, gs, opt, hyp=hyp, augment=True,
|
| 151 |
+
cache=opt.cache_images, rect=opt.rect, local_rank=rank,
|
| 152 |
+
world_size=opt.world_size)
|
| 153 |
+
mlc = np.concatenate(dataset.labels, 0)[:, 0].max() # max label class
|
| 154 |
+
nb = len(dataloader) # number of batches
|
| 155 |
+
assert mlc < nc, 'Label class %g exceeds nc=%g in %s. Possible class labels are 0-%g' % (mlc, nc, opt.data, nc - 1)
|
| 156 |
+
|
| 157 |
+
# Testloader
|
| 158 |
+
if rank in [-1, 0]:
|
| 159 |
+
# local_rank is set to -1. Because only the first process is expected to do evaluation.
|
| 160 |
+
testloader = create_dataloader(test_path, imgsz_test, total_batch_size, gs, opt, hyp=hyp, augment=False,
|
| 161 |
+
cache=opt.cache_images, rect=True, local_rank=-1, world_size=opt.world_size)[0]
|
| 162 |
+
|
| 163 |
+
# Model parameters
|
| 164 |
+
hyp['cls'] *= nc / 80. # scale coco-tuned hyp['cls'] to current dataset
|
| 165 |
+
model.nc = nc # attach number of classes to model
|
| 166 |
+
model.hyp = hyp # attach hyperparameters to model
|
| 167 |
+
model.gr = 1.0 # giou loss ratio (obj_loss = 1.0 or giou)
|
| 168 |
+
model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) # attach class weights
|
| 169 |
+
model.names = names
|
| 170 |
+
|
| 171 |
+
# Class frequency
|
| 172 |
+
if rank in [-1, 0]:
|
| 173 |
+
labels = np.concatenate(dataset.labels, 0)
|
| 174 |
+
c = torch.tensor(labels[:, 0]) # classes
|
| 175 |
+
# cf = torch.bincount(c.long(), minlength=nc) + 1.
|
| 176 |
+
# model._initialize_biases(cf.to(device))
|
| 177 |
+
plot_labels(labels, save_dir=log_dir)
|
| 178 |
+
if tb_writer:
|
| 179 |
+
# tb_writer.add_hparams(hyp, {}) # causes duplicate https://github.com/ultralytics/yolov5/pull/384
|
| 180 |
+
tb_writer.add_histogram('classes', c, 0)
|
| 181 |
+
|
| 182 |
+
# Check anchors
|
| 183 |
+
if not opt.noautoanchor:
|
| 184 |
+
check_anchors(dataset, model=model, thr=hyp['anchor_t'], imgsz=imgsz)
|
| 185 |
+
|
| 186 |
+
# Start training
|
| 187 |
+
t0 = time.time()
|
| 188 |
+
nw = max(3 * nb, 1e3) # number of warmup iterations, max(3 epochs, 1k iterations)
|
| 189 |
+
# nw = min(nw, (epochs - start_epoch) / 2 * nb) # limit warmup to < 1/2 of training
|
| 190 |
+
maps = np.zeros(nc) # mAP per class
|
| 191 |
+
results = (0, 0, 0, 0, 0, 0, 0) # 'P', 'R', 'mAP', 'F1', 'val GIoU', 'val Objectness', 'val Classification'
|
| 192 |
+
scheduler.last_epoch = start_epoch - 1 # do not move
|
| 193 |
+
scaler = amp.GradScaler(enabled=cuda)
|
| 194 |
+
if rank in [0, -1]:
|
| 195 |
+
print('Image sizes %g train, %g test' % (imgsz, imgsz_test))
|
| 196 |
+
print('Using %g dataloader workers' % dataloader.num_workers)
|
| 197 |
+
print('Starting training for %g epochs...' % epochs)
|
| 198 |
+
# torch.autograd.set_detect_anomaly(True)
|
| 199 |
+
for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------
|
| 200 |
+
model.train()
|
| 201 |
+
|
| 202 |
+
# Update image weights (optional)
|
| 203 |
+
if dataset.image_weights:
|
| 204 |
+
# Generate indices
|
| 205 |
+
if rank in [-1, 0]:
|
| 206 |
+
w = model.class_weights.cpu().numpy() * (1 - maps) ** 2 # class weights
|
| 207 |
+
image_weights = labels_to_image_weights(dataset.labels, nc=nc, class_weights=w)
|
| 208 |
+
dataset.indices = random.choices(range(dataset.n), weights=image_weights,
|
| 209 |
+
k=dataset.n) # rand weighted idx
|
| 210 |
+
# Broadcast if DDP
|
| 211 |
+
if rank != -1:
|
| 212 |
+
indices = torch.zeros([dataset.n], dtype=torch.int)
|
| 213 |
+
if rank == 0:
|
| 214 |
+
indices[:] = torch.from_tensor(dataset.indices, dtype=torch.int)
|
| 215 |
+
dist.broadcast(indices, 0)
|
| 216 |
+
if rank != 0:
|
| 217 |
+
dataset.indices = indices.cpu().numpy()
|
| 218 |
+
|
| 219 |
+
# Update mosaic border
|
| 220 |
+
# b = int(random.uniform(0.25 * imgsz, 0.75 * imgsz + gs) // gs * gs)
|
| 221 |
+
# dataset.mosaic_border = [b - imgsz, -b] # height, width borders
|
| 222 |
+
|
| 223 |
+
mloss = torch.zeros(4, device=device) # mean losses
|
| 224 |
+
if rank != -1:
|
| 225 |
+
dataloader.sampler.set_epoch(epoch)
|
| 226 |
+
pbar = enumerate(dataloader)
|
| 227 |
+
if rank in [-1, 0]:
|
| 228 |
+
print(('\n' + '%10s' * 8) % ('Epoch', 'gpu_mem', 'GIoU', 'obj', 'cls', 'total', 'targets', 'img_size'))
|
| 229 |
+
pbar = tqdm(pbar, total=nb) # progress bar
|
| 230 |
+
optimizer.zero_grad()
|
| 231 |
+
for i, (imgs, targets, paths, _) in pbar: # batch -------------------------------------------------------------
|
| 232 |
+
ni = i + nb * epoch # number integrated batches (since train start)
|
| 233 |
+
imgs = imgs.to(device, non_blocking=True).float() / 255.0 # uint8 to float32, 0-255 to 0.0-1.0
|
| 234 |
+
|
| 235 |
+
# Warmup
|
| 236 |
+
if ni <= nw:
|
| 237 |
+
xi = [0, nw] # x interp
|
| 238 |
+
# model.gr = np.interp(ni, xi, [0.0, 1.0]) # giou loss ratio (obj_loss = 1.0 or giou)
|
| 239 |
+
accumulate = max(1, np.interp(ni, xi, [1, nbs / total_batch_size]).round())
|
| 240 |
+
for j, x in enumerate(optimizer.param_groups):
|
| 241 |
+
# bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0
|
| 242 |
+
x['lr'] = np.interp(ni, xi, [0.1 if j == 2 else 0.0, x['initial_lr'] * lf(epoch)])
|
| 243 |
+
if 'momentum' in x:
|
| 244 |
+
x['momentum'] = np.interp(ni, xi, [0.9, hyp['momentum']])
|
| 245 |
+
|
| 246 |
+
# Multi-scale
|
| 247 |
+
if opt.multi_scale:
|
| 248 |
+
sz = random.randrange(imgsz * 0.5, imgsz * 1.5 + gs) // gs * gs # size
|
| 249 |
+
sf = sz / max(imgs.shape[2:]) # scale factor
|
| 250 |
+
if sf != 1:
|
| 251 |
+
ns = [math.ceil(x * sf / gs) * gs for x in imgs.shape[2:]] # new shape (stretched to gs-multiple)
|
| 252 |
+
imgs = F.interpolate(imgs, size=ns, mode='bilinear', align_corners=False)
|
| 253 |
+
|
| 254 |
+
# Autocast
|
| 255 |
+
with amp.autocast(enabled=cuda):
|
| 256 |
+
# Forward
|
| 257 |
+
pred = model(imgs)
|
| 258 |
+
|
| 259 |
+
# Loss
|
| 260 |
+
loss, loss_items = compute_loss(pred, targets.to(device), model) # scaled by batch_size
|
| 261 |
+
if rank != -1:
|
| 262 |
+
loss *= opt.world_size # gradient averaged between devices in DDP mode
|
| 263 |
+
# if not torch.isfinite(loss):
|
| 264 |
+
# print('WARNING: non-finite loss, ending training ', loss_items)
|
| 265 |
+
# return results
|
| 266 |
+
|
| 267 |
+
# Backward
|
| 268 |
+
scaler.scale(loss).backward()
|
| 269 |
+
|
| 270 |
+
# Optimize
|
| 271 |
+
if ni % accumulate == 0:
|
| 272 |
+
scaler.step(optimizer) # optimizer.step
|
| 273 |
+
scaler.update()
|
| 274 |
+
optimizer.zero_grad()
|
| 275 |
+
if ema is not None:
|
| 276 |
+
ema.update(model)
|
| 277 |
+
|
| 278 |
+
# Print
|
| 279 |
+
if rank in [-1, 0]:
|
| 280 |
+
mloss = (mloss * i + loss_items) / (i + 1) # update mean losses
|
| 281 |
+
mem = '%.3gG' % (torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0) # (GB)
|
| 282 |
+
s = ('%10s' * 2 + '%10.4g' * 6) % (
|
| 283 |
+
'%g/%g' % (epoch, epochs - 1), mem, *mloss, targets.shape[0], imgs.shape[-1])
|
| 284 |
+
pbar.set_description(s)
|
| 285 |
+
|
| 286 |
+
# Plot
|
| 287 |
+
if ni < 3:
|
| 288 |
+
f = str(log_dir / ('train_batch%g.jpg' % ni)) # filename
|
| 289 |
+
result = plot_images(images=imgs, targets=targets, paths=paths, fname=f)
|
| 290 |
+
if tb_writer and result is not None:
|
| 291 |
+
tb_writer.add_image(f, result, dataformats='HWC', global_step=epoch)
|
| 292 |
+
# tb_writer.add_graph(model, imgs) # add model to tensorboard
|
| 293 |
+
|
| 294 |
+
# end batch ------------------------------------------------------------------------------------------------
|
| 295 |
+
|
| 296 |
+
# Scheduler
|
| 297 |
+
scheduler.step()
|
| 298 |
+
|
| 299 |
+
# DDP process 0 or single-GPU
|
| 300 |
+
if rank in [-1, 0]:
|
| 301 |
+
# mAP
|
| 302 |
+
if ema is not None:
|
| 303 |
+
ema.update_attr(model, include=['yaml', 'nc', 'hyp', 'gr', 'names', 'stride'])
|
| 304 |
+
final_epoch = epoch + 1 == epochs
|
| 305 |
+
if not opt.notest or final_epoch: # Calculate mAP
|
| 306 |
+
results, maps, times = test.test(opt.data,
|
| 307 |
+
batch_size=total_batch_size,
|
| 308 |
+
imgsz=imgsz_test,
|
| 309 |
+
model=ema.ema.module if hasattr(ema.ema, 'module') else ema.ema,
|
| 310 |
+
single_cls=opt.single_cls,
|
| 311 |
+
dataloader=testloader,
|
| 312 |
+
save_dir=log_dir)
|
| 313 |
+
|
| 314 |
+
# Write
|
| 315 |
+
with open(results_file, 'a') as f:
|
| 316 |
+
f.write(s + '%10.4g' * 7 % results + '\n') # P, R, mAP, F1, test_losses=(GIoU, obj, cls)
|
| 317 |
+
if len(opt.name) and opt.bucket:
|
| 318 |
+
os.system('gsutil cp %s gs://%s/results/results%s.txt' % (results_file, opt.bucket, opt.name))
|
| 319 |
+
|
| 320 |
+
# Tensorboard
|
| 321 |
+
if tb_writer:
|
| 322 |
+
tags = ['train/giou_loss', 'train/obj_loss', 'train/cls_loss',
|
| 323 |
+
'metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/mAP_0.5:0.95',
|
| 324 |
+
'val/giou_loss', 'val/obj_loss', 'val/cls_loss']
|
| 325 |
+
for x, tag in zip(list(mloss[:-1]) + list(results), tags):
|
| 326 |
+
tb_writer.add_scalar(tag, x, epoch)
|
| 327 |
+
|
| 328 |
+
# Update best mAP
|
| 329 |
+
fi = fitness(np.array(results).reshape(1, -1)) # fitness_i = weighted combination of [P, R, mAP, F1]
|
| 330 |
+
if fi > best_fitness:
|
| 331 |
+
best_fitness = fi
|
| 332 |
+
|
| 333 |
+
# Save model
|
| 334 |
+
save = (not opt.nosave) or (final_epoch and not opt.evolve)
|
| 335 |
+
if save:
|
| 336 |
+
with open(results_file, 'r') as f: # create checkpoint
|
| 337 |
+
ckpt = {'epoch': epoch,
|
| 338 |
+
'best_fitness': best_fitness,
|
| 339 |
+
'training_results': f.read(),
|
| 340 |
+
'model': ema.ema.module if hasattr(ema, 'module') else ema.ema,
|
| 341 |
+
'optimizer': None if final_epoch else optimizer.state_dict()}
|
| 342 |
+
|
| 343 |
+
# Save last, best and delete
|
| 344 |
+
torch.save(ckpt, last)
|
| 345 |
+
if best_fitness == fi:
|
| 346 |
+
torch.save(ckpt, best)
|
| 347 |
+
del ckpt
|
| 348 |
+
# end epoch ----------------------------------------------------------------------------------------------------
|
| 349 |
+
# end training
|
| 350 |
+
|
| 351 |
+
if rank in [-1, 0]:
|
| 352 |
+
# Strip optimizers
|
| 353 |
+
n = ('_' if len(opt.name) and not opt.name.isnumeric() else '') + opt.name
|
| 354 |
+
fresults, flast, fbest = 'results%s.txt' % n, wdir + 'last%s.pt' % n, wdir + 'best%s.pt' % n
|
| 355 |
+
for f1, f2 in zip([wdir + 'last.pt', wdir + 'best.pt', 'results.txt'], [flast, fbest, fresults]):
|
| 356 |
+
if os.path.exists(f1):
|
| 357 |
+
os.rename(f1, f2) # rename
|
| 358 |
+
ispt = f2.endswith('.pt') # is *.pt
|
| 359 |
+
strip_optimizer(f2) if ispt else None # strip optimizer
|
| 360 |
+
os.system('gsutil cp %s gs://%s/weights' % (f2, opt.bucket)) if opt.bucket and ispt else None # upload
|
| 361 |
+
# Finish
|
| 362 |
+
if not opt.evolve:
|
| 363 |
+
plot_results(save_dir=log_dir) # save as results.png
|
| 364 |
+
print('%g epochs completed in %.3f hours.\n' % (epoch - start_epoch + 1, (time.time() - t0) / 3600))
|
| 365 |
+
|
| 366 |
+
dist.destroy_process_group() if rank not in [-1, 0] else None
|
| 367 |
+
torch.cuda.empty_cache()
|
| 368 |
+
return results
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
if __name__ == '__main__':
|
| 372 |
+
parser = argparse.ArgumentParser()
|
| 373 |
+
parser.add_argument('--weights', type=str, default='yolov5s.pt', help='initial weights path')
|
| 374 |
+
parser.add_argument('--cfg', type=str, default='', help='model.yaml path')
|
| 375 |
+
parser.add_argument('--data', type=str, default='data/coco128.yaml', help='data.yaml path')
|
| 376 |
+
parser.add_argument('--hyp', type=str, default='', help='hyperparameters path, i.e. data/hyp.scratch.yaml')
|
| 377 |
+
parser.add_argument('--epochs', type=int, default=300)
|
| 378 |
+
parser.add_argument('--batch-size', type=int, default=16, help='total batch size for all GPUs')
|
| 379 |
+
parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='train,test sizes')
|
| 380 |
+
parser.add_argument('--rect', action='store_true', help='rectangular training')
|
| 381 |
+
parser.add_argument('--resume', nargs='?', const='get_last', default=False,
|
| 382 |
+
help='resume from given path/last.pt, or most recent run if blank')
|
| 383 |
+
parser.add_argument('--nosave', action='store_true', help='only save final checkpoint')
|
| 384 |
+
parser.add_argument('--notest', action='store_true', help='only test final epoch')
|
| 385 |
+
parser.add_argument('--noautoanchor', action='store_true', help='disable autoanchor check')
|
| 386 |
+
parser.add_argument('--evolve', action='store_true', help='evolve hyperparameters')
|
| 387 |
+
parser.add_argument('--bucket', type=str, default='', help='gsutil bucket')
|
| 388 |
+
parser.add_argument('--cache-images', action='store_true', help='cache images for faster training')
|
| 389 |
+
parser.add_argument('--name', default='', help='renames results.txt to results_name.txt if supplied')
|
| 390 |
+
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
|
| 391 |
+
parser.add_argument('--multi-scale', action='store_true', help='vary img-size +/- 50%%')
|
| 392 |
+
parser.add_argument('--single-cls', action='store_true', help='train as single-class dataset')
|
| 393 |
+
parser.add_argument('--adam', action='store_true', help='use torch.optim.Adam() optimizer')
|
| 394 |
+
parser.add_argument('--sync-bn', action='store_true', help='use SyncBatchNorm, only available in DDP mode')
|
| 395 |
+
parser.add_argument('--local_rank', type=int, default=-1, help='DDP parameter, do not modify')
|
| 396 |
+
parser.add_argument('--logdir', type=str, default='runs/', help='logging directory')
|
| 397 |
+
opt = parser.parse_args()
|
| 398 |
+
|
| 399 |
+
# Resume
|
| 400 |
+
if opt.resume:
|
| 401 |
+
last = get_latest_run() if opt.resume == 'get_last' else opt.resume # resume from most recent run
|
| 402 |
+
if last and not opt.weights:
|
| 403 |
+
print(f'Resuming training from {last}')
|
| 404 |
+
opt.weights = last if opt.resume and not opt.weights else opt.weights
|
| 405 |
+
if opt.local_rank == -1 or ("RANK" in os.environ and os.environ["RANK"] == "0"):
|
| 406 |
+
check_git_status()
|
| 407 |
+
|
| 408 |
+
opt.hyp = opt.hyp or ('data/hyp.finetune.yaml' if opt.weights else 'data/hyp.scratch.yaml')
|
| 409 |
+
opt.data, opt.cfg, opt.hyp = check_file(opt.data), check_file(opt.cfg), check_file(opt.hyp) # check files
|
| 410 |
+
assert len(opt.cfg) or len(opt.weights), 'either --cfg or --weights must be specified'
|
| 411 |
+
|
| 412 |
+
opt.img_size.extend([opt.img_size[-1]] * (2 - len(opt.img_size))) # extend to 2 sizes (train, test)
|
| 413 |
+
device = select_device(opt.device, batch_size=opt.batch_size)
|
| 414 |
+
opt.total_batch_size = opt.batch_size
|
| 415 |
+
opt.world_size = 1
|
| 416 |
+
opt.global_rank = -1
|
| 417 |
+
|
| 418 |
+
# DDP mode
|
| 419 |
+
if opt.local_rank != -1:
|
| 420 |
+
assert torch.cuda.device_count() > opt.local_rank
|
| 421 |
+
torch.cuda.set_device(opt.local_rank)
|
| 422 |
+
device = torch.device('cuda', opt.local_rank)
|
| 423 |
+
dist.init_process_group(backend='nccl', init_method='env://') # distributed backend
|
| 424 |
+
opt.world_size = dist.get_world_size()
|
| 425 |
+
opt.global_rank = dist.get_rank()
|
| 426 |
+
assert opt.batch_size % opt.world_size == 0, '--batch-size must be multiple of CUDA device count'
|
| 427 |
+
opt.batch_size = opt.total_batch_size // opt.world_size
|
| 428 |
+
|
| 429 |
+
print(opt)
|
| 430 |
+
with open(opt.hyp) as f:
|
| 431 |
+
hyp = yaml.load(f, Loader=yaml.FullLoader) # load hyps
|
| 432 |
+
|
| 433 |
+
# Train
|
| 434 |
+
if not opt.evolve:
|
| 435 |
+
tb_writer = None
|
| 436 |
+
if opt.global_rank in [-1, 0]:
|
| 437 |
+
print('Start Tensorboard with "tensorboard --logdir %s", view at http://localhost:6006/' % opt.logdir)
|
| 438 |
+
tb_writer = SummaryWriter(log_dir=increment_dir(Path(opt.logdir) / 'exp', opt.name)) # runs/exp
|
| 439 |
+
|
| 440 |
+
train(hyp, opt, device, tb_writer)
|
| 441 |
+
|
| 442 |
+
# Evolve hyperparameters (optional)
|
| 443 |
+
else:
|
| 444 |
+
# Hyperparameter evolution metadata (mutation scale 0-1, lower_limit, upper_limit)
|
| 445 |
+
meta = {'lr0': (1, 1e-5, 1e-1), # initial learning rate (SGD=1E-2, Adam=1E-3)
|
| 446 |
+
'momentum': (0.1, 0.6, 0.98), # SGD momentum/Adam beta1
|
| 447 |
+
'weight_decay': (1, 0.0, 0.001), # optimizer weight decay
|
| 448 |
+
'giou': (1, 0.02, 0.2), # GIoU loss gain
|
| 449 |
+
'cls': (1, 0.2, 4.0), # cls loss gain
|
| 450 |
+
'cls_pw': (1, 0.5, 2.0), # cls BCELoss positive_weight
|
| 451 |
+
'obj': (1, 0.2, 4.0), # obj loss gain (scale with pixels)
|
| 452 |
+
'obj_pw': (1, 0.5, 2.0), # obj BCELoss positive_weight
|
| 453 |
+
'iou_t': (0, 0.1, 0.7), # IoU training threshold
|
| 454 |
+
'anchor_t': (1, 2.0, 8.0), # anchor-multiple threshold
|
| 455 |
+
'fl_gamma': (0, 0.0, 2.0), # focal loss gamma (efficientDet default gamma=1.5)
|
| 456 |
+
'hsv_h': (1, 0.0, 0.1), # image HSV-Hue augmentation (fraction)
|
| 457 |
+
'hsv_s': (1, 0.0, 0.9), # image HSV-Saturation augmentation (fraction)
|
| 458 |
+
'hsv_v': (1, 0.0, 0.9), # image HSV-Value augmentation (fraction)
|
| 459 |
+
'degrees': (1, 0.0, 45.0), # image rotation (+/- deg)
|
| 460 |
+
'translate': (1, 0.0, 0.9), # image translation (+/- fraction)
|
| 461 |
+
'scale': (1, 0.0, 0.9), # image scale (+/- gain)
|
| 462 |
+
'shear': (1, 0.0, 10.0), # image shear (+/- deg)
|
| 463 |
+
'perspective': (1, 0.0, 0.001), # image perspective (+/- fraction), range 0-0.001
|
| 464 |
+
'flipud': (0, 0.0, 1.0), # image flip up-down (probability)
|
| 465 |
+
'fliplr': (1, 0.0, 1.0), # image flip left-right (probability)
|
| 466 |
+
'mixup': (1, 0.0, 1.0)} # image mixup (probability)
|
| 467 |
+
|
| 468 |
+
assert opt.local_rank == -1, 'DDP mode not implemented for --evolve'
|
| 469 |
+
opt.notest, opt.nosave = True, True # only test/save final epoch
|
| 470 |
+
# ei = [isinstance(x, (int, float)) for x in hyp.values()] # evolvable indices
|
| 471 |
+
yaml_file = Path('runs/evolve/hyp_evolved.yaml') # save best result here
|
| 472 |
+
if opt.bucket:
|
| 473 |
+
os.system('gsutil cp gs://%s/evolve.txt .' % opt.bucket) # download evolve.txt if exists
|
| 474 |
+
|
| 475 |
+
for _ in range(100): # generations to evolve
|
| 476 |
+
if os.path.exists('evolve.txt'): # if evolve.txt exists: select best hyps and mutate
|
| 477 |
+
# Select parent(s)
|
| 478 |
+
parent = 'single' # parent selection method: 'single' or 'weighted'
|
| 479 |
+
x = np.loadtxt('evolve.txt', ndmin=2)
|
| 480 |
+
n = min(5, len(x)) # number of previous results to consider
|
| 481 |
+
x = x[np.argsort(-fitness(x))][:n] # top n mutations
|
| 482 |
+
w = fitness(x) - fitness(x).min() # weights
|
| 483 |
+
if parent == 'single' or len(x) == 1:
|
| 484 |
+
# x = x[random.randint(0, n - 1)] # random selection
|
| 485 |
+
x = x[random.choices(range(n), weights=w)[0]] # weighted selection
|
| 486 |
+
elif parent == 'weighted':
|
| 487 |
+
x = (x * w.reshape(n, 1)).sum(0) / w.sum() # weighted combination
|
| 488 |
+
|
| 489 |
+
# Mutate
|
| 490 |
+
mp, s = 0.9, 0.2 # mutation probability, sigma
|
| 491 |
+
npr = np.random
|
| 492 |
+
npr.seed(int(time.time()))
|
| 493 |
+
g = np.array([x[0] for x in meta.values()]) # gains 0-1
|
| 494 |
+
ng = len(meta)
|
| 495 |
+
v = np.ones(ng)
|
| 496 |
+
while all(v == 1): # mutate until a change occurs (prevent duplicates)
|
| 497 |
+
v = (g * (npr.random(ng) < mp) * npr.randn(ng) * npr.random() * s + 1).clip(0.3, 3.0)
|
| 498 |
+
for i, k in enumerate(hyp.keys()): # plt.hist(v.ravel(), 300)
|
| 499 |
+
hyp[k] = float(x[i + 7] * v[i]) # mutate
|
| 500 |
+
|
| 501 |
+
# Constrain to limits
|
| 502 |
+
for k, v in meta.items():
|
| 503 |
+
hyp[k] = max(hyp[k], v[1]) # lower limit
|
| 504 |
+
hyp[k] = min(hyp[k], v[2]) # upper limit
|
| 505 |
+
hyp[k] = round(hyp[k], 5) # significant digits
|
| 506 |
+
|
| 507 |
+
# Train mutation
|
| 508 |
+
results = train(hyp.copy(), opt, device)
|
| 509 |
+
|
| 510 |
+
# Write mutation results
|
| 511 |
+
print_mutation(hyp.copy(), results, yaml_file, opt.bucket)
|
| 512 |
+
|
| 513 |
+
# Plot results
|
| 514 |
+
plot_evolution(yaml_file)
|
| 515 |
+
print('Hyperparameter evolution complete. Best results saved as: %s\nCommand to train a new model with these '
|
| 516 |
+
'hyperparameters: $ python train.py --hyp %s' % (yaml_file, yaml_file))
|
yolov5_anime/utils/__init__.py
ADDED
|
File without changes
|
yolov5_anime/utils/activations.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
# Swish https://arxiv.org/pdf/1905.02244.pdf ---------------------------------------------------------------------------
|
| 7 |
+
class Swish(nn.Module): #
|
| 8 |
+
@staticmethod
|
| 9 |
+
def forward(x):
|
| 10 |
+
return x * torch.sigmoid(x)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class HardSwish(nn.Module):
|
| 14 |
+
@staticmethod
|
| 15 |
+
def forward(x):
|
| 16 |
+
return x * F.hardtanh(x + 3, 0., 6., True) / 6.
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class MemoryEfficientSwish(nn.Module):
|
| 20 |
+
class F(torch.autograd.Function):
|
| 21 |
+
@staticmethod
|
| 22 |
+
def forward(ctx, x):
|
| 23 |
+
ctx.save_for_backward(x)
|
| 24 |
+
return x * torch.sigmoid(x)
|
| 25 |
+
|
| 26 |
+
@staticmethod
|
| 27 |
+
def backward(ctx, grad_output):
|
| 28 |
+
x = ctx.saved_tensors[0]
|
| 29 |
+
sx = torch.sigmoid(x)
|
| 30 |
+
return grad_output * (sx * (1 + x * (1 - sx)))
|
| 31 |
+
|
| 32 |
+
def forward(self, x):
|
| 33 |
+
return self.F.apply(x)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# Mish https://github.com/digantamisra98/Mish --------------------------------------------------------------------------
|
| 37 |
+
class Mish(nn.Module):
|
| 38 |
+
@staticmethod
|
| 39 |
+
def forward(x):
|
| 40 |
+
return x * F.softplus(x).tanh()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class MemoryEfficientMish(nn.Module):
|
| 44 |
+
class F(torch.autograd.Function):
|
| 45 |
+
@staticmethod
|
| 46 |
+
def forward(ctx, x):
|
| 47 |
+
ctx.save_for_backward(x)
|
| 48 |
+
return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x)))
|
| 49 |
+
|
| 50 |
+
@staticmethod
|
| 51 |
+
def backward(ctx, grad_output):
|
| 52 |
+
x = ctx.saved_tensors[0]
|
| 53 |
+
sx = torch.sigmoid(x)
|
| 54 |
+
fx = F.softplus(x).tanh()
|
| 55 |
+
return grad_output * (fx + x * sx * (1 - fx * fx))
|
| 56 |
+
|
| 57 |
+
def forward(self, x):
|
| 58 |
+
return self.F.apply(x)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# FReLU https://arxiv.org/abs/2007.11824 -------------------------------------------------------------------------------
|
| 62 |
+
class FReLU(nn.Module):
|
| 63 |
+
def __init__(self, c1, k=3): # ch_in, kernel
|
| 64 |
+
super().__init__()
|
| 65 |
+
self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1)
|
| 66 |
+
self.bn = nn.BatchNorm2d(c1)
|
| 67 |
+
|
| 68 |
+
def forward(self, x):
|
| 69 |
+
return torch.max(x, self.bn(self.conv(x)))
|
yolov5_anime/utils/datasets.py
ADDED
|
@@ -0,0 +1,907 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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1 |
+
import glob
|
| 2 |
+
import math
|
| 3 |
+
import os
|
| 4 |
+
import random
|
| 5 |
+
import shutil
|
| 6 |
+
import time
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from threading import Thread
|
| 9 |
+
|
| 10 |
+
import cv2
|
| 11 |
+
import numpy as np
|
| 12 |
+
import torch
|
| 13 |
+
from PIL import Image, ExifTags
|
| 14 |
+
from torch.utils.data import Dataset
|
| 15 |
+
from tqdm import tqdm
|
| 16 |
+
|
| 17 |
+
from utils.general import xyxy2xywh, xywh2xyxy, torch_distributed_zero_first
|
| 18 |
+
|
| 19 |
+
help_url = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data'
|
| 20 |
+
img_formats = ['.bmp', '.jpg', '.jpeg', '.png', '.tif', '.tiff', '.dng']
|
| 21 |
+
vid_formats = ['.mov', '.avi', '.mp4', '.mpg', '.mpeg', '.m4v', '.wmv', '.mkv']
|
| 22 |
+
|
| 23 |
+
# Get orientation exif tag
|
| 24 |
+
for orientation in ExifTags.TAGS.keys():
|
| 25 |
+
if ExifTags.TAGS[orientation] == 'Orientation':
|
| 26 |
+
break
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def get_hash(files):
|
| 30 |
+
# Returns a single hash value of a list of files
|
| 31 |
+
return sum(os.path.getsize(f) for f in files if os.path.isfile(f))
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def exif_size(img):
|
| 35 |
+
# Returns exif-corrected PIL size
|
| 36 |
+
s = img.size # (width, height)
|
| 37 |
+
try:
|
| 38 |
+
rotation = dict(img._getexif().items())[orientation]
|
| 39 |
+
if rotation == 6: # rotation 270
|
| 40 |
+
s = (s[1], s[0])
|
| 41 |
+
elif rotation == 8: # rotation 90
|
| 42 |
+
s = (s[1], s[0])
|
| 43 |
+
except:
|
| 44 |
+
pass
|
| 45 |
+
|
| 46 |
+
return s
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def create_dataloader(path, imgsz, batch_size, stride, opt, hyp=None, augment=False, cache=False, pad=0.0, rect=False,
|
| 50 |
+
local_rank=-1, world_size=1):
|
| 51 |
+
# Make sure only the first process in DDP process the dataset first, and the following others can use the cache.
|
| 52 |
+
with torch_distributed_zero_first(local_rank):
|
| 53 |
+
dataset = LoadImagesAndLabels(path, imgsz, batch_size,
|
| 54 |
+
augment=augment, # augment images
|
| 55 |
+
hyp=hyp, # augmentation hyperparameters
|
| 56 |
+
rect=rect, # rectangular training
|
| 57 |
+
cache_images=cache,
|
| 58 |
+
single_cls=opt.single_cls,
|
| 59 |
+
stride=int(stride),
|
| 60 |
+
pad=pad)
|
| 61 |
+
|
| 62 |
+
batch_size = min(batch_size, len(dataset))
|
| 63 |
+
nw = min([os.cpu_count() // world_size, batch_size if batch_size > 1 else 0, 8]) # number of workers
|
| 64 |
+
train_sampler = torch.utils.data.distributed.DistributedSampler(dataset) if local_rank != -1 else None
|
| 65 |
+
dataloader = torch.utils.data.DataLoader(dataset,
|
| 66 |
+
batch_size=batch_size,
|
| 67 |
+
num_workers=nw,
|
| 68 |
+
sampler=train_sampler,
|
| 69 |
+
pin_memory=True,
|
| 70 |
+
collate_fn=LoadImagesAndLabels.collate_fn)
|
| 71 |
+
return dataloader, dataset
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class LoadImages: # for inference
|
| 75 |
+
def __init__(self, path, img_size=640):
|
| 76 |
+
p = str(Path(path)) # os-agnostic
|
| 77 |
+
p = os.path.abspath(p) # absolute path
|
| 78 |
+
if '*' in p:
|
| 79 |
+
files = sorted(glob.glob(p)) # glob
|
| 80 |
+
elif os.path.isdir(p):
|
| 81 |
+
files = sorted(glob.glob(os.path.join(p, '*.*'))) # dir
|
| 82 |
+
elif os.path.isfile(p):
|
| 83 |
+
files = [p] # files
|
| 84 |
+
else:
|
| 85 |
+
raise Exception('ERROR: %s does not exist' % p)
|
| 86 |
+
|
| 87 |
+
images = [x for x in files if os.path.splitext(x)[-1].lower() in img_formats]
|
| 88 |
+
videos = [x for x in files if os.path.splitext(x)[-1].lower() in vid_formats]
|
| 89 |
+
ni, nv = len(images), len(videos)
|
| 90 |
+
|
| 91 |
+
self.img_size = img_size
|
| 92 |
+
self.files = images + videos
|
| 93 |
+
self.nf = ni + nv # number of files
|
| 94 |
+
self.video_flag = [False] * ni + [True] * nv
|
| 95 |
+
self.mode = 'images'
|
| 96 |
+
if any(videos):
|
| 97 |
+
self.new_video(videos[0]) # new video
|
| 98 |
+
else:
|
| 99 |
+
self.cap = None
|
| 100 |
+
assert self.nf > 0, 'No images or videos found in %s. Supported formats are:\nimages: %s\nvideos: %s' % \
|
| 101 |
+
(p, img_formats, vid_formats)
|
| 102 |
+
|
| 103 |
+
def __iter__(self):
|
| 104 |
+
self.count = 0
|
| 105 |
+
return self
|
| 106 |
+
|
| 107 |
+
def __next__(self):
|
| 108 |
+
if self.count == self.nf:
|
| 109 |
+
raise StopIteration
|
| 110 |
+
path = self.files[self.count]
|
| 111 |
+
|
| 112 |
+
if self.video_flag[self.count]:
|
| 113 |
+
# Read video
|
| 114 |
+
self.mode = 'video'
|
| 115 |
+
ret_val, img0 = self.cap.read()
|
| 116 |
+
if not ret_val:
|
| 117 |
+
self.count += 1
|
| 118 |
+
self.cap.release()
|
| 119 |
+
if self.count == self.nf: # last video
|
| 120 |
+
raise StopIteration
|
| 121 |
+
else:
|
| 122 |
+
path = self.files[self.count]
|
| 123 |
+
self.new_video(path)
|
| 124 |
+
ret_val, img0 = self.cap.read()
|
| 125 |
+
|
| 126 |
+
self.frame += 1
|
| 127 |
+
print('video %g/%g (%g/%g) %s: ' % (self.count + 1, self.nf, self.frame, self.nframes, path), end='')
|
| 128 |
+
|
| 129 |
+
else:
|
| 130 |
+
# Read image
|
| 131 |
+
self.count += 1
|
| 132 |
+
img0 = cv2.imread(path) # BGR
|
| 133 |
+
assert img0 is not None, 'Image Not Found ' + path
|
| 134 |
+
print('image %g/%g %s: ' % (self.count, self.nf, path), end='')
|
| 135 |
+
|
| 136 |
+
# Padded resize
|
| 137 |
+
img = letterbox(img0, new_shape=self.img_size)[0]
|
| 138 |
+
|
| 139 |
+
# Convert
|
| 140 |
+
img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
|
| 141 |
+
img = np.ascontiguousarray(img)
|
| 142 |
+
|
| 143 |
+
# cv2.imwrite(path + '.letterbox.jpg', 255 * img.transpose((1, 2, 0))[:, :, ::-1]) # save letterbox image
|
| 144 |
+
return path, img, img0, self.cap
|
| 145 |
+
|
| 146 |
+
def new_video(self, path):
|
| 147 |
+
self.frame = 0
|
| 148 |
+
self.cap = cv2.VideoCapture(path)
|
| 149 |
+
self.nframes = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 150 |
+
|
| 151 |
+
def __len__(self):
|
| 152 |
+
return self.nf # number of files
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
class LoadWebcam: # for inference
|
| 156 |
+
def __init__(self, pipe=0, img_size=640):
|
| 157 |
+
self.img_size = img_size
|
| 158 |
+
|
| 159 |
+
if pipe == '0':
|
| 160 |
+
pipe = 0 # local camera
|
| 161 |
+
# pipe = 'rtsp://192.168.1.64/1' # IP camera
|
| 162 |
+
# pipe = 'rtsp://username:[email protected]/1' # IP camera with login
|
| 163 |
+
# pipe = 'rtsp://170.93.143.139/rtplive/470011e600ef003a004ee33696235daa' # IP traffic camera
|
| 164 |
+
# pipe = 'http://wmccpinetop.axiscam.net/mjpg/video.mjpg' # IP golf camera
|
| 165 |
+
|
| 166 |
+
# https://answers.opencv.org/question/215996/changing-gstreamer-pipeline-to-opencv-in-pythonsolved/
|
| 167 |
+
# pipe = '"rtspsrc location="rtsp://username:[email protected]/1" latency=10 ! appsink' # GStreamer
|
| 168 |
+
|
| 169 |
+
# https://answers.opencv.org/question/200787/video-acceleration-gstremer-pipeline-in-videocapture/
|
| 170 |
+
# https://stackoverflow.com/questions/54095699/install-gstreamer-support-for-opencv-python-package # install help
|
| 171 |
+
# pipe = "rtspsrc location=rtsp://root:[email protected]:554/axis-media/media.amp?videocodec=h264&resolution=3840x2160 protocols=GST_RTSP_LOWER_TRANS_TCP ! rtph264depay ! queue ! vaapih264dec ! videoconvert ! appsink" # GStreamer
|
| 172 |
+
|
| 173 |
+
self.pipe = pipe
|
| 174 |
+
self.cap = cv2.VideoCapture(pipe) # video capture object
|
| 175 |
+
self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3) # set buffer size
|
| 176 |
+
|
| 177 |
+
def __iter__(self):
|
| 178 |
+
self.count = -1
|
| 179 |
+
return self
|
| 180 |
+
|
| 181 |
+
def __next__(self):
|
| 182 |
+
self.count += 1
|
| 183 |
+
if cv2.waitKey(1) == ord('q'): # q to quit
|
| 184 |
+
self.cap.release()
|
| 185 |
+
cv2.destroyAllWindows()
|
| 186 |
+
raise StopIteration
|
| 187 |
+
|
| 188 |
+
# Read frame
|
| 189 |
+
if self.pipe == 0: # local camera
|
| 190 |
+
ret_val, img0 = self.cap.read()
|
| 191 |
+
img0 = cv2.flip(img0, 1) # flip left-right
|
| 192 |
+
else: # IP camera
|
| 193 |
+
n = 0
|
| 194 |
+
while True:
|
| 195 |
+
n += 1
|
| 196 |
+
self.cap.grab()
|
| 197 |
+
if n % 30 == 0: # skip frames
|
| 198 |
+
ret_val, img0 = self.cap.retrieve()
|
| 199 |
+
if ret_val:
|
| 200 |
+
break
|
| 201 |
+
|
| 202 |
+
# Print
|
| 203 |
+
assert ret_val, 'Camera Error %s' % self.pipe
|
| 204 |
+
img_path = 'webcam.jpg'
|
| 205 |
+
print('webcam %g: ' % self.count, end='')
|
| 206 |
+
|
| 207 |
+
# Padded resize
|
| 208 |
+
img = letterbox(img0, new_shape=self.img_size)[0]
|
| 209 |
+
|
| 210 |
+
# Convert
|
| 211 |
+
img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
|
| 212 |
+
img = np.ascontiguousarray(img)
|
| 213 |
+
|
| 214 |
+
return img_path, img, img0, None
|
| 215 |
+
|
| 216 |
+
def __len__(self):
|
| 217 |
+
return 0
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class LoadStreams: # multiple IP or RTSP cameras
|
| 221 |
+
def __init__(self, sources='streams.txt', img_size=640):
|
| 222 |
+
self.mode = 'images'
|
| 223 |
+
self.img_size = img_size
|
| 224 |
+
|
| 225 |
+
if os.path.isfile(sources):
|
| 226 |
+
with open(sources, 'r') as f:
|
| 227 |
+
sources = [x.strip() for x in f.read().splitlines() if len(x.strip())]
|
| 228 |
+
else:
|
| 229 |
+
sources = [sources]
|
| 230 |
+
|
| 231 |
+
n = len(sources)
|
| 232 |
+
self.imgs = [None] * n
|
| 233 |
+
self.sources = sources
|
| 234 |
+
for i, s in enumerate(sources):
|
| 235 |
+
# Start the thread to read frames from the video stream
|
| 236 |
+
print('%g/%g: %s... ' % (i + 1, n, s), end='')
|
| 237 |
+
cap = cv2.VideoCapture(0 if s == '0' else s)
|
| 238 |
+
assert cap.isOpened(), 'Failed to open %s' % s
|
| 239 |
+
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
| 240 |
+
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
| 241 |
+
fps = cap.get(cv2.CAP_PROP_FPS) % 100
|
| 242 |
+
_, self.imgs[i] = cap.read() # guarantee first frame
|
| 243 |
+
thread = Thread(target=self.update, args=([i, cap]), daemon=True)
|
| 244 |
+
print(' success (%gx%g at %.2f FPS).' % (w, h, fps))
|
| 245 |
+
thread.start()
|
| 246 |
+
print('') # newline
|
| 247 |
+
|
| 248 |
+
# check for common shapes
|
| 249 |
+
s = np.stack([letterbox(x, new_shape=self.img_size)[0].shape for x in self.imgs], 0) # inference shapes
|
| 250 |
+
self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal
|
| 251 |
+
if not self.rect:
|
| 252 |
+
print('WARNING: Different stream shapes detected. For optimal performance supply similarly-shaped streams.')
|
| 253 |
+
|
| 254 |
+
def update(self, index, cap):
|
| 255 |
+
# Read next stream frame in a daemon thread
|
| 256 |
+
n = 0
|
| 257 |
+
while cap.isOpened():
|
| 258 |
+
n += 1
|
| 259 |
+
# _, self.imgs[index] = cap.read()
|
| 260 |
+
cap.grab()
|
| 261 |
+
if n == 4: # read every 4th frame
|
| 262 |
+
_, self.imgs[index] = cap.retrieve()
|
| 263 |
+
n = 0
|
| 264 |
+
time.sleep(0.01) # wait time
|
| 265 |
+
|
| 266 |
+
def __iter__(self):
|
| 267 |
+
self.count = -1
|
| 268 |
+
return self
|
| 269 |
+
|
| 270 |
+
def __next__(self):
|
| 271 |
+
self.count += 1
|
| 272 |
+
img0 = self.imgs.copy()
|
| 273 |
+
if cv2.waitKey(1) == ord('q'): # q to quit
|
| 274 |
+
cv2.destroyAllWindows()
|
| 275 |
+
raise StopIteration
|
| 276 |
+
|
| 277 |
+
# Letterbox
|
| 278 |
+
img = [letterbox(x, new_shape=self.img_size, auto=self.rect)[0] for x in img0]
|
| 279 |
+
|
| 280 |
+
# Stack
|
| 281 |
+
img = np.stack(img, 0)
|
| 282 |
+
|
| 283 |
+
# Convert
|
| 284 |
+
img = img[:, :, :, ::-1].transpose(0, 3, 1, 2) # BGR to RGB, to bsx3x416x416
|
| 285 |
+
img = np.ascontiguousarray(img)
|
| 286 |
+
|
| 287 |
+
return self.sources, img, img0, None
|
| 288 |
+
|
| 289 |
+
def __len__(self):
|
| 290 |
+
return 0 # 1E12 frames = 32 streams at 30 FPS for 30 years
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
class LoadImagesAndLabels(Dataset): # for training/testing
|
| 294 |
+
def __init__(self, path, img_size=640, batch_size=16, augment=False, hyp=None, rect=False, image_weights=False,
|
| 295 |
+
cache_images=False, single_cls=False, stride=32, pad=0.0):
|
| 296 |
+
try:
|
| 297 |
+
f = [] # image files
|
| 298 |
+
for p in path if isinstance(path, list) else [path]:
|
| 299 |
+
p = str(Path(p)) # os-agnostic
|
| 300 |
+
parent = str(Path(p).parent) + os.sep
|
| 301 |
+
if os.path.isfile(p): # file
|
| 302 |
+
with open(p, 'r') as t:
|
| 303 |
+
t = t.read().splitlines()
|
| 304 |
+
f += [x.replace('./', parent) if x.startswith('./') else x for x in t] # local to global path
|
| 305 |
+
elif os.path.isdir(p): # folder
|
| 306 |
+
f += glob.iglob(p + os.sep + '*.*')
|
| 307 |
+
else:
|
| 308 |
+
raise Exception('%s does not exist' % p)
|
| 309 |
+
self.img_files = sorted(
|
| 310 |
+
[x.replace('/', os.sep) for x in f if os.path.splitext(x)[-1].lower() in img_formats])
|
| 311 |
+
except Exception as e:
|
| 312 |
+
raise Exception('Error loading data from %s: %s\nSee %s' % (path, e, help_url))
|
| 313 |
+
|
| 314 |
+
n = len(self.img_files)
|
| 315 |
+
assert n > 0, 'No images found in %s. See %s' % (path, help_url)
|
| 316 |
+
bi = np.floor(np.arange(n) / batch_size).astype(np.int) # batch index
|
| 317 |
+
nb = bi[-1] + 1 # number of batches
|
| 318 |
+
|
| 319 |
+
self.n = n # number of images
|
| 320 |
+
self.batch = bi # batch index of image
|
| 321 |
+
self.img_size = img_size
|
| 322 |
+
self.augment = augment
|
| 323 |
+
self.hyp = hyp
|
| 324 |
+
self.image_weights = image_weights
|
| 325 |
+
self.rect = False if image_weights else rect
|
| 326 |
+
self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training)
|
| 327 |
+
self.mosaic_border = [-img_size // 2, -img_size // 2]
|
| 328 |
+
self.stride = stride
|
| 329 |
+
|
| 330 |
+
# Define labels
|
| 331 |
+
self.label_files = [x.replace('images', 'labels').replace(os.path.splitext(x)[-1], '.txt') for x in
|
| 332 |
+
self.img_files]
|
| 333 |
+
|
| 334 |
+
# Check cache
|
| 335 |
+
cache_path = str(Path(self.label_files[0]).parent) + '.cache' # cached labels
|
| 336 |
+
if os.path.isfile(cache_path):
|
| 337 |
+
cache = torch.load(cache_path) # load
|
| 338 |
+
if cache['hash'] != get_hash(self.label_files + self.img_files): # dataset changed
|
| 339 |
+
cache = self.cache_labels(cache_path) # re-cache
|
| 340 |
+
else:
|
| 341 |
+
cache = self.cache_labels(cache_path) # cache
|
| 342 |
+
|
| 343 |
+
# Get labels
|
| 344 |
+
labels, shapes = zip(*[cache[x] for x in self.img_files])
|
| 345 |
+
self.shapes = np.array(shapes, dtype=np.float64)
|
| 346 |
+
self.labels = list(labels)
|
| 347 |
+
|
| 348 |
+
# Rectangular Training https://github.com/ultralytics/yolov3/issues/232
|
| 349 |
+
if self.rect:
|
| 350 |
+
# Sort by aspect ratio
|
| 351 |
+
s = self.shapes # wh
|
| 352 |
+
ar = s[:, 1] / s[:, 0] # aspect ratio
|
| 353 |
+
irect = ar.argsort()
|
| 354 |
+
self.img_files = [self.img_files[i] for i in irect]
|
| 355 |
+
self.label_files = [self.label_files[i] for i in irect]
|
| 356 |
+
self.labels = [self.labels[i] for i in irect]
|
| 357 |
+
self.shapes = s[irect] # wh
|
| 358 |
+
ar = ar[irect]
|
| 359 |
+
|
| 360 |
+
# Set training image shapes
|
| 361 |
+
shapes = [[1, 1]] * nb
|
| 362 |
+
for i in range(nb):
|
| 363 |
+
ari = ar[bi == i]
|
| 364 |
+
mini, maxi = ari.min(), ari.max()
|
| 365 |
+
if maxi < 1:
|
| 366 |
+
shapes[i] = [maxi, 1]
|
| 367 |
+
elif mini > 1:
|
| 368 |
+
shapes[i] = [1, 1 / mini]
|
| 369 |
+
|
| 370 |
+
self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int) * stride
|
| 371 |
+
|
| 372 |
+
# Cache labels
|
| 373 |
+
create_datasubset, extract_bounding_boxes, labels_loaded = False, False, False
|
| 374 |
+
nm, nf, ne, ns, nd = 0, 0, 0, 0, 0 # number missing, found, empty, datasubset, duplicate
|
| 375 |
+
pbar = tqdm(self.label_files)
|
| 376 |
+
for i, file in enumerate(pbar):
|
| 377 |
+
l = self.labels[i] # label
|
| 378 |
+
if l.shape[0]:
|
| 379 |
+
assert l.shape[1] == 5, '> 5 label columns: %s' % file
|
| 380 |
+
assert (l >= 0).all(), 'negative labels: %s' % file
|
| 381 |
+
assert (l[:, 1:] <= 1).all(), 'non-normalized or out of bounds coordinate labels: %s' % file
|
| 382 |
+
if np.unique(l, axis=0).shape[0] < l.shape[0]: # duplicate rows
|
| 383 |
+
nd += 1 # print('WARNING: duplicate rows in %s' % self.label_files[i]) # duplicate rows
|
| 384 |
+
if single_cls:
|
| 385 |
+
l[:, 0] = 0 # force dataset into single-class mode
|
| 386 |
+
self.labels[i] = l
|
| 387 |
+
nf += 1 # file found
|
| 388 |
+
|
| 389 |
+
# Create subdataset (a smaller dataset)
|
| 390 |
+
if create_datasubset and ns < 1E4:
|
| 391 |
+
if ns == 0:
|
| 392 |
+
create_folder(path='./datasubset')
|
| 393 |
+
os.makedirs('./datasubset/images')
|
| 394 |
+
exclude_classes = 43
|
| 395 |
+
if exclude_classes not in l[:, 0]:
|
| 396 |
+
ns += 1
|
| 397 |
+
# shutil.copy(src=self.img_files[i], dst='./datasubset/images/') # copy image
|
| 398 |
+
with open('./datasubset/images.txt', 'a') as f:
|
| 399 |
+
f.write(self.img_files[i] + '\n')
|
| 400 |
+
|
| 401 |
+
# Extract object detection boxes for a second stage classifier
|
| 402 |
+
if extract_bounding_boxes:
|
| 403 |
+
p = Path(self.img_files[i])
|
| 404 |
+
img = cv2.imread(str(p))
|
| 405 |
+
h, w = img.shape[:2]
|
| 406 |
+
for j, x in enumerate(l):
|
| 407 |
+
f = '%s%sclassifier%s%g_%g_%s' % (p.parent.parent, os.sep, os.sep, x[0], j, p.name)
|
| 408 |
+
if not os.path.exists(Path(f).parent):
|
| 409 |
+
os.makedirs(Path(f).parent) # make new output folder
|
| 410 |
+
|
| 411 |
+
b = x[1:] * [w, h, w, h] # box
|
| 412 |
+
b[2:] = b[2:].max() # rectangle to square
|
| 413 |
+
b[2:] = b[2:] * 1.3 + 30 # pad
|
| 414 |
+
b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int)
|
| 415 |
+
|
| 416 |
+
b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image
|
| 417 |
+
b[[1, 3]] = np.clip(b[[1, 3]], 0, h)
|
| 418 |
+
assert cv2.imwrite(f, img[b[1]:b[3], b[0]:b[2]]), 'Failure extracting classifier boxes'
|
| 419 |
+
else:
|
| 420 |
+
ne += 1 # print('empty labels for image %s' % self.img_files[i]) # file empty
|
| 421 |
+
# os.system("rm '%s' '%s'" % (self.img_files[i], self.label_files[i])) # remove
|
| 422 |
+
|
| 423 |
+
pbar.desc = 'Scanning labels %s (%g found, %g missing, %g empty, %g duplicate, for %g images)' % (
|
| 424 |
+
cache_path, nf, nm, ne, nd, n)
|
| 425 |
+
if nf == 0:
|
| 426 |
+
s = 'WARNING: No labels found in %s. See %s' % (os.path.dirname(file) + os.sep, help_url)
|
| 427 |
+
print(s)
|
| 428 |
+
assert not augment, '%s. Can not train without labels.' % s
|
| 429 |
+
|
| 430 |
+
# Cache images into memory for faster training (WARNING: large datasets may exceed system RAM)
|
| 431 |
+
self.imgs = [None] * n
|
| 432 |
+
if cache_images:
|
| 433 |
+
gb = 0 # Gigabytes of cached images
|
| 434 |
+
pbar = tqdm(range(len(self.img_files)), desc='Caching images')
|
| 435 |
+
self.img_hw0, self.img_hw = [None] * n, [None] * n
|
| 436 |
+
for i in pbar: # max 10k images
|
| 437 |
+
self.imgs[i], self.img_hw0[i], self.img_hw[i] = load_image(self, i) # img, hw_original, hw_resized
|
| 438 |
+
gb += self.imgs[i].nbytes
|
| 439 |
+
pbar.desc = 'Caching images (%.1fGB)' % (gb / 1E9)
|
| 440 |
+
|
| 441 |
+
def cache_labels(self, path='labels.cache'):
|
| 442 |
+
# Cache dataset labels, check images and read shapes
|
| 443 |
+
x = {} # dict
|
| 444 |
+
pbar = tqdm(zip(self.img_files, self.label_files), desc='Scanning images', total=len(self.img_files))
|
| 445 |
+
for (img, label) in pbar:
|
| 446 |
+
try:
|
| 447 |
+
l = []
|
| 448 |
+
image = Image.open(img)
|
| 449 |
+
image.verify() # PIL verify
|
| 450 |
+
# _ = io.imread(img) # skimage verify (from skimage import io)
|
| 451 |
+
shape = exif_size(image) # image size
|
| 452 |
+
assert (shape[0] > 9) & (shape[1] > 9), 'image size <10 pixels'
|
| 453 |
+
if os.path.isfile(label):
|
| 454 |
+
with open(label, 'r') as f:
|
| 455 |
+
l = np.array([x.split() for x in f.read().splitlines()], dtype=np.float32) # labels
|
| 456 |
+
if len(l) == 0:
|
| 457 |
+
l = np.zeros((0, 5), dtype=np.float32)
|
| 458 |
+
x[img] = [l, shape]
|
| 459 |
+
except Exception as e:
|
| 460 |
+
x[img] = [None, None]
|
| 461 |
+
print('WARNING: %s: %s' % (img, e))
|
| 462 |
+
|
| 463 |
+
x['hash'] = get_hash(self.label_files + self.img_files)
|
| 464 |
+
torch.save(x, path) # save for next time
|
| 465 |
+
return x
|
| 466 |
+
|
| 467 |
+
def __len__(self):
|
| 468 |
+
return len(self.img_files)
|
| 469 |
+
|
| 470 |
+
# def __iter__(self):
|
| 471 |
+
# self.count = -1
|
| 472 |
+
# print('ran dataset iter')
|
| 473 |
+
# #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF)
|
| 474 |
+
# return self
|
| 475 |
+
|
| 476 |
+
def __getitem__(self, index):
|
| 477 |
+
if self.image_weights:
|
| 478 |
+
index = self.indices[index]
|
| 479 |
+
|
| 480 |
+
hyp = self.hyp
|
| 481 |
+
if self.mosaic:
|
| 482 |
+
# Load mosaic
|
| 483 |
+
img, labels = load_mosaic(self, index)
|
| 484 |
+
shapes = None
|
| 485 |
+
|
| 486 |
+
# MixUp https://arxiv.org/pdf/1710.09412.pdf
|
| 487 |
+
if random.random() < hyp['mixup']:
|
| 488 |
+
img2, labels2 = load_mosaic(self, random.randint(0, len(self.labels) - 1))
|
| 489 |
+
r = np.random.beta(8.0, 8.0) # mixup ratio, alpha=beta=8.0
|
| 490 |
+
img = (img * r + img2 * (1 - r)).astype(np.uint8)
|
| 491 |
+
labels = np.concatenate((labels, labels2), 0)
|
| 492 |
+
|
| 493 |
+
else:
|
| 494 |
+
# Load image
|
| 495 |
+
img, (h0, w0), (h, w) = load_image(self, index)
|
| 496 |
+
|
| 497 |
+
# Letterbox
|
| 498 |
+
shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape
|
| 499 |
+
img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment)
|
| 500 |
+
shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling
|
| 501 |
+
|
| 502 |
+
# Load labels
|
| 503 |
+
labels = []
|
| 504 |
+
x = self.labels[index]
|
| 505 |
+
if x.size > 0:
|
| 506 |
+
# Normalized xywh to pixel xyxy format
|
| 507 |
+
labels = x.copy()
|
| 508 |
+
labels[:, 1] = ratio[0] * w * (x[:, 1] - x[:, 3] / 2) + pad[0] # pad width
|
| 509 |
+
labels[:, 2] = ratio[1] * h * (x[:, 2] - x[:, 4] / 2) + pad[1] # pad height
|
| 510 |
+
labels[:, 3] = ratio[0] * w * (x[:, 1] + x[:, 3] / 2) + pad[0]
|
| 511 |
+
labels[:, 4] = ratio[1] * h * (x[:, 2] + x[:, 4] / 2) + pad[1]
|
| 512 |
+
|
| 513 |
+
if self.augment:
|
| 514 |
+
# Augment imagespace
|
| 515 |
+
if not self.mosaic:
|
| 516 |
+
img, labels = random_perspective(img, labels,
|
| 517 |
+
degrees=hyp['degrees'],
|
| 518 |
+
translate=hyp['translate'],
|
| 519 |
+
scale=hyp['scale'],
|
| 520 |
+
shear=hyp['shear'],
|
| 521 |
+
perspective=hyp['perspective'])
|
| 522 |
+
|
| 523 |
+
# Augment colorspace
|
| 524 |
+
augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v'])
|
| 525 |
+
|
| 526 |
+
# Apply cutouts
|
| 527 |
+
# if random.random() < 0.9:
|
| 528 |
+
# labels = cutout(img, labels)
|
| 529 |
+
|
| 530 |
+
nL = len(labels) # number of labels
|
| 531 |
+
if nL:
|
| 532 |
+
labels[:, 1:5] = xyxy2xywh(labels[:, 1:5]) # convert xyxy to xywh
|
| 533 |
+
labels[:, [2, 4]] /= img.shape[0] # normalized height 0-1
|
| 534 |
+
labels[:, [1, 3]] /= img.shape[1] # normalized width 0-1
|
| 535 |
+
|
| 536 |
+
if self.augment:
|
| 537 |
+
# flip up-down
|
| 538 |
+
if random.random() < hyp['flipud']:
|
| 539 |
+
img = np.flipud(img)
|
| 540 |
+
if nL:
|
| 541 |
+
labels[:, 2] = 1 - labels[:, 2]
|
| 542 |
+
|
| 543 |
+
# flip left-right
|
| 544 |
+
if random.random() < hyp['fliplr']:
|
| 545 |
+
img = np.fliplr(img)
|
| 546 |
+
if nL:
|
| 547 |
+
labels[:, 1] = 1 - labels[:, 1]
|
| 548 |
+
|
| 549 |
+
labels_out = torch.zeros((nL, 6))
|
| 550 |
+
if nL:
|
| 551 |
+
labels_out[:, 1:] = torch.from_numpy(labels)
|
| 552 |
+
|
| 553 |
+
# Convert
|
| 554 |
+
img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
|
| 555 |
+
img = np.ascontiguousarray(img)
|
| 556 |
+
|
| 557 |
+
return torch.from_numpy(img), labels_out, self.img_files[index], shapes
|
| 558 |
+
|
| 559 |
+
@staticmethod
|
| 560 |
+
def collate_fn(batch):
|
| 561 |
+
img, label, path, shapes = zip(*batch) # transposed
|
| 562 |
+
for i, l in enumerate(label):
|
| 563 |
+
l[:, 0] = i # add target image index for build_targets()
|
| 564 |
+
return torch.stack(img, 0), torch.cat(label, 0), path, shapes
|
| 565 |
+
|
| 566 |
+
|
| 567 |
+
# Ancillary functions --------------------------------------------------------------------------------------------------
|
| 568 |
+
def load_image(self, index):
|
| 569 |
+
# loads 1 image from dataset, returns img, original hw, resized hw
|
| 570 |
+
img = self.imgs[index]
|
| 571 |
+
if img is None: # not cached
|
| 572 |
+
path = self.img_files[index]
|
| 573 |
+
img = cv2.imread(path) # BGR
|
| 574 |
+
assert img is not None, 'Image Not Found ' + path
|
| 575 |
+
h0, w0 = img.shape[:2] # orig hw
|
| 576 |
+
r = self.img_size / max(h0, w0) # resize image to img_size
|
| 577 |
+
if r != 1: # always resize down, only resize up if training with augmentation
|
| 578 |
+
interp = cv2.INTER_AREA if r < 1 and not self.augment else cv2.INTER_LINEAR
|
| 579 |
+
img = cv2.resize(img, (int(w0 * r), int(h0 * r)), interpolation=interp)
|
| 580 |
+
return img, (h0, w0), img.shape[:2] # img, hw_original, hw_resized
|
| 581 |
+
else:
|
| 582 |
+
return self.imgs[index], self.img_hw0[index], self.img_hw[index] # img, hw_original, hw_resized
|
| 583 |
+
|
| 584 |
+
|
| 585 |
+
def augment_hsv(img, hgain=0.5, sgain=0.5, vgain=0.5):
|
| 586 |
+
r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains
|
| 587 |
+
hue, sat, val = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))
|
| 588 |
+
dtype = img.dtype # uint8
|
| 589 |
+
|
| 590 |
+
x = np.arange(0, 256, dtype=np.int16)
|
| 591 |
+
lut_hue = ((x * r[0]) % 180).astype(dtype)
|
| 592 |
+
lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
|
| 593 |
+
lut_val = np.clip(x * r[2], 0, 255).astype(dtype)
|
| 594 |
+
|
| 595 |
+
img_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))).astype(dtype)
|
| 596 |
+
cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR, dst=img) # no return needed
|
| 597 |
+
|
| 598 |
+
# Histogram equalization
|
| 599 |
+
# if random.random() < 0.2:
|
| 600 |
+
# for i in range(3):
|
| 601 |
+
# img[:, :, i] = cv2.equalizeHist(img[:, :, i])
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
def load_mosaic(self, index):
|
| 605 |
+
# loads images in a mosaic
|
| 606 |
+
|
| 607 |
+
labels4 = []
|
| 608 |
+
s = self.img_size
|
| 609 |
+
yc, xc = s, s # mosaic center x, y
|
| 610 |
+
indices = [index] + [random.randint(0, len(self.labels) - 1) for _ in range(3)] # 3 additional image indices
|
| 611 |
+
for i, index in enumerate(indices):
|
| 612 |
+
# Load image
|
| 613 |
+
img, _, (h, w) = load_image(self, index)
|
| 614 |
+
|
| 615 |
+
# place img in img4
|
| 616 |
+
if i == 0: # top left
|
| 617 |
+
img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
|
| 618 |
+
x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)
|
| 619 |
+
x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)
|
| 620 |
+
elif i == 1: # top right
|
| 621 |
+
x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc
|
| 622 |
+
x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
|
| 623 |
+
elif i == 2: # bottom left
|
| 624 |
+
x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)
|
| 625 |
+
x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, max(xc, w), min(y2a - y1a, h)
|
| 626 |
+
elif i == 3: # bottom right
|
| 627 |
+
x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)
|
| 628 |
+
x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)
|
| 629 |
+
|
| 630 |
+
img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
|
| 631 |
+
padw = x1a - x1b
|
| 632 |
+
padh = y1a - y1b
|
| 633 |
+
|
| 634 |
+
# Labels
|
| 635 |
+
x = self.labels[index]
|
| 636 |
+
labels = x.copy()
|
| 637 |
+
if x.size > 0: # Normalized xywh to pixel xyxy format
|
| 638 |
+
labels[:, 1] = w * (x[:, 1] - x[:, 3] / 2) + padw
|
| 639 |
+
labels[:, 2] = h * (x[:, 2] - x[:, 4] / 2) + padh
|
| 640 |
+
labels[:, 3] = w * (x[:, 1] + x[:, 3] / 2) + padw
|
| 641 |
+
labels[:, 4] = h * (x[:, 2] + x[:, 4] / 2) + padh
|
| 642 |
+
labels4.append(labels)
|
| 643 |
+
|
| 644 |
+
# Concat/clip labels
|
| 645 |
+
if len(labels4):
|
| 646 |
+
labels4 = np.concatenate(labels4, 0)
|
| 647 |
+
# np.clip(labels4[:, 1:] - s / 2, 0, s, out=labels4[:, 1:]) # use with center crop
|
| 648 |
+
np.clip(labels4[:, 1:], 0, 2 * s, out=labels4[:, 1:]) # use with random_affine
|
| 649 |
+
|
| 650 |
+
# Replicate
|
| 651 |
+
# img4, labels4 = replicate(img4, labels4)
|
| 652 |
+
|
| 653 |
+
# Augment
|
| 654 |
+
# img4 = img4[s // 2: int(s * 1.5), s // 2:int(s * 1.5)] # center crop (WARNING, requires box pruning)
|
| 655 |
+
img4, labels4 = random_perspective(img4, labels4,
|
| 656 |
+
degrees=self.hyp['degrees'],
|
| 657 |
+
translate=self.hyp['translate'],
|
| 658 |
+
scale=self.hyp['scale'],
|
| 659 |
+
shear=self.hyp['shear'],
|
| 660 |
+
perspective=self.hyp['perspective'],
|
| 661 |
+
border=self.mosaic_border) # border to remove
|
| 662 |
+
|
| 663 |
+
return img4, labels4
|
| 664 |
+
|
| 665 |
+
|
| 666 |
+
def replicate(img, labels):
|
| 667 |
+
# Replicate labels
|
| 668 |
+
h, w = img.shape[:2]
|
| 669 |
+
boxes = labels[:, 1:].astype(int)
|
| 670 |
+
x1, y1, x2, y2 = boxes.T
|
| 671 |
+
s = ((x2 - x1) + (y2 - y1)) / 2 # side length (pixels)
|
| 672 |
+
for i in s.argsort()[:round(s.size * 0.5)]: # smallest indices
|
| 673 |
+
x1b, y1b, x2b, y2b = boxes[i]
|
| 674 |
+
bh, bw = y2b - y1b, x2b - x1b
|
| 675 |
+
yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw)) # offset x, y
|
| 676 |
+
x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh]
|
| 677 |
+
img[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
|
| 678 |
+
labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0)
|
| 679 |
+
|
| 680 |
+
return img, labels
|
| 681 |
+
|
| 682 |
+
|
| 683 |
+
def letterbox(img, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True):
|
| 684 |
+
# Resize image to a 32-pixel-multiple rectangle https://github.com/ultralytics/yolov3/issues/232
|
| 685 |
+
shape = img.shape[:2] # current shape [height, width]
|
| 686 |
+
if isinstance(new_shape, int):
|
| 687 |
+
new_shape = (new_shape, new_shape)
|
| 688 |
+
|
| 689 |
+
# Scale ratio (new / old)
|
| 690 |
+
r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
|
| 691 |
+
if not scaleup: # only scale down, do not scale up (for better test mAP)
|
| 692 |
+
r = min(r, 1.0)
|
| 693 |
+
|
| 694 |
+
# Compute padding
|
| 695 |
+
ratio = r, r # width, height ratios
|
| 696 |
+
new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
|
| 697 |
+
dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
|
| 698 |
+
if auto: # minimum rectangle
|
| 699 |
+
dw, dh = np.mod(dw, 64), np.mod(dh, 64) # wh padding
|
| 700 |
+
elif scaleFill: # stretch
|
| 701 |
+
dw, dh = 0.0, 0.0
|
| 702 |
+
new_unpad = (new_shape[1], new_shape[0])
|
| 703 |
+
ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios
|
| 704 |
+
|
| 705 |
+
dw /= 2 # divide padding into 2 sides
|
| 706 |
+
dh /= 2
|
| 707 |
+
|
| 708 |
+
if shape[::-1] != new_unpad: # resize
|
| 709 |
+
img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)
|
| 710 |
+
top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
|
| 711 |
+
left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
|
| 712 |
+
img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border
|
| 713 |
+
return img, ratio, (dw, dh)
|
| 714 |
+
|
| 715 |
+
|
| 716 |
+
def random_perspective(img, targets=(), degrees=10, translate=.1, scale=.1, shear=10, perspective=0.0, border=(0, 0)):
|
| 717 |
+
# torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10))
|
| 718 |
+
# targets = [cls, xyxy]
|
| 719 |
+
|
| 720 |
+
height = img.shape[0] + border[0] * 2 # shape(h,w,c)
|
| 721 |
+
width = img.shape[1] + border[1] * 2
|
| 722 |
+
|
| 723 |
+
# Center
|
| 724 |
+
C = np.eye(3)
|
| 725 |
+
C[0, 2] = -img.shape[1] / 2 # x translation (pixels)
|
| 726 |
+
C[1, 2] = -img.shape[0] / 2 # y translation (pixels)
|
| 727 |
+
|
| 728 |
+
# Perspective
|
| 729 |
+
P = np.eye(3)
|
| 730 |
+
P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y)
|
| 731 |
+
P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x)
|
| 732 |
+
|
| 733 |
+
# Rotation and Scale
|
| 734 |
+
R = np.eye(3)
|
| 735 |
+
a = random.uniform(-degrees, degrees)
|
| 736 |
+
# a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations
|
| 737 |
+
s = random.uniform(1 - scale, 1 + scale)
|
| 738 |
+
# s = 2 ** random.uniform(-scale, scale)
|
| 739 |
+
R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
|
| 740 |
+
|
| 741 |
+
# Shear
|
| 742 |
+
S = np.eye(3)
|
| 743 |
+
S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg)
|
| 744 |
+
S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg)
|
| 745 |
+
|
| 746 |
+
# Translation
|
| 747 |
+
T = np.eye(3)
|
| 748 |
+
T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels)
|
| 749 |
+
T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels)
|
| 750 |
+
|
| 751 |
+
# Combined rotation matrix
|
| 752 |
+
M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT
|
| 753 |
+
if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed
|
| 754 |
+
if perspective:
|
| 755 |
+
img = cv2.warpPerspective(img, M, dsize=(width, height), borderValue=(114, 114, 114))
|
| 756 |
+
else: # affine
|
| 757 |
+
img = cv2.warpAffine(img, M[:2], dsize=(width, height), borderValue=(114, 114, 114))
|
| 758 |
+
|
| 759 |
+
# Visualize
|
| 760 |
+
# import matplotlib.pyplot as plt
|
| 761 |
+
# ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()
|
| 762 |
+
# ax[0].imshow(img[:, :, ::-1]) # base
|
| 763 |
+
# ax[1].imshow(img2[:, :, ::-1]) # warped
|
| 764 |
+
|
| 765 |
+
# Transform label coordinates
|
| 766 |
+
n = len(targets)
|
| 767 |
+
if n:
|
| 768 |
+
# warp points
|
| 769 |
+
xy = np.ones((n * 4, 3))
|
| 770 |
+
xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1
|
| 771 |
+
xy = xy @ M.T # transform
|
| 772 |
+
if perspective:
|
| 773 |
+
xy = (xy[:, :2] / xy[:, 2:3]).reshape(n, 8) # rescale
|
| 774 |
+
else: # affine
|
| 775 |
+
xy = xy[:, :2].reshape(n, 8)
|
| 776 |
+
|
| 777 |
+
# create new boxes
|
| 778 |
+
x = xy[:, [0, 2, 4, 6]]
|
| 779 |
+
y = xy[:, [1, 3, 5, 7]]
|
| 780 |
+
xy = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T
|
| 781 |
+
|
| 782 |
+
# # apply angle-based reduction of bounding boxes
|
| 783 |
+
# radians = a * math.pi / 180
|
| 784 |
+
# reduction = max(abs(math.sin(radians)), abs(math.cos(radians))) ** 0.5
|
| 785 |
+
# x = (xy[:, 2] + xy[:, 0]) / 2
|
| 786 |
+
# y = (xy[:, 3] + xy[:, 1]) / 2
|
| 787 |
+
# w = (xy[:, 2] - xy[:, 0]) * reduction
|
| 788 |
+
# h = (xy[:, 3] - xy[:, 1]) * reduction
|
| 789 |
+
# xy = np.concatenate((x - w / 2, y - h / 2, x + w / 2, y + h / 2)).reshape(4, n).T
|
| 790 |
+
|
| 791 |
+
# clip boxes
|
| 792 |
+
xy[:, [0, 2]] = xy[:, [0, 2]].clip(0, width)
|
| 793 |
+
xy[:, [1, 3]] = xy[:, [1, 3]].clip(0, height)
|
| 794 |
+
|
| 795 |
+
# filter candidates
|
| 796 |
+
i = box_candidates(box1=targets[:, 1:5].T * s, box2=xy.T)
|
| 797 |
+
targets = targets[i]
|
| 798 |
+
targets[:, 1:5] = xy[i]
|
| 799 |
+
|
| 800 |
+
return img, targets
|
| 801 |
+
|
| 802 |
+
|
| 803 |
+
def box_candidates(box1, box2, wh_thr=2, ar_thr=20, area_thr=0.2): # box1(4,n), box2(4,n)
|
| 804 |
+
# Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio
|
| 805 |
+
w1, h1 = box1[2] - box1[0], box1[3] - box1[1]
|
| 806 |
+
w2, h2 = box2[2] - box2[0], box2[3] - box2[1]
|
| 807 |
+
ar = np.maximum(w2 / (h2 + 1e-16), h2 / (w2 + 1e-16)) # aspect ratio
|
| 808 |
+
return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + 1e-16) > area_thr) & (ar < ar_thr) # candidates
|
| 809 |
+
|
| 810 |
+
|
| 811 |
+
def cutout(image, labels):
|
| 812 |
+
# Applies image cutout augmentation https://arxiv.org/abs/1708.04552
|
| 813 |
+
h, w = image.shape[:2]
|
| 814 |
+
|
| 815 |
+
def bbox_ioa(box1, box2):
|
| 816 |
+
# Returns the intersection over box2 area given box1, box2. box1 is 4, box2 is nx4. boxes are x1y1x2y2
|
| 817 |
+
box2 = box2.transpose()
|
| 818 |
+
|
| 819 |
+
# Get the coordinates of bounding boxes
|
| 820 |
+
b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]
|
| 821 |
+
b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]
|
| 822 |
+
|
| 823 |
+
# Intersection area
|
| 824 |
+
inter_area = (np.minimum(b1_x2, b2_x2) - np.maximum(b1_x1, b2_x1)).clip(0) * \
|
| 825 |
+
(np.minimum(b1_y2, b2_y2) - np.maximum(b1_y1, b2_y1)).clip(0)
|
| 826 |
+
|
| 827 |
+
# box2 area
|
| 828 |
+
box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + 1e-16
|
| 829 |
+
|
| 830 |
+
# Intersection over box2 area
|
| 831 |
+
return inter_area / box2_area
|
| 832 |
+
|
| 833 |
+
# create random masks
|
| 834 |
+
scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction
|
| 835 |
+
for s in scales:
|
| 836 |
+
mask_h = random.randint(1, int(h * s))
|
| 837 |
+
mask_w = random.randint(1, int(w * s))
|
| 838 |
+
|
| 839 |
+
# box
|
| 840 |
+
xmin = max(0, random.randint(0, w) - mask_w // 2)
|
| 841 |
+
ymin = max(0, random.randint(0, h) - mask_h // 2)
|
| 842 |
+
xmax = min(w, xmin + mask_w)
|
| 843 |
+
ymax = min(h, ymin + mask_h)
|
| 844 |
+
|
| 845 |
+
# apply random color mask
|
| 846 |
+
image[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)]
|
| 847 |
+
|
| 848 |
+
# return unobscured labels
|
| 849 |
+
if len(labels) and s > 0.03:
|
| 850 |
+
box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32)
|
| 851 |
+
ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
|
| 852 |
+
labels = labels[ioa < 0.60] # remove >60% obscured labels
|
| 853 |
+
|
| 854 |
+
return labels
|
| 855 |
+
|
| 856 |
+
|
| 857 |
+
def reduce_img_size(path='path/images', img_size=1024): # from utils.datasets import *; reduce_img_size()
|
| 858 |
+
# creates a new ./images_reduced folder with reduced size images of maximum size img_size
|
| 859 |
+
path_new = path + '_reduced' # reduced images path
|
| 860 |
+
create_folder(path_new)
|
| 861 |
+
for f in tqdm(glob.glob('%s/*.*' % path)):
|
| 862 |
+
try:
|
| 863 |
+
img = cv2.imread(f)
|
| 864 |
+
h, w = img.shape[:2]
|
| 865 |
+
r = img_size / max(h, w) # size ratio
|
| 866 |
+
if r < 1.0:
|
| 867 |
+
img = cv2.resize(img, (int(w * r), int(h * r)), interpolation=cv2.INTER_AREA) # _LINEAR fastest
|
| 868 |
+
fnew = f.replace(path, path_new) # .replace(Path(f).suffix, '.jpg')
|
| 869 |
+
cv2.imwrite(fnew, img)
|
| 870 |
+
except:
|
| 871 |
+
print('WARNING: image failure %s' % f)
|
| 872 |
+
|
| 873 |
+
|
| 874 |
+
def recursive_dataset2bmp(dataset='path/dataset_bmp'): # from utils.datasets import *; recursive_dataset2bmp()
|
| 875 |
+
# Converts dataset to bmp (for faster training)
|
| 876 |
+
formats = [x.lower() for x in img_formats] + [x.upper() for x in img_formats]
|
| 877 |
+
for a, b, files in os.walk(dataset):
|
| 878 |
+
for file in tqdm(files, desc=a):
|
| 879 |
+
p = a + '/' + file
|
| 880 |
+
s = Path(file).suffix
|
| 881 |
+
if s == '.txt': # replace text
|
| 882 |
+
with open(p, 'r') as f:
|
| 883 |
+
lines = f.read()
|
| 884 |
+
for f in formats:
|
| 885 |
+
lines = lines.replace(f, '.bmp')
|
| 886 |
+
with open(p, 'w') as f:
|
| 887 |
+
f.write(lines)
|
| 888 |
+
elif s in formats: # replace image
|
| 889 |
+
cv2.imwrite(p.replace(s, '.bmp'), cv2.imread(p))
|
| 890 |
+
if s != '.bmp':
|
| 891 |
+
os.system("rm '%s'" % p)
|
| 892 |
+
|
| 893 |
+
|
| 894 |
+
def imagelist2folder(path='path/images.txt'): # from utils.datasets import *; imagelist2folder()
|
| 895 |
+
# Copies all the images in a text file (list of images) into a folder
|
| 896 |
+
create_folder(path[:-4])
|
| 897 |
+
with open(path, 'r') as f:
|
| 898 |
+
for line in f.read().splitlines():
|
| 899 |
+
os.system('cp "%s" %s' % (line, path[:-4]))
|
| 900 |
+
print(line)
|
| 901 |
+
|
| 902 |
+
|
| 903 |
+
def create_folder(path='./new'):
|
| 904 |
+
# Create folder
|
| 905 |
+
if os.path.exists(path):
|
| 906 |
+
shutil.rmtree(path) # delete output folder
|
| 907 |
+
os.makedirs(path) # make new output folder
|
yolov5_anime/utils/general.py
ADDED
|
@@ -0,0 +1,1284 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import glob
|
| 2 |
+
import math
|
| 3 |
+
import os
|
| 4 |
+
import random
|
| 5 |
+
import shutil
|
| 6 |
+
import subprocess
|
| 7 |
+
import time
|
| 8 |
+
from contextlib import contextmanager
|
| 9 |
+
from copy import copy
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from sys import platform
|
| 12 |
+
|
| 13 |
+
import cv2
|
| 14 |
+
import matplotlib
|
| 15 |
+
import matplotlib.pyplot as plt
|
| 16 |
+
import numpy as np
|
| 17 |
+
import torch
|
| 18 |
+
import torch.nn as nn
|
| 19 |
+
import torchvision
|
| 20 |
+
import yaml
|
| 21 |
+
|
| 22 |
+
# SciPy is optional for inference. Some helper functions (e.g. kmeans anchors, signal filtering)
|
| 23 |
+
# use SciPy, but face detection + NMS do not. On some environments SciPy may be installed but
|
| 24 |
+
# incompatible with the installed NumPy (e.g. missing `numpy.exceptions`), so we guard imports.
|
| 25 |
+
_SCIPY_IMPORT_ERROR = None
|
| 26 |
+
try:
|
| 27 |
+
from scipy.cluster.vq import kmeans # type: ignore
|
| 28 |
+
from scipy.signal import butter, filtfilt # type: ignore
|
| 29 |
+
except Exception as _e: # noqa: BLE001
|
| 30 |
+
kmeans = None
|
| 31 |
+
butter = None
|
| 32 |
+
filtfilt = None
|
| 33 |
+
_SCIPY_IMPORT_ERROR = str(_e)
|
| 34 |
+
from tqdm import tqdm
|
| 35 |
+
|
| 36 |
+
from utils.torch_utils import init_seeds, is_parallel
|
| 37 |
+
|
| 38 |
+
# Set printoptions
|
| 39 |
+
torch.set_printoptions(linewidth=320, precision=5, profile='long')
|
| 40 |
+
np.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format}) # format short g, %precision=5
|
| 41 |
+
matplotlib.rc('font', **{'size': 11})
|
| 42 |
+
|
| 43 |
+
# Prevent OpenCV from multithreading (to use PyTorch DataLoader)
|
| 44 |
+
cv2.setNumThreads(0)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@contextmanager
|
| 48 |
+
def torch_distributed_zero_first(local_rank: int):
|
| 49 |
+
"""
|
| 50 |
+
Decorator to make all processes in distributed training wait for each local_master to do something.
|
| 51 |
+
"""
|
| 52 |
+
if local_rank not in [-1, 0]:
|
| 53 |
+
torch.distributed.barrier()
|
| 54 |
+
yield
|
| 55 |
+
if local_rank == 0:
|
| 56 |
+
torch.distributed.barrier()
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def init_seeds(seed=0):
|
| 60 |
+
random.seed(seed)
|
| 61 |
+
np.random.seed(seed)
|
| 62 |
+
init_seeds(seed=seed)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def get_latest_run(search_dir='./runs'):
|
| 66 |
+
# Return path to most recent 'last.pt' in /runs (i.e. to --resume from)
|
| 67 |
+
last_list = glob.glob(f'{search_dir}/**/last*.pt', recursive=True)
|
| 68 |
+
return max(last_list, key=os.path.getctime)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def check_git_status():
|
| 72 |
+
# Suggest 'git pull' if repo is out of date
|
| 73 |
+
if platform in ['linux', 'darwin'] and not os.path.isfile('/.dockerenv'):
|
| 74 |
+
s = subprocess.check_output('if [ -d .git ]; then git fetch && git status -uno; fi', shell=True).decode('utf-8')
|
| 75 |
+
if 'Your branch is behind' in s:
|
| 76 |
+
print(s[s.find('Your branch is behind'):s.find('\n\n')] + '\n')
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def check_img_size(img_size, s=32):
|
| 80 |
+
# Verify img_size is a multiple of stride s
|
| 81 |
+
new_size = make_divisible(img_size, int(s)) # ceil gs-multiple
|
| 82 |
+
if new_size != img_size:
|
| 83 |
+
print('WARNING: --img-size %g must be multiple of max stride %g, updating to %g' % (img_size, s, new_size))
|
| 84 |
+
return new_size
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def check_anchors(dataset, model, thr=4.0, imgsz=640):
|
| 88 |
+
# Check anchor fit to data, recompute if necessary
|
| 89 |
+
print('\nAnalyzing anchors... ', end='')
|
| 90 |
+
m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect()
|
| 91 |
+
shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)
|
| 92 |
+
scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale
|
| 93 |
+
wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh
|
| 94 |
+
|
| 95 |
+
def metric(k): # compute metric
|
| 96 |
+
r = wh[:, None] / k[None]
|
| 97 |
+
x = torch.min(r, 1. / r).min(2)[0] # ratio metric
|
| 98 |
+
best = x.max(1)[0] # best_x
|
| 99 |
+
aat = (x > 1. / thr).float().sum(1).mean() # anchors above threshold
|
| 100 |
+
bpr = (best > 1. / thr).float().mean() # best possible recall
|
| 101 |
+
return bpr, aat
|
| 102 |
+
|
| 103 |
+
bpr, aat = metric(m.anchor_grid.clone().cpu().view(-1, 2))
|
| 104 |
+
print('anchors/target = %.2f, Best Possible Recall (BPR) = %.4f' % (aat, bpr), end='')
|
| 105 |
+
if bpr < 0.98: # threshold to recompute
|
| 106 |
+
print('. Attempting to generate improved anchors, please wait...' % bpr)
|
| 107 |
+
na = m.anchor_grid.numel() // 2 # number of anchors
|
| 108 |
+
new_anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False)
|
| 109 |
+
new_bpr = metric(new_anchors.reshape(-1, 2))[0]
|
| 110 |
+
if new_bpr > bpr: # replace anchors
|
| 111 |
+
new_anchors = torch.tensor(new_anchors, device=m.anchors.device).type_as(m.anchors)
|
| 112 |
+
m.anchor_grid[:] = new_anchors.clone().view_as(m.anchor_grid) # for inference
|
| 113 |
+
m.anchors[:] = new_anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1) # loss
|
| 114 |
+
check_anchor_order(m)
|
| 115 |
+
print('New anchors saved to model. Update model *.yaml to use these anchors in the future.')
|
| 116 |
+
else:
|
| 117 |
+
print('Original anchors better than new anchors. Proceeding with original anchors.')
|
| 118 |
+
print('') # newline
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def check_anchor_order(m):
|
| 122 |
+
# Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary
|
| 123 |
+
a = m.anchor_grid.prod(-1).view(-1) # anchor area
|
| 124 |
+
da = a[-1] - a[0] # delta a
|
| 125 |
+
ds = m.stride[-1] - m.stride[0] # delta s
|
| 126 |
+
if da.sign() != ds.sign(): # same order
|
| 127 |
+
print('Reversing anchor order')
|
| 128 |
+
m.anchors[:] = m.anchors.flip(0)
|
| 129 |
+
m.anchor_grid[:] = m.anchor_grid.flip(0)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def check_file(file):
|
| 133 |
+
# Searches for file if not found locally
|
| 134 |
+
if os.path.isfile(file) or file == '':
|
| 135 |
+
return file
|
| 136 |
+
else:
|
| 137 |
+
files = glob.glob('./**/' + file, recursive=True) # find file
|
| 138 |
+
assert len(files), 'File Not Found: %s' % file # assert file was found
|
| 139 |
+
return files[0] # return first file if multiple found
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def check_dataset(dict):
|
| 143 |
+
# Download dataset if not found
|
| 144 |
+
train, val = os.path.abspath(dict['train']), os.path.abspath(dict['val']) # data paths
|
| 145 |
+
if not (os.path.exists(train) and os.path.exists(val)):
|
| 146 |
+
print('\nWARNING: Dataset not found, nonexistant paths: %s' % [train, val])
|
| 147 |
+
if 'download' in dict:
|
| 148 |
+
s = dict['download']
|
| 149 |
+
print('Attempting autodownload from: %s' % s)
|
| 150 |
+
if s.startswith('http') and s.endswith('.zip'): # URL
|
| 151 |
+
f = Path(s).name # filename
|
| 152 |
+
torch.hub.download_url_to_file(s, f)
|
| 153 |
+
r = os.system('unzip -q %s -d ../ && rm %s' % (f, f))
|
| 154 |
+
else: # bash script
|
| 155 |
+
r = os.system(s)
|
| 156 |
+
print('Dataset autodownload %s\n' % ('success' if r == 0 else 'failure')) # analyze return value
|
| 157 |
+
else:
|
| 158 |
+
Exception('Dataset autodownload unavailable.')
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def make_divisible(x, divisor):
|
| 162 |
+
# Returns x evenly divisble by divisor
|
| 163 |
+
return math.ceil(x / divisor) * divisor
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def labels_to_class_weights(labels, nc=80):
|
| 167 |
+
# Get class weights (inverse frequency) from training labels
|
| 168 |
+
if labels[0] is None: # no labels loaded
|
| 169 |
+
return torch.Tensor()
|
| 170 |
+
|
| 171 |
+
labels = np.concatenate(labels, 0) # labels.shape = (866643, 5) for COCO
|
| 172 |
+
classes = labels[:, 0].astype(np.int) # labels = [class xywh]
|
| 173 |
+
weights = np.bincount(classes, minlength=nc) # occurences per class
|
| 174 |
+
|
| 175 |
+
# Prepend gridpoint count (for uCE trianing)
|
| 176 |
+
# gpi = ((320 / 32 * np.array([1, 2, 4])) ** 2 * 3).sum() # gridpoints per image
|
| 177 |
+
# weights = np.hstack([gpi * len(labels) - weights.sum() * 9, weights * 9]) ** 0.5 # prepend gridpoints to start
|
| 178 |
+
|
| 179 |
+
weights[weights == 0] = 1 # replace empty bins with 1
|
| 180 |
+
weights = 1 / weights # number of targets per class
|
| 181 |
+
weights /= weights.sum() # normalize
|
| 182 |
+
return torch.from_numpy(weights)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def labels_to_image_weights(labels, nc=80, class_weights=np.ones(80)):
|
| 186 |
+
# Produces image weights based on class mAPs
|
| 187 |
+
n = len(labels)
|
| 188 |
+
class_counts = np.array([np.bincount(labels[i][:, 0].astype(np.int), minlength=nc) for i in range(n)])
|
| 189 |
+
image_weights = (class_weights.reshape(1, nc) * class_counts).sum(1)
|
| 190 |
+
# index = random.choices(range(n), weights=image_weights, k=1) # weight image sample
|
| 191 |
+
return image_weights
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def coco80_to_coco91_class(): # converts 80-index (val2014) to 91-index (paper)
|
| 195 |
+
# https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/
|
| 196 |
+
# a = np.loadtxt('data/coco.names', dtype='str', delimiter='\n')
|
| 197 |
+
# b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='\n')
|
| 198 |
+
# x1 = [list(a[i] == b).index(True) + 1 for i in range(80)] # darknet to coco
|
| 199 |
+
# x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)] # coco to darknet
|
| 200 |
+
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34,
|
| 201 |
+
35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
|
| 202 |
+
64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90]
|
| 203 |
+
return x
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def xyxy2xywh(x):
|
| 207 |
+
# Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right
|
| 208 |
+
y = torch.zeros_like(x) if isinstance(x, torch.Tensor) else np.zeros_like(x)
|
| 209 |
+
y[:, 0] = (x[:, 0] + x[:, 2]) / 2 # x center
|
| 210 |
+
y[:, 1] = (x[:, 1] + x[:, 3]) / 2 # y center
|
| 211 |
+
y[:, 2] = x[:, 2] - x[:, 0] # width
|
| 212 |
+
y[:, 3] = x[:, 3] - x[:, 1] # height
|
| 213 |
+
return y
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def xywh2xyxy(x):
|
| 217 |
+
# Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
|
| 218 |
+
y = torch.zeros_like(x) if isinstance(x, torch.Tensor) else np.zeros_like(x)
|
| 219 |
+
y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x
|
| 220 |
+
y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y
|
| 221 |
+
y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x
|
| 222 |
+
y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y
|
| 223 |
+
return y
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None):
|
| 227 |
+
# Rescale coords (xyxy) from img1_shape to img0_shape
|
| 228 |
+
if ratio_pad is None: # calculate from img0_shape
|
| 229 |
+
gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new
|
| 230 |
+
pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding
|
| 231 |
+
else:
|
| 232 |
+
gain = ratio_pad[0][0]
|
| 233 |
+
pad = ratio_pad[1]
|
| 234 |
+
|
| 235 |
+
coords[:, [0, 2]] -= pad[0] # x padding
|
| 236 |
+
coords[:, [1, 3]] -= pad[1] # y padding
|
| 237 |
+
coords[:, :4] /= gain
|
| 238 |
+
clip_coords(coords, img0_shape)
|
| 239 |
+
return coords
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def clip_coords(boxes, img_shape):
|
| 243 |
+
# Clip bounding xyxy bounding boxes to image shape (height, width)
|
| 244 |
+
boxes[:, 0].clamp_(0, img_shape[1]) # x1
|
| 245 |
+
boxes[:, 1].clamp_(0, img_shape[0]) # y1
|
| 246 |
+
boxes[:, 2].clamp_(0, img_shape[1]) # x2
|
| 247 |
+
boxes[:, 3].clamp_(0, img_shape[0]) # y2
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def ap_per_class(tp, conf, pred_cls, target_cls):
|
| 251 |
+
""" Compute the average precision, given the recall and precision curves.
|
| 252 |
+
Source: https://github.com/rafaelpadilla/Object-Detection-Metrics.
|
| 253 |
+
# Arguments
|
| 254 |
+
tp: True positives (nparray, nx1 or nx10).
|
| 255 |
+
conf: Objectness value from 0-1 (nparray).
|
| 256 |
+
pred_cls: Predicted object classes (nparray).
|
| 257 |
+
target_cls: True object classes (nparray).
|
| 258 |
+
# Returns
|
| 259 |
+
The average precision as computed in py-faster-rcnn.
|
| 260 |
+
"""
|
| 261 |
+
|
| 262 |
+
# Sort by objectness
|
| 263 |
+
i = np.argsort(-conf)
|
| 264 |
+
tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
|
| 265 |
+
|
| 266 |
+
# Find unique classes
|
| 267 |
+
unique_classes = np.unique(target_cls)
|
| 268 |
+
|
| 269 |
+
# Create Precision-Recall curve and compute AP for each class
|
| 270 |
+
pr_score = 0.1 # score to evaluate P and R https://github.com/ultralytics/yolov3/issues/898
|
| 271 |
+
s = [unique_classes.shape[0], tp.shape[1]] # number class, number iou thresholds (i.e. 10 for mAP0.5...0.95)
|
| 272 |
+
ap, p, r = np.zeros(s), np.zeros(s), np.zeros(s)
|
| 273 |
+
for ci, c in enumerate(unique_classes):
|
| 274 |
+
i = pred_cls == c
|
| 275 |
+
n_gt = (target_cls == c).sum() # Number of ground truth objects
|
| 276 |
+
n_p = i.sum() # Number of predicted objects
|
| 277 |
+
|
| 278 |
+
if n_p == 0 or n_gt == 0:
|
| 279 |
+
continue
|
| 280 |
+
else:
|
| 281 |
+
# Accumulate FPs and TPs
|
| 282 |
+
fpc = (1 - tp[i]).cumsum(0)
|
| 283 |
+
tpc = tp[i].cumsum(0)
|
| 284 |
+
|
| 285 |
+
# Recall
|
| 286 |
+
recall = tpc / (n_gt + 1e-16) # recall curve
|
| 287 |
+
r[ci] = np.interp(-pr_score, -conf[i], recall[:, 0]) # r at pr_score, negative x, xp because xp decreases
|
| 288 |
+
|
| 289 |
+
# Precision
|
| 290 |
+
precision = tpc / (tpc + fpc) # precision curve
|
| 291 |
+
p[ci] = np.interp(-pr_score, -conf[i], precision[:, 0]) # p at pr_score
|
| 292 |
+
|
| 293 |
+
# AP from recall-precision curve
|
| 294 |
+
for j in range(tp.shape[1]):
|
| 295 |
+
ap[ci, j] = compute_ap(recall[:, j], precision[:, j])
|
| 296 |
+
|
| 297 |
+
# Plot
|
| 298 |
+
# fig, ax = plt.subplots(1, 1, figsize=(5, 5))
|
| 299 |
+
# ax.plot(recall, precision)
|
| 300 |
+
# ax.set_xlabel('Recall')
|
| 301 |
+
# ax.set_ylabel('Precision')
|
| 302 |
+
# ax.set_xlim(0, 1.01)
|
| 303 |
+
# ax.set_ylim(0, 1.01)
|
| 304 |
+
# fig.tight_layout()
|
| 305 |
+
# fig.savefig('PR_curve.png', dpi=300)
|
| 306 |
+
|
| 307 |
+
# Compute F1 score (harmonic mean of precision and recall)
|
| 308 |
+
f1 = 2 * p * r / (p + r + 1e-16)
|
| 309 |
+
|
| 310 |
+
return p, r, ap, f1, unique_classes.astype('int32')
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def compute_ap(recall, precision):
|
| 314 |
+
""" Compute the average precision, given the recall and precision curves.
|
| 315 |
+
Source: https://github.com/rbgirshick/py-faster-rcnn.
|
| 316 |
+
# Arguments
|
| 317 |
+
recall: The recall curve (list).
|
| 318 |
+
precision: The precision curve (list).
|
| 319 |
+
# Returns
|
| 320 |
+
The average precision as computed in py-faster-rcnn.
|
| 321 |
+
"""
|
| 322 |
+
|
| 323 |
+
# Append sentinel values to beginning and end
|
| 324 |
+
mrec = np.concatenate(([0.], recall, [min(recall[-1] + 1E-3, 1.)]))
|
| 325 |
+
mpre = np.concatenate(([0.], precision, [0.]))
|
| 326 |
+
|
| 327 |
+
# Compute the precision envelope
|
| 328 |
+
mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))
|
| 329 |
+
|
| 330 |
+
# Integrate area under curve
|
| 331 |
+
method = 'interp' # methods: 'continuous', 'interp'
|
| 332 |
+
if method == 'interp':
|
| 333 |
+
x = np.linspace(0, 1, 101) # 101-point interp (COCO)
|
| 334 |
+
ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate
|
| 335 |
+
else: # 'continuous'
|
| 336 |
+
i = np.where(mrec[1:] != mrec[:-1])[0] # points where x axis (recall) changes
|
| 337 |
+
ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve
|
| 338 |
+
|
| 339 |
+
return ap
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def bbox_iou(box1, box2, x1y1x2y2=True, GIoU=False, DIoU=False, CIoU=False):
|
| 343 |
+
# Returns the IoU of box1 to box2. box1 is 4, box2 is nx4
|
| 344 |
+
box2 = box2.T
|
| 345 |
+
|
| 346 |
+
# Get the coordinates of bounding boxes
|
| 347 |
+
if x1y1x2y2: # x1, y1, x2, y2 = box1
|
| 348 |
+
b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]
|
| 349 |
+
b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]
|
| 350 |
+
else: # transform from xywh to xyxy
|
| 351 |
+
b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2
|
| 352 |
+
b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2
|
| 353 |
+
b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2
|
| 354 |
+
b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2
|
| 355 |
+
|
| 356 |
+
# Intersection area
|
| 357 |
+
inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \
|
| 358 |
+
(torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0)
|
| 359 |
+
|
| 360 |
+
# Union Area
|
| 361 |
+
w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1
|
| 362 |
+
w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1
|
| 363 |
+
union = (w1 * h1 + 1e-16) + w2 * h2 - inter
|
| 364 |
+
|
| 365 |
+
iou = inter / union # iou
|
| 366 |
+
if GIoU or DIoU or CIoU:
|
| 367 |
+
cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex (smallest enclosing box) width
|
| 368 |
+
ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height
|
| 369 |
+
if GIoU: # Generalized IoU https://arxiv.org/pdf/1902.09630.pdf
|
| 370 |
+
c_area = cw * ch + 1e-16 # convex area
|
| 371 |
+
return iou - (c_area - union) / c_area # GIoU
|
| 372 |
+
if DIoU or CIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
|
| 373 |
+
# convex diagonal squared
|
| 374 |
+
c2 = cw ** 2 + ch ** 2 + 1e-16
|
| 375 |
+
# centerpoint distance squared
|
| 376 |
+
rho2 = ((b2_x1 + b2_x2) - (b1_x1 + b1_x2)) ** 2 / 4 + ((b2_y1 + b2_y2) - (b1_y1 + b1_y2)) ** 2 / 4
|
| 377 |
+
if DIoU:
|
| 378 |
+
return iou - rho2 / c2 # DIoU
|
| 379 |
+
elif CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
|
| 380 |
+
v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2)
|
| 381 |
+
with torch.no_grad():
|
| 382 |
+
alpha = v / (1 - iou + v + 1e-16)
|
| 383 |
+
return iou - (rho2 / c2 + v * alpha) # CIoU
|
| 384 |
+
|
| 385 |
+
return iou
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
def box_iou(box1, box2):
|
| 389 |
+
# https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py
|
| 390 |
+
"""
|
| 391 |
+
Return intersection-over-union (Jaccard index) of boxes.
|
| 392 |
+
Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
|
| 393 |
+
Arguments:
|
| 394 |
+
box1 (Tensor[N, 4])
|
| 395 |
+
box2 (Tensor[M, 4])
|
| 396 |
+
Returns:
|
| 397 |
+
iou (Tensor[N, M]): the NxM matrix containing the pairwise
|
| 398 |
+
IoU values for every element in boxes1 and boxes2
|
| 399 |
+
"""
|
| 400 |
+
|
| 401 |
+
def box_area(box):
|
| 402 |
+
# box = 4xn
|
| 403 |
+
return (box[2] - box[0]) * (box[3] - box[1])
|
| 404 |
+
|
| 405 |
+
area1 = box_area(box1.T)
|
| 406 |
+
area2 = box_area(box2.T)
|
| 407 |
+
|
| 408 |
+
# inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)
|
| 409 |
+
inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2)
|
| 410 |
+
return inter / (area1[:, None] + area2 - inter) # iou = inter / (area1 + area2 - inter)
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def wh_iou(wh1, wh2):
|
| 414 |
+
# Returns the nxm IoU matrix. wh1 is nx2, wh2 is mx2
|
| 415 |
+
wh1 = wh1[:, None] # [N,1,2]
|
| 416 |
+
wh2 = wh2[None] # [1,M,2]
|
| 417 |
+
inter = torch.min(wh1, wh2).prod(2) # [N,M]
|
| 418 |
+
return inter / (wh1.prod(2) + wh2.prod(2) - inter) # iou = inter / (area1 + area2 - inter)
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
class FocalLoss(nn.Module):
|
| 422 |
+
# Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
|
| 423 |
+
def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
|
| 424 |
+
super(FocalLoss, self).__init__()
|
| 425 |
+
self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
|
| 426 |
+
self.gamma = gamma
|
| 427 |
+
self.alpha = alpha
|
| 428 |
+
self.reduction = loss_fcn.reduction
|
| 429 |
+
self.loss_fcn.reduction = 'none' # required to apply FL to each element
|
| 430 |
+
|
| 431 |
+
def forward(self, pred, true):
|
| 432 |
+
loss = self.loss_fcn(pred, true)
|
| 433 |
+
# p_t = torch.exp(-loss)
|
| 434 |
+
# loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability
|
| 435 |
+
|
| 436 |
+
# TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py
|
| 437 |
+
pred_prob = torch.sigmoid(pred) # prob from logits
|
| 438 |
+
p_t = true * pred_prob + (1 - true) * (1 - pred_prob)
|
| 439 |
+
alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
|
| 440 |
+
modulating_factor = (1.0 - p_t) ** self.gamma
|
| 441 |
+
loss *= alpha_factor * modulating_factor
|
| 442 |
+
|
| 443 |
+
if self.reduction == 'mean':
|
| 444 |
+
return loss.mean()
|
| 445 |
+
elif self.reduction == 'sum':
|
| 446 |
+
return loss.sum()
|
| 447 |
+
else: # 'none'
|
| 448 |
+
return loss
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
|
| 452 |
+
# return positive, negative label smoothing BCE targets
|
| 453 |
+
return 1.0 - 0.5 * eps, 0.5 * eps
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
class BCEBlurWithLogitsLoss(nn.Module):
|
| 457 |
+
# BCEwithLogitLoss() with reduced missing label effects.
|
| 458 |
+
def __init__(self, alpha=0.05):
|
| 459 |
+
super(BCEBlurWithLogitsLoss, self).__init__()
|
| 460 |
+
self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none') # must be nn.BCEWithLogitsLoss()
|
| 461 |
+
self.alpha = alpha
|
| 462 |
+
|
| 463 |
+
def forward(self, pred, true):
|
| 464 |
+
loss = self.loss_fcn(pred, true)
|
| 465 |
+
pred = torch.sigmoid(pred) # prob from logits
|
| 466 |
+
dx = pred - true # reduce only missing label effects
|
| 467 |
+
# dx = (pred - true).abs() # reduce missing label and false label effects
|
| 468 |
+
alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4))
|
| 469 |
+
loss *= alpha_factor
|
| 470 |
+
return loss.mean()
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def compute_loss(p, targets, model): # predictions, targets, model
|
| 474 |
+
device = targets.device
|
| 475 |
+
lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device)
|
| 476 |
+
tcls, tbox, indices, anchors = build_targets(p, targets, model) # targets
|
| 477 |
+
h = model.hyp # hyperparameters
|
| 478 |
+
|
| 479 |
+
# Define criteria
|
| 480 |
+
BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.Tensor([h['cls_pw']])).to(device)
|
| 481 |
+
BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.Tensor([h['obj_pw']])).to(device)
|
| 482 |
+
|
| 483 |
+
# Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
|
| 484 |
+
cp, cn = smooth_BCE(eps=0.0)
|
| 485 |
+
|
| 486 |
+
# Focal loss
|
| 487 |
+
g = h['fl_gamma'] # focal loss gamma
|
| 488 |
+
if g > 0:
|
| 489 |
+
BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
|
| 490 |
+
|
| 491 |
+
# Losses
|
| 492 |
+
nt = 0 # number of targets
|
| 493 |
+
np = len(p) # number of outputs
|
| 494 |
+
balance = [4.0, 1.0, 0.4] if np == 3 else [4.0, 1.0, 0.4, 0.1] # P3-5 or P3-6
|
| 495 |
+
for i, pi in enumerate(p): # layer index, layer predictions
|
| 496 |
+
b, a, gj, gi = indices[i] # image, anchor, gridy, gridx
|
| 497 |
+
tobj = torch.zeros_like(pi[..., 0], device=device) # target obj
|
| 498 |
+
|
| 499 |
+
n = b.shape[0] # number of targets
|
| 500 |
+
if n:
|
| 501 |
+
nt += n # cumulative targets
|
| 502 |
+
ps = pi[b, a, gj, gi] # prediction subset corresponding to targets
|
| 503 |
+
|
| 504 |
+
# Regression
|
| 505 |
+
pxy = ps[:, :2].sigmoid() * 2. - 0.5
|
| 506 |
+
pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i]
|
| 507 |
+
pbox = torch.cat((pxy, pwh), 1).to(device) # predicted box
|
| 508 |
+
giou = bbox_iou(pbox.T, tbox[i], x1y1x2y2=False, CIoU=True) # giou(prediction, target)
|
| 509 |
+
lbox += (1.0 - giou).mean() # giou loss
|
| 510 |
+
|
| 511 |
+
# Objectness
|
| 512 |
+
tobj[b, a, gj, gi] = (1.0 - model.gr) + model.gr * giou.detach().clamp(0).type(tobj.dtype) # giou ratio
|
| 513 |
+
|
| 514 |
+
# Classification
|
| 515 |
+
if model.nc > 1: # cls loss (only if multiple classes)
|
| 516 |
+
t = torch.full_like(ps[:, 5:], cn, device=device) # targets
|
| 517 |
+
t[range(n), tcls[i]] = cp
|
| 518 |
+
lcls += BCEcls(ps[:, 5:], t) # BCE
|
| 519 |
+
|
| 520 |
+
# Append targets to text file
|
| 521 |
+
# with open('targets.txt', 'a') as file:
|
| 522 |
+
# [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)]
|
| 523 |
+
|
| 524 |
+
lobj += BCEobj(pi[..., 4], tobj) * balance[i] # obj loss
|
| 525 |
+
|
| 526 |
+
s = 3 / np # output count scaling
|
| 527 |
+
lbox *= h['giou'] * s
|
| 528 |
+
lobj *= h['obj'] * s * (1.4 if np == 4 else 1.)
|
| 529 |
+
lcls *= h['cls'] * s
|
| 530 |
+
bs = tobj.shape[0] # batch size
|
| 531 |
+
|
| 532 |
+
loss = lbox + lobj + lcls
|
| 533 |
+
return loss * bs, torch.cat((lbox, lobj, lcls, loss)).detach()
|
| 534 |
+
|
| 535 |
+
|
| 536 |
+
def build_targets(p, targets, model):
|
| 537 |
+
# Build targets for compute_loss(), input targets(image,class,x,y,w,h)
|
| 538 |
+
det = model.module.model[-1] if is_parallel(model) else model.model[-1] # Detect() module
|
| 539 |
+
na, nt = det.na, targets.shape[0] # number of anchors, targets
|
| 540 |
+
tcls, tbox, indices, anch = [], [], [], []
|
| 541 |
+
gain = torch.ones(7, device=targets.device) # normalized to gridspace gain
|
| 542 |
+
ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)
|
| 543 |
+
targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices
|
| 544 |
+
|
| 545 |
+
g = 0.5 # bias
|
| 546 |
+
off = torch.tensor([[0, 0],
|
| 547 |
+
[1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m
|
| 548 |
+
# [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
|
| 549 |
+
], device=targets.device).float() * g # offsets
|
| 550 |
+
|
| 551 |
+
for i in range(det.nl):
|
| 552 |
+
anchors = det.anchors[i]
|
| 553 |
+
gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain
|
| 554 |
+
|
| 555 |
+
# Match targets to anchors
|
| 556 |
+
t = targets * gain
|
| 557 |
+
if nt:
|
| 558 |
+
# Matches
|
| 559 |
+
r = t[:, :, 4:6] / anchors[:, None] # wh ratio
|
| 560 |
+
j = torch.max(r, 1. / r).max(2)[0] < model.hyp['anchor_t'] # compare
|
| 561 |
+
# j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
|
| 562 |
+
t = t[j] # filter
|
| 563 |
+
|
| 564 |
+
# Offsets
|
| 565 |
+
gxy = t[:, 2:4] # grid xy
|
| 566 |
+
gxi = gain[[2, 3]] - gxy # inverse
|
| 567 |
+
j, k = ((gxy % 1. < g) & (gxy > 1.)).T
|
| 568 |
+
l, m = ((gxi % 1. < g) & (gxi > 1.)).T
|
| 569 |
+
j = torch.stack((torch.ones_like(j), j, k, l, m))
|
| 570 |
+
t = t.repeat((5, 1, 1))[j]
|
| 571 |
+
offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
|
| 572 |
+
else:
|
| 573 |
+
t = targets[0]
|
| 574 |
+
offsets = 0
|
| 575 |
+
|
| 576 |
+
# Define
|
| 577 |
+
b, c = t[:, :2].long().T # image, class
|
| 578 |
+
gxy = t[:, 2:4] # grid xy
|
| 579 |
+
gwh = t[:, 4:6] # grid wh
|
| 580 |
+
gij = (gxy - offsets).long()
|
| 581 |
+
gi, gj = gij.T # grid xy indices
|
| 582 |
+
|
| 583 |
+
# Append
|
| 584 |
+
a = t[:, 6].long() # anchor indices
|
| 585 |
+
indices.append((b, a, gj, gi)) # image, anchor, grid indices
|
| 586 |
+
tbox.append(torch.cat((gxy - gij, gwh), 1)) # box
|
| 587 |
+
anch.append(anchors[a]) # anchors
|
| 588 |
+
tcls.append(c) # class
|
| 589 |
+
|
| 590 |
+
return tcls, tbox, indices, anch
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
def non_max_suppression(prediction, conf_thres=0.1, iou_thres=0.6, merge=False, classes=None, agnostic=False):
|
| 594 |
+
"""Performs Non-Maximum Suppression (NMS) on inference results
|
| 595 |
+
|
| 596 |
+
Returns:
|
| 597 |
+
detections with shape: nx6 (x1, y1, x2, y2, conf, cls)
|
| 598 |
+
"""
|
| 599 |
+
if prediction.dtype is torch.float16:
|
| 600 |
+
prediction = prediction.float() # to FP32
|
| 601 |
+
|
| 602 |
+
nc = prediction[0].shape[1] - 5 # number of classes
|
| 603 |
+
xc = prediction[..., 4] > conf_thres # candidates
|
| 604 |
+
|
| 605 |
+
# Settings
|
| 606 |
+
min_wh, max_wh = 2, 4096 # (pixels) minimum and maximum box width and height
|
| 607 |
+
max_det = 300 # maximum number of detections per image
|
| 608 |
+
time_limit = 10.0 # seconds to quit after
|
| 609 |
+
redundant = True # require redundant detections
|
| 610 |
+
multi_label = nc > 1 # multiple labels per box (adds 0.5ms/img)
|
| 611 |
+
|
| 612 |
+
t = time.time()
|
| 613 |
+
output = [None] * prediction.shape[0]
|
| 614 |
+
for xi, x in enumerate(prediction): # image index, image inference
|
| 615 |
+
# Apply constraints
|
| 616 |
+
# x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height
|
| 617 |
+
x = x[xc[xi]] # confidence
|
| 618 |
+
|
| 619 |
+
# If none remain process next image
|
| 620 |
+
if not x.shape[0]:
|
| 621 |
+
continue
|
| 622 |
+
|
| 623 |
+
# Compute conf
|
| 624 |
+
x[:, 5:] *= x[:, 4:5] # conf = obj_conf * cls_conf
|
| 625 |
+
|
| 626 |
+
# Box (center x, center y, width, height) to (x1, y1, x2, y2)
|
| 627 |
+
box = xywh2xyxy(x[:, :4])
|
| 628 |
+
|
| 629 |
+
# Detections matrix nx6 (xyxy, conf, cls)
|
| 630 |
+
if multi_label:
|
| 631 |
+
i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T
|
| 632 |
+
x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1)
|
| 633 |
+
else: # best class only
|
| 634 |
+
conf, j = x[:, 5:].max(1, keepdim=True)
|
| 635 |
+
x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres]
|
| 636 |
+
|
| 637 |
+
# Filter by class
|
| 638 |
+
if classes:
|
| 639 |
+
x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]
|
| 640 |
+
|
| 641 |
+
# Apply finite constraint
|
| 642 |
+
# if not torch.isfinite(x).all():
|
| 643 |
+
# x = x[torch.isfinite(x).all(1)]
|
| 644 |
+
|
| 645 |
+
# If none remain process next image
|
| 646 |
+
n = x.shape[0] # number of boxes
|
| 647 |
+
if not n:
|
| 648 |
+
continue
|
| 649 |
+
|
| 650 |
+
# Sort by confidence
|
| 651 |
+
# x = x[x[:, 4].argsort(descending=True)]
|
| 652 |
+
|
| 653 |
+
# Batched NMS
|
| 654 |
+
c = x[:, 5:6] * (0 if agnostic else max_wh) # classes
|
| 655 |
+
boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores
|
| 656 |
+
i = torchvision.ops.boxes.nms(boxes, scores, iou_thres)
|
| 657 |
+
if i.shape[0] > max_det: # limit detections
|
| 658 |
+
i = i[:max_det]
|
| 659 |
+
if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean)
|
| 660 |
+
try: # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)
|
| 661 |
+
iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix
|
| 662 |
+
weights = iou * scores[None] # box weights
|
| 663 |
+
x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes
|
| 664 |
+
if redundant:
|
| 665 |
+
i = i[iou.sum(1) > 1] # require redundancy
|
| 666 |
+
except: # possible CUDA error https://github.com/ultralytics/yolov3/issues/1139
|
| 667 |
+
print(x, i, x.shape, i.shape)
|
| 668 |
+
pass
|
| 669 |
+
|
| 670 |
+
output[xi] = x[i]
|
| 671 |
+
if (time.time() - t) > time_limit:
|
| 672 |
+
break # time limit exceeded
|
| 673 |
+
|
| 674 |
+
return output
|
| 675 |
+
|
| 676 |
+
|
| 677 |
+
def strip_optimizer(f='weights/best.pt', s=''): # from utils.utils import *; strip_optimizer()
|
| 678 |
+
# Strip optimizer from 'f' to finalize training, optionally save as 's'
|
| 679 |
+
x = torch.load(f, map_location=torch.device('cpu'))
|
| 680 |
+
x['optimizer'] = None
|
| 681 |
+
x['training_results'] = None
|
| 682 |
+
x['epoch'] = -1
|
| 683 |
+
x['model'].half() # to FP16
|
| 684 |
+
for p in x['model'].parameters():
|
| 685 |
+
p.requires_grad = False
|
| 686 |
+
torch.save(x, s or f)
|
| 687 |
+
mb = os.path.getsize(s or f) / 1E6 # filesize
|
| 688 |
+
print('Optimizer stripped from %s,%s %.1fMB' % (f, (' saved as %s,' % s) if s else '', mb))
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
def coco_class_count(path='../coco/labels/train2014/'):
|
| 692 |
+
# Histogram of occurrences per class
|
| 693 |
+
nc = 80 # number classes
|
| 694 |
+
x = np.zeros(nc, dtype='int32')
|
| 695 |
+
files = sorted(glob.glob('%s/*.*' % path))
|
| 696 |
+
for i, file in enumerate(files):
|
| 697 |
+
labels = np.loadtxt(file, dtype=np.float32).reshape(-1, 5)
|
| 698 |
+
x += np.bincount(labels[:, 0].astype('int32'), minlength=nc)
|
| 699 |
+
print(i, len(files))
|
| 700 |
+
|
| 701 |
+
|
| 702 |
+
def coco_only_people(path='../coco/labels/train2017/'): # from utils.utils import *; coco_only_people()
|
| 703 |
+
# Find images with only people
|
| 704 |
+
files = sorted(glob.glob('%s/*.*' % path))
|
| 705 |
+
for i, file in enumerate(files):
|
| 706 |
+
labels = np.loadtxt(file, dtype=np.float32).reshape(-1, 5)
|
| 707 |
+
if all(labels[:, 0] == 0):
|
| 708 |
+
print(labels.shape[0], file)
|
| 709 |
+
|
| 710 |
+
|
| 711 |
+
def crop_images_random(path='../images/', scale=0.50): # from utils.utils import *; crop_images_random()
|
| 712 |
+
# crops images into random squares up to scale fraction
|
| 713 |
+
# WARNING: overwrites images!
|
| 714 |
+
for file in tqdm(sorted(glob.glob('%s/*.*' % path))):
|
| 715 |
+
img = cv2.imread(file) # BGR
|
| 716 |
+
if img is not None:
|
| 717 |
+
h, w = img.shape[:2]
|
| 718 |
+
|
| 719 |
+
# create random mask
|
| 720 |
+
a = 30 # minimum size (pixels)
|
| 721 |
+
mask_h = random.randint(a, int(max(a, h * scale))) # mask height
|
| 722 |
+
mask_w = mask_h # mask width
|
| 723 |
+
|
| 724 |
+
# box
|
| 725 |
+
xmin = max(0, random.randint(0, w) - mask_w // 2)
|
| 726 |
+
ymin = max(0, random.randint(0, h) - mask_h // 2)
|
| 727 |
+
xmax = min(w, xmin + mask_w)
|
| 728 |
+
ymax = min(h, ymin + mask_h)
|
| 729 |
+
|
| 730 |
+
# apply random color mask
|
| 731 |
+
cv2.imwrite(file, img[ymin:ymax, xmin:xmax])
|
| 732 |
+
|
| 733 |
+
|
| 734 |
+
def coco_single_class_labels(path='../coco/labels/train2014/', label_class=43):
|
| 735 |
+
# Makes single-class coco datasets. from utils.utils import *; coco_single_class_labels()
|
| 736 |
+
if os.path.exists('new/'):
|
| 737 |
+
shutil.rmtree('new/') # delete output folder
|
| 738 |
+
os.makedirs('new/') # make new output folder
|
| 739 |
+
os.makedirs('new/labels/')
|
| 740 |
+
os.makedirs('new/images/')
|
| 741 |
+
for file in tqdm(sorted(glob.glob('%s/*.*' % path))):
|
| 742 |
+
with open(file, 'r') as f:
|
| 743 |
+
labels = np.array([x.split() for x in f.read().splitlines()], dtype=np.float32)
|
| 744 |
+
i = labels[:, 0] == label_class
|
| 745 |
+
if any(i):
|
| 746 |
+
img_file = file.replace('labels', 'images').replace('txt', 'jpg')
|
| 747 |
+
labels[:, 0] = 0 # reset class to 0
|
| 748 |
+
with open('new/images.txt', 'a') as f: # add image to dataset list
|
| 749 |
+
f.write(img_file + '\n')
|
| 750 |
+
with open('new/labels/' + Path(file).name, 'a') as f: # write label
|
| 751 |
+
for l in labels[i]:
|
| 752 |
+
f.write('%g %.6f %.6f %.6f %.6f\n' % tuple(l))
|
| 753 |
+
shutil.copyfile(src=img_file, dst='new/images/' + Path(file).name.replace('txt', 'jpg')) # copy images
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
def kmean_anchors(path='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True):
|
| 757 |
+
""" Creates kmeans-evolved anchors from training dataset
|
| 758 |
+
|
| 759 |
+
Arguments:
|
| 760 |
+
path: path to dataset *.yaml, or a loaded dataset
|
| 761 |
+
n: number of anchors
|
| 762 |
+
img_size: image size used for training
|
| 763 |
+
thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0
|
| 764 |
+
gen: generations to evolve anchors using genetic algorithm
|
| 765 |
+
|
| 766 |
+
Return:
|
| 767 |
+
k: kmeans evolved anchors
|
| 768 |
+
|
| 769 |
+
Usage:
|
| 770 |
+
from utils.utils import *; _ = kmean_anchors()
|
| 771 |
+
"""
|
| 772 |
+
if kmeans is None:
|
| 773 |
+
raise ImportError(
|
| 774 |
+
"SciPy is required for kmean_anchors(), but SciPy could not be imported in this environment. "
|
| 775 |
+
f"Original error: {_SCIPY_IMPORT_ERROR}"
|
| 776 |
+
)
|
| 777 |
+
thr = 1. / thr
|
| 778 |
+
|
| 779 |
+
def metric(k, wh): # compute metrics
|
| 780 |
+
r = wh[:, None] / k[None]
|
| 781 |
+
x = torch.min(r, 1. / r).min(2)[0] # ratio metric
|
| 782 |
+
# x = wh_iou(wh, torch.tensor(k)) # iou metric
|
| 783 |
+
return x, x.max(1)[0] # x, best_x
|
| 784 |
+
|
| 785 |
+
def fitness(k): # mutation fitness
|
| 786 |
+
_, best = metric(torch.tensor(k, dtype=torch.float32), wh)
|
| 787 |
+
return (best * (best > thr).float()).mean() # fitness
|
| 788 |
+
|
| 789 |
+
def print_results(k):
|
| 790 |
+
k = k[np.argsort(k.prod(1))] # sort small to large
|
| 791 |
+
x, best = metric(k, wh0)
|
| 792 |
+
bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr
|
| 793 |
+
print('thr=%.2f: %.4f best possible recall, %.2f anchors past thr' % (thr, bpr, aat))
|
| 794 |
+
print('n=%g, img_size=%s, metric_all=%.3f/%.3f-mean/best, past_thr=%.3f-mean: ' %
|
| 795 |
+
(n, img_size, x.mean(), best.mean(), x[x > thr].mean()), end='')
|
| 796 |
+
for i, x in enumerate(k):
|
| 797 |
+
print('%i,%i' % (round(x[0]), round(x[1])), end=', ' if i < len(k) - 1 else '\n') # use in *.cfg
|
| 798 |
+
return k
|
| 799 |
+
|
| 800 |
+
if isinstance(path, str): # *.yaml file
|
| 801 |
+
with open(path) as f:
|
| 802 |
+
data_dict = yaml.load(f, Loader=yaml.FullLoader) # model dict
|
| 803 |
+
from utils.datasets import LoadImagesAndLabels
|
| 804 |
+
dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True)
|
| 805 |
+
else:
|
| 806 |
+
dataset = path # dataset
|
| 807 |
+
|
| 808 |
+
# Get label wh
|
| 809 |
+
shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True)
|
| 810 |
+
wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh
|
| 811 |
+
|
| 812 |
+
# Filter
|
| 813 |
+
i = (wh0 < 3.0).any(1).sum()
|
| 814 |
+
if i:
|
| 815 |
+
print('WARNING: Extremely small objects found. '
|
| 816 |
+
'%g of %g labels are < 3 pixels in width or height.' % (i, len(wh0)))
|
| 817 |
+
wh = wh0[(wh0 >= 2.0).any(1)] # filter > 2 pixels
|
| 818 |
+
|
| 819 |
+
# Kmeans calculation
|
| 820 |
+
print('Running kmeans for %g anchors on %g points...' % (n, len(wh)))
|
| 821 |
+
s = wh.std(0) # sigmas for whitening
|
| 822 |
+
k, dist = kmeans(wh / s, n, iter=30) # points, mean distance
|
| 823 |
+
k *= s
|
| 824 |
+
wh = torch.tensor(wh, dtype=torch.float32) # filtered
|
| 825 |
+
wh0 = torch.tensor(wh0, dtype=torch.float32) # unflitered
|
| 826 |
+
k = print_results(k)
|
| 827 |
+
|
| 828 |
+
# Plot
|
| 829 |
+
# k, d = [None] * 20, [None] * 20
|
| 830 |
+
# for i in tqdm(range(1, 21)):
|
| 831 |
+
# k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance
|
| 832 |
+
# fig, ax = plt.subplots(1, 2, figsize=(14, 7))
|
| 833 |
+
# ax = ax.ravel()
|
| 834 |
+
# ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.')
|
| 835 |
+
# fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh
|
| 836 |
+
# ax[0].hist(wh[wh[:, 0]<100, 0],400)
|
| 837 |
+
# ax[1].hist(wh[wh[:, 1]<100, 1],400)
|
| 838 |
+
# fig.tight_layout()
|
| 839 |
+
# fig.savefig('wh.png', dpi=200)
|
| 840 |
+
|
| 841 |
+
# Evolve
|
| 842 |
+
npr = np.random
|
| 843 |
+
f, sh, mp, s = fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma
|
| 844 |
+
pbar = tqdm(range(gen), desc='Evolving anchors with Genetic Algorithm') # progress bar
|
| 845 |
+
for _ in pbar:
|
| 846 |
+
v = np.ones(sh)
|
| 847 |
+
while (v == 1).all(): # mutate until a change occurs (prevent duplicates)
|
| 848 |
+
v = ((npr.random(sh) < mp) * npr.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0)
|
| 849 |
+
kg = (k.copy() * v).clip(min=2.0)
|
| 850 |
+
fg = fitness(kg)
|
| 851 |
+
if fg > f:
|
| 852 |
+
f, k = fg, kg.copy()
|
| 853 |
+
pbar.desc = 'Evolving anchors with Genetic Algorithm: fitness = %.4f' % f
|
| 854 |
+
if verbose:
|
| 855 |
+
print_results(k)
|
| 856 |
+
|
| 857 |
+
return print_results(k)
|
| 858 |
+
|
| 859 |
+
|
| 860 |
+
def print_mutation(hyp, results, yaml_file='hyp_evolved.yaml', bucket=''):
|
| 861 |
+
# Print mutation results to evolve.txt (for use with train.py --evolve)
|
| 862 |
+
a = '%10s' * len(hyp) % tuple(hyp.keys()) # hyperparam keys
|
| 863 |
+
b = '%10.3g' * len(hyp) % tuple(hyp.values()) # hyperparam values
|
| 864 |
+
c = '%10.4g' * len(results) % results # results (P, R, [email protected], [email protected]:0.95, val_losses x 3)
|
| 865 |
+
print('\n%s\n%s\nEvolved fitness: %s\n' % (a, b, c))
|
| 866 |
+
|
| 867 |
+
if bucket:
|
| 868 |
+
os.system('gsutil cp gs://%s/evolve.txt .' % bucket) # download evolve.txt
|
| 869 |
+
|
| 870 |
+
with open('evolve.txt', 'a') as f: # append result
|
| 871 |
+
f.write(c + b + '\n')
|
| 872 |
+
x = np.unique(np.loadtxt('evolve.txt', ndmin=2), axis=0) # load unique rows
|
| 873 |
+
x = x[np.argsort(-fitness(x))] # sort
|
| 874 |
+
np.savetxt('evolve.txt', x, '%10.3g') # save sort by fitness
|
| 875 |
+
|
| 876 |
+
if bucket:
|
| 877 |
+
os.system('gsutil cp evolve.txt gs://%s' % bucket) # upload evolve.txt
|
| 878 |
+
|
| 879 |
+
# Save yaml
|
| 880 |
+
for i, k in enumerate(hyp.keys()):
|
| 881 |
+
hyp[k] = float(x[0, i + 7])
|
| 882 |
+
with open(yaml_file, 'w') as f:
|
| 883 |
+
results = tuple(x[0, :7])
|
| 884 |
+
c = '%10.4g' * len(results) % results # results (P, R, [email protected], [email protected]:0.95, val_losses x 3)
|
| 885 |
+
f.write('# Hyperparameter Evolution Results\n# Generations: %g\n# Metrics: ' % len(x) + c + '\n\n')
|
| 886 |
+
yaml.dump(hyp, f, sort_keys=False)
|
| 887 |
+
|
| 888 |
+
|
| 889 |
+
def apply_classifier(x, model, img, im0):
|
| 890 |
+
# applies a second stage classifier to yolo outputs
|
| 891 |
+
im0 = [im0] if isinstance(im0, np.ndarray) else im0
|
| 892 |
+
for i, d in enumerate(x): # per image
|
| 893 |
+
if d is not None and len(d):
|
| 894 |
+
d = d.clone()
|
| 895 |
+
|
| 896 |
+
# Reshape and pad cutouts
|
| 897 |
+
b = xyxy2xywh(d[:, :4]) # boxes
|
| 898 |
+
b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # rectangle to square
|
| 899 |
+
b[:, 2:] = b[:, 2:] * 1.3 + 30 # pad
|
| 900 |
+
d[:, :4] = xywh2xyxy(b).long()
|
| 901 |
+
|
| 902 |
+
# Rescale boxes from img_size to im0 size
|
| 903 |
+
scale_coords(img.shape[2:], d[:, :4], im0[i].shape)
|
| 904 |
+
|
| 905 |
+
# Classes
|
| 906 |
+
pred_cls1 = d[:, 5].long()
|
| 907 |
+
ims = []
|
| 908 |
+
for j, a in enumerate(d): # per item
|
| 909 |
+
cutout = im0[i][int(a[1]):int(a[3]), int(a[0]):int(a[2])]
|
| 910 |
+
im = cv2.resize(cutout, (224, 224)) # BGR
|
| 911 |
+
# cv2.imwrite('test%i.jpg' % j, cutout)
|
| 912 |
+
|
| 913 |
+
im = im[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
|
| 914 |
+
im = np.ascontiguousarray(im, dtype=np.float32) # uint8 to float32
|
| 915 |
+
im /= 255.0 # 0 - 255 to 0.0 - 1.0
|
| 916 |
+
ims.append(im)
|
| 917 |
+
|
| 918 |
+
pred_cls2 = model(torch.Tensor(ims).to(d.device)).argmax(1) # classifier prediction
|
| 919 |
+
x[i] = x[i][pred_cls1 == pred_cls2] # retain matching class detections
|
| 920 |
+
|
| 921 |
+
return x
|
| 922 |
+
|
| 923 |
+
|
| 924 |
+
def fitness(x):
|
| 925 |
+
# Returns fitness (for use with results.txt or evolve.txt)
|
| 926 |
+
w = [0.0, 0.0, 0.1, 0.9] # weights for [P, R, [email protected], [email protected]:0.95]
|
| 927 |
+
return (x[:, :4] * w).sum(1)
|
| 928 |
+
|
| 929 |
+
|
| 930 |
+
def output_to_target(output, width, height):
|
| 931 |
+
# Convert model output to target format [batch_id, class_id, x, y, w, h, conf]
|
| 932 |
+
if isinstance(output, torch.Tensor):
|
| 933 |
+
output = output.cpu().numpy()
|
| 934 |
+
|
| 935 |
+
targets = []
|
| 936 |
+
for i, o in enumerate(output):
|
| 937 |
+
if o is not None:
|
| 938 |
+
for pred in o:
|
| 939 |
+
box = pred[:4]
|
| 940 |
+
w = (box[2] - box[0]) / width
|
| 941 |
+
h = (box[3] - box[1]) / height
|
| 942 |
+
x = box[0] / width + w / 2
|
| 943 |
+
y = box[1] / height + h / 2
|
| 944 |
+
conf = pred[4]
|
| 945 |
+
cls = int(pred[5])
|
| 946 |
+
|
| 947 |
+
targets.append([i, cls, x, y, w, h, conf])
|
| 948 |
+
|
| 949 |
+
return np.array(targets)
|
| 950 |
+
|
| 951 |
+
|
| 952 |
+
def increment_dir(dir, comment=''):
|
| 953 |
+
# Increments a directory runs/exp1 --> runs/exp2_comment
|
| 954 |
+
n = 0 # number
|
| 955 |
+
dir = str(Path(dir)) # os-agnostic
|
| 956 |
+
d = sorted(glob.glob(dir + '*')) # directories
|
| 957 |
+
if len(d):
|
| 958 |
+
n = max([int(x[len(dir):x.find('_') if '_' in x else None]) for x in d]) + 1 # increment
|
| 959 |
+
return dir + str(n) + ('_' + comment if comment else '')
|
| 960 |
+
|
| 961 |
+
|
| 962 |
+
# Plotting functions ---------------------------------------------------------------------------------------------------
|
| 963 |
+
def hist2d(x, y, n=100):
|
| 964 |
+
# 2d histogram used in labels.png and evolve.png
|
| 965 |
+
xedges, yedges = np.linspace(x.min(), x.max(), n), np.linspace(y.min(), y.max(), n)
|
| 966 |
+
hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges))
|
| 967 |
+
xidx = np.clip(np.digitize(x, xedges) - 1, 0, hist.shape[0] - 1)
|
| 968 |
+
yidx = np.clip(np.digitize(y, yedges) - 1, 0, hist.shape[1] - 1)
|
| 969 |
+
return np.log(hist[xidx, yidx])
|
| 970 |
+
|
| 971 |
+
|
| 972 |
+
def butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5):
|
| 973 |
+
if butter is None or filtfilt is None:
|
| 974 |
+
raise ImportError(
|
| 975 |
+
"SciPy is required for butter_lowpass_filtfilt(), but SciPy could not be imported in this environment. "
|
| 976 |
+
f"Original error: {_SCIPY_IMPORT_ERROR}"
|
| 977 |
+
)
|
| 978 |
+
# https://stackoverflow.com/questions/28536191/how-to-filter-smooth-with-scipy-numpy
|
| 979 |
+
def butter_lowpass(cutoff, fs, order):
|
| 980 |
+
nyq = 0.5 * fs
|
| 981 |
+
normal_cutoff = cutoff / nyq
|
| 982 |
+
b, a = butter(order, normal_cutoff, btype='low', analog=False)
|
| 983 |
+
return b, a
|
| 984 |
+
|
| 985 |
+
b, a = butter_lowpass(cutoff, fs, order=order)
|
| 986 |
+
return filtfilt(b, a, data) # forward-backward filter
|
| 987 |
+
|
| 988 |
+
|
| 989 |
+
def plot_one_box(x, img, color=None, label=None, line_thickness=None):
|
| 990 |
+
# Plots one bounding box on image img
|
| 991 |
+
tl = line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1 # line/font thickness
|
| 992 |
+
color = color or [random.randint(0, 255) for _ in range(3)]
|
| 993 |
+
c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
|
| 994 |
+
cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)
|
| 995 |
+
if label:
|
| 996 |
+
tf = max(tl - 1, 1) # font thickness
|
| 997 |
+
t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
|
| 998 |
+
c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
|
| 999 |
+
cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA) # filled
|
| 1000 |
+
cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)
|
| 1001 |
+
|
| 1002 |
+
|
| 1003 |
+
def plot_wh_methods(): # from utils.utils import *; plot_wh_methods()
|
| 1004 |
+
# Compares the two methods for width-height anchor multiplication
|
| 1005 |
+
# https://github.com/ultralytics/yolov3/issues/168
|
| 1006 |
+
x = np.arange(-4.0, 4.0, .1)
|
| 1007 |
+
ya = np.exp(x)
|
| 1008 |
+
yb = torch.sigmoid(torch.from_numpy(x)).numpy() * 2
|
| 1009 |
+
|
| 1010 |
+
fig = plt.figure(figsize=(6, 3), dpi=150)
|
| 1011 |
+
plt.plot(x, ya, '.-', label='YOLOv3')
|
| 1012 |
+
plt.plot(x, yb ** 2, '.-', label='YOLOv5 ^2')
|
| 1013 |
+
plt.plot(x, yb ** 1.6, '.-', label='YOLOv5 ^1.6')
|
| 1014 |
+
plt.xlim(left=-4, right=4)
|
| 1015 |
+
plt.ylim(bottom=0, top=6)
|
| 1016 |
+
plt.xlabel('input')
|
| 1017 |
+
plt.ylabel('output')
|
| 1018 |
+
plt.grid()
|
| 1019 |
+
plt.legend()
|
| 1020 |
+
fig.tight_layout()
|
| 1021 |
+
fig.savefig('comparison.png', dpi=200)
|
| 1022 |
+
|
| 1023 |
+
|
| 1024 |
+
def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=640, max_subplots=16):
|
| 1025 |
+
tl = 3 # line thickness
|
| 1026 |
+
tf = max(tl - 1, 1) # font thickness
|
| 1027 |
+
if os.path.isfile(fname): # do not overwrite
|
| 1028 |
+
return None
|
| 1029 |
+
|
| 1030 |
+
if isinstance(images, torch.Tensor):
|
| 1031 |
+
images = images.cpu().float().numpy()
|
| 1032 |
+
|
| 1033 |
+
if isinstance(targets, torch.Tensor):
|
| 1034 |
+
targets = targets.cpu().numpy()
|
| 1035 |
+
|
| 1036 |
+
# un-normalise
|
| 1037 |
+
if np.max(images[0]) <= 1:
|
| 1038 |
+
images *= 255
|
| 1039 |
+
|
| 1040 |
+
bs, _, h, w = images.shape # batch size, _, height, width
|
| 1041 |
+
bs = min(bs, max_subplots) # limit plot images
|
| 1042 |
+
ns = np.ceil(bs ** 0.5) # number of subplots (square)
|
| 1043 |
+
|
| 1044 |
+
# Check if we should resize
|
| 1045 |
+
scale_factor = max_size / max(h, w)
|
| 1046 |
+
if scale_factor < 1:
|
| 1047 |
+
h = math.ceil(scale_factor * h)
|
| 1048 |
+
w = math.ceil(scale_factor * w)
|
| 1049 |
+
|
| 1050 |
+
# Empty array for output
|
| 1051 |
+
mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8)
|
| 1052 |
+
|
| 1053 |
+
# Fix class - colour map
|
| 1054 |
+
prop_cycle = plt.rcParams['axes.prop_cycle']
|
| 1055 |
+
# https://stackoverflow.com/questions/51350872/python-from-color-name-to-rgb
|
| 1056 |
+
hex2rgb = lambda h: tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))
|
| 1057 |
+
color_lut = [hex2rgb(h) for h in prop_cycle.by_key()['color']]
|
| 1058 |
+
|
| 1059 |
+
for i, img in enumerate(images):
|
| 1060 |
+
if i == max_subplots: # if last batch has fewer images than we expect
|
| 1061 |
+
break
|
| 1062 |
+
|
| 1063 |
+
block_x = int(w * (i // ns))
|
| 1064 |
+
block_y = int(h * (i % ns))
|
| 1065 |
+
|
| 1066 |
+
img = img.transpose(1, 2, 0)
|
| 1067 |
+
if scale_factor < 1:
|
| 1068 |
+
img = cv2.resize(img, (w, h))
|
| 1069 |
+
|
| 1070 |
+
mosaic[block_y:block_y + h, block_x:block_x + w, :] = img
|
| 1071 |
+
if len(targets) > 0:
|
| 1072 |
+
image_targets = targets[targets[:, 0] == i]
|
| 1073 |
+
boxes = xywh2xyxy(image_targets[:, 2:6]).T
|
| 1074 |
+
classes = image_targets[:, 1].astype('int')
|
| 1075 |
+
gt = image_targets.shape[1] == 6 # ground truth if no conf column
|
| 1076 |
+
conf = None if gt else image_targets[:, 6] # check for confidence presence (gt vs pred)
|
| 1077 |
+
|
| 1078 |
+
boxes[[0, 2]] *= w
|
| 1079 |
+
boxes[[0, 2]] += block_x
|
| 1080 |
+
boxes[[1, 3]] *= h
|
| 1081 |
+
boxes[[1, 3]] += block_y
|
| 1082 |
+
for j, box in enumerate(boxes.T):
|
| 1083 |
+
cls = int(classes[j])
|
| 1084 |
+
color = color_lut[cls % len(color_lut)]
|
| 1085 |
+
cls = names[cls] if names else cls
|
| 1086 |
+
if gt or conf[j] > 0.3: # 0.3 conf thresh
|
| 1087 |
+
label = '%s' % cls if gt else '%s %.1f' % (cls, conf[j])
|
| 1088 |
+
plot_one_box(box, mosaic, label=label, color=color, line_thickness=tl)
|
| 1089 |
+
|
| 1090 |
+
# Draw image filename labels
|
| 1091 |
+
if paths is not None:
|
| 1092 |
+
label = os.path.basename(paths[i])[:40] # trim to 40 char
|
| 1093 |
+
t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
|
| 1094 |
+
cv2.putText(mosaic, label, (block_x + 5, block_y + t_size[1] + 5), 0, tl / 3, [220, 220, 220], thickness=tf,
|
| 1095 |
+
lineType=cv2.LINE_AA)
|
| 1096 |
+
|
| 1097 |
+
# Image border
|
| 1098 |
+
cv2.rectangle(mosaic, (block_x, block_y), (block_x + w, block_y + h), (255, 255, 255), thickness=3)
|
| 1099 |
+
|
| 1100 |
+
if fname is not None:
|
| 1101 |
+
mosaic = cv2.resize(mosaic, (int(ns * w * 0.5), int(ns * h * 0.5)), interpolation=cv2.INTER_AREA)
|
| 1102 |
+
cv2.imwrite(fname, cv2.cvtColor(mosaic, cv2.COLOR_BGR2RGB))
|
| 1103 |
+
|
| 1104 |
+
return mosaic
|
| 1105 |
+
|
| 1106 |
+
|
| 1107 |
+
def plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=''):
|
| 1108 |
+
# Plot LR simulating training for full epochs
|
| 1109 |
+
optimizer, scheduler = copy(optimizer), copy(scheduler) # do not modify originals
|
| 1110 |
+
y = []
|
| 1111 |
+
for _ in range(epochs):
|
| 1112 |
+
scheduler.step()
|
| 1113 |
+
y.append(optimizer.param_groups[0]['lr'])
|
| 1114 |
+
plt.plot(y, '.-', label='LR')
|
| 1115 |
+
plt.xlabel('epoch')
|
| 1116 |
+
plt.ylabel('LR')
|
| 1117 |
+
plt.grid()
|
| 1118 |
+
plt.xlim(0, epochs)
|
| 1119 |
+
plt.ylim(0)
|
| 1120 |
+
plt.tight_layout()
|
| 1121 |
+
plt.savefig(Path(save_dir) / 'LR.png', dpi=200)
|
| 1122 |
+
|
| 1123 |
+
|
| 1124 |
+
def plot_test_txt(): # from utils.utils import *; plot_test()
|
| 1125 |
+
# Plot test.txt histograms
|
| 1126 |
+
x = np.loadtxt('test.txt', dtype=np.float32)
|
| 1127 |
+
box = xyxy2xywh(x[:, :4])
|
| 1128 |
+
cx, cy = box[:, 0], box[:, 1]
|
| 1129 |
+
|
| 1130 |
+
fig, ax = plt.subplots(1, 1, figsize=(6, 6), tight_layout=True)
|
| 1131 |
+
ax.hist2d(cx, cy, bins=600, cmax=10, cmin=0)
|
| 1132 |
+
ax.set_aspect('equal')
|
| 1133 |
+
plt.savefig('hist2d.png', dpi=300)
|
| 1134 |
+
|
| 1135 |
+
fig, ax = plt.subplots(1, 2, figsize=(12, 6), tight_layout=True)
|
| 1136 |
+
ax[0].hist(cx, bins=600)
|
| 1137 |
+
ax[1].hist(cy, bins=600)
|
| 1138 |
+
plt.savefig('hist1d.png', dpi=200)
|
| 1139 |
+
|
| 1140 |
+
|
| 1141 |
+
def plot_targets_txt(): # from utils.utils import *; plot_targets_txt()
|
| 1142 |
+
# Plot targets.txt histograms
|
| 1143 |
+
x = np.loadtxt('targets.txt', dtype=np.float32).T
|
| 1144 |
+
s = ['x targets', 'y targets', 'width targets', 'height targets']
|
| 1145 |
+
fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)
|
| 1146 |
+
ax = ax.ravel()
|
| 1147 |
+
for i in range(4):
|
| 1148 |
+
ax[i].hist(x[i], bins=100, label='%.3g +/- %.3g' % (x[i].mean(), x[i].std()))
|
| 1149 |
+
ax[i].legend()
|
| 1150 |
+
ax[i].set_title(s[i])
|
| 1151 |
+
plt.savefig('targets.jpg', dpi=200)
|
| 1152 |
+
|
| 1153 |
+
|
| 1154 |
+
def plot_study_txt(f='study.txt', x=None): # from utils.utils import *; plot_study_txt()
|
| 1155 |
+
# Plot study.txt generated by test.py
|
| 1156 |
+
fig, ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True)
|
| 1157 |
+
ax = ax.ravel()
|
| 1158 |
+
|
| 1159 |
+
fig2, ax2 = plt.subplots(1, 1, figsize=(8, 4), tight_layout=True)
|
| 1160 |
+
for f in ['coco_study/study_coco_yolov5%s.txt' % x for x in ['s', 'm', 'l', 'x']]:
|
| 1161 |
+
y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T
|
| 1162 |
+
x = np.arange(y.shape[1]) if x is None else np.array(x)
|
| 1163 |
+
s = ['P', 'R', '[email protected]', '[email protected]:.95', 't_inference (ms/img)', 't_NMS (ms/img)', 't_total (ms/img)']
|
| 1164 |
+
for i in range(7):
|
| 1165 |
+
ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8)
|
| 1166 |
+
ax[i].set_title(s[i])
|
| 1167 |
+
|
| 1168 |
+
j = y[3].argmax() + 1
|
| 1169 |
+
ax2.plot(y[6, :j], y[3, :j] * 1E2, '.-', linewidth=2, markersize=8,
|
| 1170 |
+
label=Path(f).stem.replace('study_coco_', '').replace('yolo', 'YOLO'))
|
| 1171 |
+
|
| 1172 |
+
ax2.plot(1E3 / np.array([209, 140, 97, 58, 35, 18]), [33.8, 39.6, 43.0, 47.5, 49.4, 50.7],
|
| 1173 |
+
'k.-', linewidth=2, markersize=8, alpha=.25, label='EfficientDet')
|
| 1174 |
+
|
| 1175 |
+
ax2.grid()
|
| 1176 |
+
ax2.set_xlim(0, 30)
|
| 1177 |
+
ax2.set_ylim(28, 50)
|
| 1178 |
+
ax2.set_yticks(np.arange(30, 55, 5))
|
| 1179 |
+
ax2.set_xlabel('GPU Speed (ms/img)')
|
| 1180 |
+
ax2.set_ylabel('COCO AP val')
|
| 1181 |
+
ax2.legend(loc='lower right')
|
| 1182 |
+
plt.savefig('study_mAP_latency.png', dpi=300)
|
| 1183 |
+
plt.savefig(f.replace('.txt', '.png'), dpi=200)
|
| 1184 |
+
|
| 1185 |
+
|
| 1186 |
+
def plot_labels(labels, save_dir=''):
|
| 1187 |
+
# plot dataset labels
|
| 1188 |
+
c, b = labels[:, 0], labels[:, 1:].transpose() # classes, boxes
|
| 1189 |
+
nc = int(c.max() + 1) # number of classes
|
| 1190 |
+
|
| 1191 |
+
fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)
|
| 1192 |
+
ax = ax.ravel()
|
| 1193 |
+
ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8)
|
| 1194 |
+
ax[0].set_xlabel('classes')
|
| 1195 |
+
ax[1].scatter(b[0], b[1], c=hist2d(b[0], b[1], 90), cmap='jet')
|
| 1196 |
+
ax[1].set_xlabel('x')
|
| 1197 |
+
ax[1].set_ylabel('y')
|
| 1198 |
+
ax[2].scatter(b[2], b[3], c=hist2d(b[2], b[3], 90), cmap='jet')
|
| 1199 |
+
ax[2].set_xlabel('width')
|
| 1200 |
+
ax[2].set_ylabel('height')
|
| 1201 |
+
plt.savefig(Path(save_dir) / 'labels.png', dpi=200)
|
| 1202 |
+
plt.close()
|
| 1203 |
+
|
| 1204 |
+
|
| 1205 |
+
def plot_evolution(yaml_file='runs/evolve/hyp_evolved.yaml'): # from utils.utils import *; plot_evolution()
|
| 1206 |
+
# Plot hyperparameter evolution results in evolve.txt
|
| 1207 |
+
with open(yaml_file) as f:
|
| 1208 |
+
hyp = yaml.load(f, Loader=yaml.FullLoader)
|
| 1209 |
+
x = np.loadtxt('evolve.txt', ndmin=2)
|
| 1210 |
+
f = fitness(x)
|
| 1211 |
+
# weights = (f - f.min()) ** 2 # for weighted results
|
| 1212 |
+
plt.figure(figsize=(10, 10), tight_layout=True)
|
| 1213 |
+
matplotlib.rc('font', **{'size': 8})
|
| 1214 |
+
for i, (k, v) in enumerate(hyp.items()):
|
| 1215 |
+
y = x[:, i + 7]
|
| 1216 |
+
# mu = (y * weights).sum() / weights.sum() # best weighted result
|
| 1217 |
+
mu = y[f.argmax()] # best single result
|
| 1218 |
+
plt.subplot(5, 5, i + 1)
|
| 1219 |
+
plt.scatter(y, f, c=hist2d(y, f, 20), cmap='viridis', alpha=.8, edgecolors='none')
|
| 1220 |
+
plt.plot(mu, f.max(), 'k+', markersize=15)
|
| 1221 |
+
plt.title('%s = %.3g' % (k, mu), fontdict={'size': 9}) # limit to 40 characters
|
| 1222 |
+
if i % 5 != 0:
|
| 1223 |
+
plt.yticks([])
|
| 1224 |
+
print('%15s: %.3g' % (k, mu))
|
| 1225 |
+
plt.savefig('evolve.png', dpi=200)
|
| 1226 |
+
print('\nPlot saved as evolve.png')
|
| 1227 |
+
|
| 1228 |
+
|
| 1229 |
+
def plot_results_overlay(start=0, stop=0): # from utils.utils import *; plot_results_overlay()
|
| 1230 |
+
# Plot training 'results*.txt', overlaying train and val losses
|
| 1231 |
+
s = ['train', 'train', 'train', 'Precision', '[email protected]', 'val', 'val', 'val', 'Recall', '[email protected]:0.95'] # legends
|
| 1232 |
+
t = ['GIoU', 'Objectness', 'Classification', 'P-R', 'mAP-F1'] # titles
|
| 1233 |
+
for f in sorted(glob.glob('results*.txt') + glob.glob('../../Downloads/results*.txt')):
|
| 1234 |
+
results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
|
| 1235 |
+
n = results.shape[1] # number of rows
|
| 1236 |
+
x = range(start, min(stop, n) if stop else n)
|
| 1237 |
+
fig, ax = plt.subplots(1, 5, figsize=(14, 3.5), tight_layout=True)
|
| 1238 |
+
ax = ax.ravel()
|
| 1239 |
+
for i in range(5):
|
| 1240 |
+
for j in [i, i + 5]:
|
| 1241 |
+
y = results[j, x]
|
| 1242 |
+
ax[i].plot(x, y, marker='.', label=s[j])
|
| 1243 |
+
# y_smooth = butter_lowpass_filtfilt(y)
|
| 1244 |
+
# ax[i].plot(x, np.gradient(y_smooth), marker='.', label=s[j])
|
| 1245 |
+
|
| 1246 |
+
ax[i].set_title(t[i])
|
| 1247 |
+
ax[i].legend()
|
| 1248 |
+
ax[i].set_ylabel(f) if i == 0 else None # add filename
|
| 1249 |
+
fig.savefig(f.replace('.txt', '.png'), dpi=200)
|
| 1250 |
+
|
| 1251 |
+
|
| 1252 |
+
def plot_results(start=0, stop=0, bucket='', id=(), labels=(),
|
| 1253 |
+
save_dir=''): # from utils.utils import *; plot_results()
|
| 1254 |
+
# Plot training 'results*.txt' as seen in https://github.com/ultralytics/yolov5#reproduce-our-training
|
| 1255 |
+
fig, ax = plt.subplots(2, 5, figsize=(12, 6))
|
| 1256 |
+
ax = ax.ravel()
|
| 1257 |
+
s = ['GIoU', 'Objectness', 'Classification', 'Precision', 'Recall',
|
| 1258 |
+
'val GIoU', 'val Objectness', 'val Classification', '[email protected]', '[email protected]:0.95']
|
| 1259 |
+
if bucket:
|
| 1260 |
+
os.system('rm -rf storage.googleapis.com')
|
| 1261 |
+
files = ['https://storage.googleapis.com/%s/results%g.txt' % (bucket, x) for x in id]
|
| 1262 |
+
else:
|
| 1263 |
+
files = glob.glob(str(Path(save_dir) / 'results*.txt')) + glob.glob('../../Downloads/results*.txt')
|
| 1264 |
+
for fi, f in enumerate(files):
|
| 1265 |
+
try:
|
| 1266 |
+
results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
|
| 1267 |
+
n = results.shape[1] # number of rows
|
| 1268 |
+
x = range(start, min(stop, n) if stop else n)
|
| 1269 |
+
for i in range(10):
|
| 1270 |
+
y = results[i, x]
|
| 1271 |
+
if i in [0, 1, 2, 5, 6, 7]:
|
| 1272 |
+
y[y == 0] = np.nan # dont show zero loss values
|
| 1273 |
+
# y /= y[0] # normalize
|
| 1274 |
+
label = labels[fi] if len(labels) else Path(f).stem
|
| 1275 |
+
ax[i].plot(x, y, marker='.', label=label, linewidth=2, markersize=8)
|
| 1276 |
+
ax[i].set_title(s[i])
|
| 1277 |
+
# if i in [5, 6, 7]: # share train and val loss y axes
|
| 1278 |
+
# ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])
|
| 1279 |
+
except:
|
| 1280 |
+
print('Warning: Plotting error for %s, skipping file' % f)
|
| 1281 |
+
|
| 1282 |
+
fig.tight_layout()
|
| 1283 |
+
ax[1].legend()
|
| 1284 |
+
fig.savefig(Path(save_dir) / 'results.png', dpi=200)
|
yolov5_anime/utils/google_utils.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file contains google utils: https://cloud.google.com/storage/docs/reference/libraries
|
| 2 |
+
# pip install --upgrade google-cloud-storage
|
| 3 |
+
# from google.cloud import storage
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
import platform
|
| 7 |
+
import time
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def attempt_download(weights):
|
| 12 |
+
# Attempt to download pretrained weights if not found locally
|
| 13 |
+
weights = weights.strip().replace("'", '')
|
| 14 |
+
msg = weights + ' missing, try downloading from https://drive.google.com/drive/folders/1Drs_Aiu7xx6S-ix95f9kNsA6ueKRpN2J'
|
| 15 |
+
|
| 16 |
+
r = 1 # return
|
| 17 |
+
if len(weights) > 0 and not os.path.isfile(weights):
|
| 18 |
+
d = {'yolov3-spp.pt': '1mM67oNw4fZoIOL1c8M3hHmj66d8e-ni_', # yolov3-spp.yaml
|
| 19 |
+
'yolov5s.pt': '1R5T6rIyy3lLwgFXNms8whc-387H0tMQO', # yolov5s.yaml
|
| 20 |
+
'yolov5m.pt': '1vobuEExpWQVpXExsJ2w-Mbf3HJjWkQJr', # yolov5m.yaml
|
| 21 |
+
'yolov5l.pt': '1hrlqD1Wdei7UT4OgT785BEk1JwnSvNEV', # yolov5l.yaml
|
| 22 |
+
'yolov5x.pt': '1mM8aZJlWTxOg7BZJvNUMrTnA2AbeCVzS', # yolov5x.yaml
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
file = Path(weights).name
|
| 26 |
+
if file in d:
|
| 27 |
+
r = gdrive_download(id=d[file], name=weights)
|
| 28 |
+
|
| 29 |
+
if not (r == 0 and os.path.exists(weights) and os.path.getsize(weights) > 1E6): # weights exist and > 1MB
|
| 30 |
+
os.remove(weights) if os.path.exists(weights) else None # remove partial downloads
|
| 31 |
+
s = 'curl -L -o %s "storage.googleapis.com/ultralytics/yolov5/ckpt/%s"' % (weights, file)
|
| 32 |
+
r = os.system(s) # execute, capture return values
|
| 33 |
+
|
| 34 |
+
# Error check
|
| 35 |
+
if not (r == 0 and os.path.exists(weights) and os.path.getsize(weights) > 1E6): # weights exist and > 1MB
|
| 36 |
+
os.remove(weights) if os.path.exists(weights) else None # remove partial downloads
|
| 37 |
+
raise Exception(msg)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def gdrive_download(id='1n_oKgR81BJtqk75b00eAjdv03qVCQn2f', name='coco128.zip'):
|
| 41 |
+
# Downloads a file from Google Drive, accepting presented query
|
| 42 |
+
# from utils.google_utils import *; gdrive_download()
|
| 43 |
+
t = time.time()
|
| 44 |
+
|
| 45 |
+
print('Downloading https://drive.google.com/uc?export=download&id=%s as %s... ' % (id, name), end='')
|
| 46 |
+
os.remove(name) if os.path.exists(name) else None # remove existing
|
| 47 |
+
os.remove('cookie') if os.path.exists('cookie') else None
|
| 48 |
+
|
| 49 |
+
# Attempt file download
|
| 50 |
+
out = "NUL" if platform.system() == "Windows" else "/dev/null"
|
| 51 |
+
os.system('curl -c ./cookie -s -L "drive.google.com/uc?export=download&id=%s" > %s ' % (id, out))
|
| 52 |
+
if os.path.exists('cookie'): # large file
|
| 53 |
+
s = 'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm=%s&id=%s" -o %s' % (get_token(), id, name)
|
| 54 |
+
else: # small file
|
| 55 |
+
s = 'curl -s -L -o %s "drive.google.com/uc?export=download&id=%s"' % (name, id)
|
| 56 |
+
r = os.system(s) # execute, capture return values
|
| 57 |
+
os.remove('cookie') if os.path.exists('cookie') else None
|
| 58 |
+
|
| 59 |
+
# Error check
|
| 60 |
+
if r != 0:
|
| 61 |
+
os.remove(name) if os.path.exists(name) else None # remove partial
|
| 62 |
+
print('Download error ') # raise Exception('Download error')
|
| 63 |
+
return r
|
| 64 |
+
|
| 65 |
+
# Unzip if archive
|
| 66 |
+
if name.endswith('.zip'):
|
| 67 |
+
print('unzipping... ', end='')
|
| 68 |
+
os.system('unzip -q %s' % name) # unzip
|
| 69 |
+
os.remove(name) # remove zip to free space
|
| 70 |
+
|
| 71 |
+
print('Done (%.1fs)' % (time.time() - t))
|
| 72 |
+
return r
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def get_token(cookie="./cookie"):
|
| 76 |
+
with open(cookie) as f:
|
| 77 |
+
for line in f:
|
| 78 |
+
if "download" in line:
|
| 79 |
+
return line.split()[-1]
|
| 80 |
+
return ""
|
| 81 |
+
|
| 82 |
+
# def upload_blob(bucket_name, source_file_name, destination_blob_name):
|
| 83 |
+
# # Uploads a file to a bucket
|
| 84 |
+
# # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python
|
| 85 |
+
#
|
| 86 |
+
# storage_client = storage.Client()
|
| 87 |
+
# bucket = storage_client.get_bucket(bucket_name)
|
| 88 |
+
# blob = bucket.blob(destination_blob_name)
|
| 89 |
+
#
|
| 90 |
+
# blob.upload_from_filename(source_file_name)
|
| 91 |
+
#
|
| 92 |
+
# print('File {} uploaded to {}.'.format(
|
| 93 |
+
# source_file_name,
|
| 94 |
+
# destination_blob_name))
|
| 95 |
+
#
|
| 96 |
+
#
|
| 97 |
+
# def download_blob(bucket_name, source_blob_name, destination_file_name):
|
| 98 |
+
# # Uploads a blob from a bucket
|
| 99 |
+
# storage_client = storage.Client()
|
| 100 |
+
# bucket = storage_client.get_bucket(bucket_name)
|
| 101 |
+
# blob = bucket.blob(source_blob_name)
|
| 102 |
+
#
|
| 103 |
+
# blob.download_to_filename(destination_file_name)
|
| 104 |
+
#
|
| 105 |
+
# print('Blob {} downloaded to {}.'.format(
|
| 106 |
+
# source_blob_name,
|
| 107 |
+
# destination_file_name))
|
yolov5_anime/utils/torch_utils.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import os
|
| 3 |
+
import time
|
| 4 |
+
from copy import deepcopy
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.backends.cudnn as cudnn
|
| 8 |
+
import torch.nn as nn
|
| 9 |
+
import torch.nn.functional as F
|
| 10 |
+
import torchvision.models as models
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def init_seeds(seed=0):
|
| 14 |
+
torch.manual_seed(seed)
|
| 15 |
+
|
| 16 |
+
# Speed-reproducibility tradeoff https://pytorch.org/docs/stable/notes/randomness.html
|
| 17 |
+
if seed == 0: # slower, more reproducible
|
| 18 |
+
cudnn.deterministic = True
|
| 19 |
+
cudnn.benchmark = False
|
| 20 |
+
else: # faster, less reproducible
|
| 21 |
+
cudnn.deterministic = False
|
| 22 |
+
cudnn.benchmark = True
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def select_device(device='', batch_size=None):
|
| 26 |
+
# device = 'cpu' or '0' or '0,1,2,3'
|
| 27 |
+
cpu_request = device.lower() == 'cpu'
|
| 28 |
+
if device and not cpu_request: # if device requested other than 'cpu'
|
| 29 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable
|
| 30 |
+
assert torch.cuda.is_available(), 'CUDA unavailable, invalid device %s requested' % device # check availablity
|
| 31 |
+
|
| 32 |
+
cuda = False if cpu_request else torch.cuda.is_available()
|
| 33 |
+
if cuda:
|
| 34 |
+
c = 1024 ** 2 # bytes to MB
|
| 35 |
+
ng = torch.cuda.device_count()
|
| 36 |
+
if ng > 1 and batch_size: # check that batch_size is compatible with device_count
|
| 37 |
+
assert batch_size % ng == 0, 'batch-size %g not multiple of GPU count %g' % (batch_size, ng)
|
| 38 |
+
x = [torch.cuda.get_device_properties(i) for i in range(ng)]
|
| 39 |
+
s = 'Using CUDA '
|
| 40 |
+
for i in range(0, ng):
|
| 41 |
+
if i == 1:
|
| 42 |
+
s = ' ' * len(s)
|
| 43 |
+
print("%sdevice%g _CudaDeviceProperties(name='%s', total_memory=%dMB)" %
|
| 44 |
+
(s, i, x[i].name, x[i].total_memory / c))
|
| 45 |
+
else:
|
| 46 |
+
print('Using CPU')
|
| 47 |
+
|
| 48 |
+
print('') # skip a line
|
| 49 |
+
return torch.device('cuda:0' if cuda else 'cpu')
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def time_synchronized():
|
| 53 |
+
torch.cuda.synchronize() if torch.cuda.is_available() else None
|
| 54 |
+
return time.time()
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def is_parallel(model):
|
| 58 |
+
return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def intersect_dicts(da, db, exclude=()):
|
| 62 |
+
# Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values
|
| 63 |
+
return {k: v for k, v in da.items() if k in db and not any(x in k for x in exclude) and v.shape == db[k].shape}
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def initialize_weights(model):
|
| 67 |
+
for m in model.modules():
|
| 68 |
+
t = type(m)
|
| 69 |
+
if t is nn.Conv2d:
|
| 70 |
+
pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
|
| 71 |
+
elif t is nn.BatchNorm2d:
|
| 72 |
+
m.eps = 1e-3
|
| 73 |
+
m.momentum = 0.03
|
| 74 |
+
elif t in [nn.LeakyReLU, nn.ReLU, nn.ReLU6]:
|
| 75 |
+
m.inplace = True
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def find_modules(model, mclass=nn.Conv2d):
|
| 79 |
+
# Finds layer indices matching module class 'mclass'
|
| 80 |
+
return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)]
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def sparsity(model):
|
| 84 |
+
# Return global model sparsity
|
| 85 |
+
a, b = 0., 0.
|
| 86 |
+
for p in model.parameters():
|
| 87 |
+
a += p.numel()
|
| 88 |
+
b += (p == 0).sum()
|
| 89 |
+
return b / a
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def prune(model, amount=0.3):
|
| 93 |
+
# Prune model to requested global sparsity
|
| 94 |
+
import torch.nn.utils.prune as prune
|
| 95 |
+
print('Pruning model... ', end='')
|
| 96 |
+
for name, m in model.named_modules():
|
| 97 |
+
if isinstance(m, nn.Conv2d):
|
| 98 |
+
prune.l1_unstructured(m, name='weight', amount=amount) # prune
|
| 99 |
+
prune.remove(m, 'weight') # make permanent
|
| 100 |
+
print(' %.3g global sparsity' % sparsity(model))
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def fuse_conv_and_bn(conv, bn):
|
| 104 |
+
# https://tehnokv.com/posts/fusing-batchnorm-and-conv/
|
| 105 |
+
with torch.no_grad():
|
| 106 |
+
# init
|
| 107 |
+
fusedconv = nn.Conv2d(conv.in_channels,
|
| 108 |
+
conv.out_channels,
|
| 109 |
+
kernel_size=conv.kernel_size,
|
| 110 |
+
stride=conv.stride,
|
| 111 |
+
padding=conv.padding,
|
| 112 |
+
bias=True).to(conv.weight.device)
|
| 113 |
+
|
| 114 |
+
# prepare filters
|
| 115 |
+
w_conv = conv.weight.clone().view(conv.out_channels, -1)
|
| 116 |
+
w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))
|
| 117 |
+
fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.size()))
|
| 118 |
+
|
| 119 |
+
# prepare spatial bias
|
| 120 |
+
b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias
|
| 121 |
+
b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))
|
| 122 |
+
fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn)
|
| 123 |
+
|
| 124 |
+
return fusedconv
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def model_info(model, verbose=False):
|
| 128 |
+
# Plots a line-by-line description of a PyTorch model
|
| 129 |
+
n_p = sum(x.numel() for x in model.parameters()) # number parameters
|
| 130 |
+
n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients
|
| 131 |
+
if verbose:
|
| 132 |
+
print('%5s %40s %9s %12s %20s %10s %10s' % ('layer', 'name', 'gradient', 'parameters', 'shape', 'mu', 'sigma'))
|
| 133 |
+
for i, (name, p) in enumerate(model.named_parameters()):
|
| 134 |
+
name = name.replace('module_list.', '')
|
| 135 |
+
print('%5g %40s %9s %12g %20s %10.3g %10.3g' %
|
| 136 |
+
(i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std()))
|
| 137 |
+
|
| 138 |
+
try: # FLOPS
|
| 139 |
+
from thop import profile
|
| 140 |
+
flops = profile(deepcopy(model), inputs=(torch.zeros(1, 3, 64, 64),), verbose=False)[0] / 1E9 * 2
|
| 141 |
+
fs = ', %.1f GFLOPS' % (flops * 100) # 640x640 FLOPS
|
| 142 |
+
except:
|
| 143 |
+
fs = ''
|
| 144 |
+
|
| 145 |
+
print('Model Summary: %g layers, %g parameters, %g gradients%s' % (len(list(model.parameters())), n_p, n_g, fs))
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def load_classifier(name='resnet101', n=2):
|
| 149 |
+
# Loads a pretrained model reshaped to n-class output
|
| 150 |
+
model = models.__dict__[name](pretrained=True)
|
| 151 |
+
|
| 152 |
+
# Display model properties
|
| 153 |
+
input_size = [3, 224, 224]
|
| 154 |
+
input_space = 'RGB'
|
| 155 |
+
input_range = [0, 1]
|
| 156 |
+
mean = [0.485, 0.456, 0.406]
|
| 157 |
+
std = [0.229, 0.224, 0.225]
|
| 158 |
+
for x in [input_size, input_space, input_range, mean, std]:
|
| 159 |
+
print(x + ' =', eval(x))
|
| 160 |
+
|
| 161 |
+
# Reshape output to n classes
|
| 162 |
+
filters = model.fc.weight.shape[1]
|
| 163 |
+
model.fc.bias = nn.Parameter(torch.zeros(n), requires_grad=True)
|
| 164 |
+
model.fc.weight = nn.Parameter(torch.zeros(n, filters), requires_grad=True)
|
| 165 |
+
model.fc.out_features = n
|
| 166 |
+
return model
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def scale_img(img, ratio=1.0, same_shape=False): # img(16,3,256,416), r=ratio
|
| 170 |
+
# scales img(bs,3,y,x) by ratio
|
| 171 |
+
if ratio == 1.0:
|
| 172 |
+
return img
|
| 173 |
+
else:
|
| 174 |
+
h, w = img.shape[2:]
|
| 175 |
+
s = (int(h * ratio), int(w * ratio)) # new size
|
| 176 |
+
img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize
|
| 177 |
+
if not same_shape: # pad/crop img
|
| 178 |
+
gs = 32 # (pixels) grid size
|
| 179 |
+
h, w = [math.ceil(x * ratio / gs) * gs for x in (h, w)]
|
| 180 |
+
return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def copy_attr(a, b, include=(), exclude=()):
|
| 184 |
+
# Copy attributes from b to a, options to only include [...] and to exclude [...]
|
| 185 |
+
for k, v in b.__dict__.items():
|
| 186 |
+
if (len(include) and k not in include) or k.startswith('_') or k in exclude:
|
| 187 |
+
continue
|
| 188 |
+
else:
|
| 189 |
+
setattr(a, k, v)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
class ModelEMA:
|
| 193 |
+
""" Model Exponential Moving Average from https://github.com/rwightman/pytorch-image-models
|
| 194 |
+
Keep a moving average of everything in the model state_dict (parameters and buffers).
|
| 195 |
+
This is intended to allow functionality like
|
| 196 |
+
https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage
|
| 197 |
+
A smoothed version of the weights is necessary for some training schemes to perform well.
|
| 198 |
+
This class is sensitive where it is initialized in the sequence of model init,
|
| 199 |
+
GPU assignment and distributed training wrappers.
|
| 200 |
+
"""
|
| 201 |
+
|
| 202 |
+
def __init__(self, model, decay=0.9999, updates=0):
|
| 203 |
+
# Create EMA
|
| 204 |
+
self.ema = deepcopy(model.module if is_parallel(model) else model).eval() # FP32 EMA
|
| 205 |
+
# if next(model.parameters()).device.type != 'cpu':
|
| 206 |
+
# self.ema.half() # FP16 EMA
|
| 207 |
+
self.updates = updates # number of EMA updates
|
| 208 |
+
self.decay = lambda x: decay * (1 - math.exp(-x / 2000)) # decay exponential ramp (to help early epochs)
|
| 209 |
+
for p in self.ema.parameters():
|
| 210 |
+
p.requires_grad_(False)
|
| 211 |
+
|
| 212 |
+
def update(self, model):
|
| 213 |
+
# Update EMA parameters
|
| 214 |
+
with torch.no_grad():
|
| 215 |
+
self.updates += 1
|
| 216 |
+
d = self.decay(self.updates)
|
| 217 |
+
|
| 218 |
+
msd = model.module.state_dict() if is_parallel(model) else model.state_dict() # model state_dict
|
| 219 |
+
for k, v in self.ema.state_dict().items():
|
| 220 |
+
if v.dtype.is_floating_point:
|
| 221 |
+
v *= d
|
| 222 |
+
v += (1. - d) * msd[k].detach()
|
| 223 |
+
|
| 224 |
+
def update_attr(self, model, include=(), exclude=('process_group', 'reducer')):
|
| 225 |
+
# Update EMA attributes
|
| 226 |
+
copy_attr(self.ema, model, include, exclude)
|