├── .dockerignore ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── data ├── coco.yaml ├── coco128.yaml ├── drive.yaml └── get_coco2017.sh ├── detect.py ├── hubconf.py ├── labels.png ├── models ├── __init__.py ├── common.py ├── experimental.py ├── onnx_export.py ├── yolo.py ├── yolov3-spp.yaml ├── yolov5l.yaml ├── yolov5m.yaml ├── yolov5s.yaml └── yolov5x.yaml ├── my_utils ├── data_aug.py ├── imgaug_utils.py ├── my_utils.rar ├── parse_xml.py └── remove_noexist.py ├── requirements.txt ├── results.png ├── results.txt ├── test.py ├── test_batch0_gt.jpg ├── test_batch0_pred.jpg ├── train.py ├── train_batch0.jpg ├── train_batch1.jpg ├── train_batch2.jpg ├── tutorial.ipynb ├── utils ├── __init__.py ├── activations.py ├── datasets.py ├── google_utils.py ├── torch_utils.py ├── utils.py └── video2rgb.py └── weights ├── best.pt ├── download_weights.sh ├── last.pt └── yolov5s.pt /.dockerignore: -------------------------------------------------------------------------------- 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 | **/*.onnx 18 | **/*.mlmodel 19 | 20 | 21 | # Below Copied From .gitignore ----------------------------------------------------------------------------------------- 22 | # Below Copied From .gitignore ----------------------------------------------------------------------------------------- 23 | 24 | 25 | # GitHub Python GitIgnore ---------------------------------------------------------------------------------------------- 26 | # Byte-compiled / optimized / DLL files 27 | __pycache__/ 28 | *.py[cod] 29 | *$py.class 30 | 31 | # C extensions 32 | *.so 33 | 34 | # Distribution / packaging 35 | .Python 36 | env/ 37 | build/ 38 | develop-eggs/ 39 | dist/ 40 | downloads/ 41 | eggs/ 42 | .eggs/ 43 | lib/ 44 | lib64/ 45 | parts/ 46 | sdist/ 47 | var/ 48 | wheels/ 49 | *.egg-info/ 50 | .installed.cfg 51 | *.egg 52 | 53 | # PyInstaller 54 | # Usually these files are written by a python script from a template 55 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 56 | *.manifest 57 | *.spec 58 | 59 | # Installer logs 60 | pip-log.txt 61 | pip-delete-this-directory.txt 62 | 63 | # Unit test / coverage reports 64 | htmlcov/ 65 | .tox/ 66 | .coverage 67 | .coverage.* 68 | .cache 69 | nosetests.xml 70 | coverage.xml 71 | *.cover 72 | .hypothesis/ 73 | 74 | # Translations 75 | *.mo 76 | *.pot 77 | 78 | # Django stuff: 79 | *.log 80 | local_settings.py 81 | 82 | # Flask stuff: 83 | instance/ 84 | .webassets-cache 85 | 86 | # Scrapy stuff: 87 | .scrapy 88 | 89 | # Sphinx documentation 90 | docs/_build/ 91 | 92 | # PyBuilder 93 | target/ 94 | 95 | # Jupyter Notebook 96 | .ipynb_checkpoints 97 | 98 | # pyenv 99 | .python-version 100 | 101 | # celery beat schedule file 102 | celerybeat-schedule 103 | 104 | # SageMath parsed files 105 | *.sage.py 106 | 107 | # dotenv 108 | .env 109 | 110 | # virtualenv 111 | .venv 112 | venv/ 113 | ENV/ 114 | 115 | # Spyder project settings 116 | .spyderproject 117 | .spyproject 118 | 119 | # Rope project settings 120 | .ropeproject 121 | 122 | # mkdocs documentation 123 | /site 124 | 125 | # mypy 126 | .mypy_cache/ 127 | 128 | 129 | # https://github.com/github/gitignore/blob/master/Global/macOS.gitignore ----------------------------------------------- 130 | 131 | # General 132 | .DS_Store 133 | .AppleDouble 134 | .LSOverride 135 | 136 | # Icon must end with two \r 137 | Icon 138 | Icon? 139 | 140 | # Thumbnails 141 | ._* 142 | 143 | # Files that might appear in the root of a volume 144 | .DocumentRevisions-V100 145 | .fseventsd 146 | .Spotlight-V100 147 | .TemporaryItems 148 | .Trashes 149 | .VolumeIcon.icns 150 | .com.apple.timemachine.donotpresent 151 | 152 | # Directories potentially created on remote AFP share 153 | .AppleDB 154 | .AppleDesktop 155 | Network Trash Folder 156 | Temporary Items 157 | .apdisk 158 | 159 | 160 | # https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore 161 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm 162 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 163 | 164 | # User-specific stuff: 165 | .idea/* 166 | .idea/**/workspace.xml 167 | .idea/**/tasks.xml 168 | .idea/dictionaries 169 | .html # Bokeh Plots 170 | .pg # TensorFlow Frozen Graphs 171 | .avi # videos 172 | 173 | # Sensitive or high-churn files: 174 | .idea/**/dataSources/ 175 | .idea/**/dataSources.ids 176 | .idea/**/dataSources.local.xml 177 | .idea/**/sqlDataSources.xml 178 | .idea/**/dynamic.xml 179 | .idea/**/uiDesigner.xml 180 | 181 | # Gradle: 182 | .idea/**/gradle.xml 183 | .idea/**/libraries 184 | 185 | # CMake 186 | cmake-build-debug/ 187 | cmake-build-release/ 188 | 189 | # Mongo Explorer plugin: 190 | .idea/**/mongoSettings.xml 191 | 192 | ## File-based project format: 193 | *.iws 194 | 195 | ## Plugin-specific files: 196 | 197 | # IntelliJ 198 | out/ 199 | 200 | # mpeltonen/sbt-idea plugin 201 | .idea_modules/ 202 | 203 | # JIRA plugin 204 | atlassian-ide-plugin.xml 205 | 206 | # Cursive Clojure plugin 207 | .idea/replstate.xml 208 | 209 | # Crashlytics plugin (for Android Studio and IntelliJ) 210 | com_crashlytics_export_strings.xml 211 | crashlytics.properties 212 | crashlytics-build.properties 213 | fabric.properties 214 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Start FROM Nvidia PyTorch image https://ngc.nvidia.com/catalog/containers/nvidia:pytorch 2 | FROM nvcr.io/nvidia/pytorch:20.03-py3 3 | 4 | # Create working directory 5 | RUN mkdir -p /usr/src/app 6 | WORKDIR /usr/src/app 7 | 8 | # Copy contents 9 | COPY . /usr/src/app 10 | 11 | # Install dependencies (pip or conda) 12 | #RUN pip install -r requirements.txt 13 | RUN pip install -U gsutil 14 | 15 | # Copy weights 16 | #RUN python3 -c "from models import *; \ 17 | #attempt_download('weights/yolov5s.pt'); \ 18 | #attempt_download('weights/yolov5m.pt'); \ 19 | #attempt_download('weights/yolov5l.pt')" 20 | 21 | 22 | # --------------------------------------------------- Extras Below --------------------------------------------------- 23 | 24 | # Build and Push 25 | # t=ultralytics/yolov5:latest && sudo docker build -t $t . && sudo docker push $t 26 | 27 | # Pull and Run 28 | # t=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host $t bash 29 | 30 | # Pull and Run with local directory access 31 | # t=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all -v "$(pwd)"/coco:/usr/src/coco $t bash 32 | 33 | # Kill all 34 | # sudo docker kill "$(sudo docker ps -q)" 35 | 36 | # Kill all image-based 37 | # sudo docker kill $(sudo docker ps -a -q --filter ancestor=ultralytics/yolov5:latest) 38 | 39 | # Run bash for loop 40 | # sudo docker run --gpus all --ipc=host ultralytics/yolov5:latest while true; do python3 train.py --evolve; done 41 | 42 | # Bash into running container 43 | # sudo docker container exec -it ba65811811ab bash 44 | # python -c "from utils.utils import *; create_backbone('weights/last.pt')" && gsutil cp weights/backbone.pt gs://* 45 | 46 | # Bash into stopped container 47 | # sudo docker commit 6d525e299258 user/test_image && sudo docker run -it --gpus all --ipc=host -v "$(pwd)"/coco:/usr/src/coco --entrypoint=sh user/test_image 48 | 49 | # Clean up 50 | # docker system prune -a --volumes -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 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 | 635 | Copyright (C) 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 . 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 | Copyright (C) 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 | . 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 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 |   4 | 5 | This repository represents Ultralytics open-source research into future object detection methods, and incorporates our lessons learned and best practices evolved over training thousands of models on custom client datasets with our previous YOLO repository https://github.com/ultralytics/yolov3. **All code and models are under active development, and are subject to modification or deletion without notice.** Use at your own risk. 6 | 7 | ** GPU Speed measures end-to-end time per image averaged over 5000 COCO val2017 images using a V100 GPU with batch size 8, and includes image preprocessing, PyTorch FP16 inference, postprocessing and NMS. 8 | 9 | - **June 22, 2020**: [PANet](https://arxiv.org/abs/1803.01534) updates: increased layers, reduced parameters, faster inference and improved mAP [364fcfd](https://github.com/ultralytics/yolov5/commit/364fcfd7dba53f46edd4f04c037a039c0a287972). 10 | - **June 19, 2020**: [FP16](https://pytorch.org/docs/stable/nn.html#torch.nn.Module.half) as new default for smaller checkpoints and faster inference [d4c6674](https://github.com/ultralytics/yolov5/commit/d4c6674c98e19df4c40e33a777610a18d1961145). 11 | - **June 9, 2020**: [CSP](https://github.com/WongKinYiu/CrossStagePartialNetworks) updates: improved speed, size, and accuracy. Credit to @WongKinYiu for excellent CSP work. 12 | - **May 27, 2020**: Public release of repo. YOLOv5 models are SOTA among all known YOLO implementations, YOLOv5 family will be undergoing architecture research and development over Q2/Q3 2020 to increase performance. Updates may include [CSP](https://github.com/WongKinYiu/CrossStagePartialNetworks) bottlenecks, [YOLOv4](https://github.com/AlexeyAB/darknet) features, as well as PANet or BiFPN heads. 13 | - **April 1, 2020**: Begin development of a 100% PyTorch, scaleable YOLOv3/4-based group of future models, in a range of compound-scaled sizes. Models will be defined by new user-friendly `*.yaml` files. New training methods will be simpler to start, faster to finish, and more robust to training a wider variety of custom dataset. 14 | 15 | 16 | ## Pretrained Checkpoints 17 | 18 | | Model | APval | APtest | AP50 | SpeedGPU | FPSGPU || params | FLOPS | 19 | |---------- |------ |------ |------ | -------- | ------| ------ |------ | :------: | 20 | | [YOLOv5s](https://drive.google.com/open?id=1Drs_Aiu7xx6S-ix95f9kNsA6ueKRpN2J) | 36.6 | 36.6 | 55.8 | **2.1ms** | **476** || 7.5M | 13.2B 21 | | [YOLOv5m](https://drive.google.com/open?id=1Drs_Aiu7xx6S-ix95f9kNsA6ueKRpN2J) | 43.4 | 43.4 | 62.4 | 3.0ms | 333 || 21.8M | 39.4B 22 | | [YOLOv5l](https://drive.google.com/open?id=1Drs_Aiu7xx6S-ix95f9kNsA6ueKRpN2J) | 46.6 | 46.7 | 65.4 | 3.9ms | 256 || 47.8M | 88.1B 23 | | [YOLOv5x](https://drive.google.com/open?id=1Drs_Aiu7xx6S-ix95f9kNsA6ueKRpN2J) | **48.4** | **48.4** | **66.9** | 6.1ms | 164 || 89.0M | 166.4B 24 | | [YOLOv3-SPP](https://drive.google.com/open?id=1Drs_Aiu7xx6S-ix95f9kNsA6ueKRpN2J) | 45.6 | 45.5 | 65.2 | 4.5ms | 222 || 63.0M | 118.0B 25 | 26 | 27 | ** APtest denotes COCO [test-dev2017](http://cocodataset.org/#upload) server results, all other AP results in the table denote val2017 accuracy. 28 | ** All AP numbers are for single-model single-scale without ensemble or test-time augmentation. Reproduce by `python test.py --img 736 --conf 0.001` 29 | ** SpeedGPU measures end-to-end time per image averaged over 5000 COCO val2017 images using a GCP [n1-standard-16](https://cloud.google.com/compute/docs/machine-types#n1_standard_machine_types) instance with one V100 GPU, and includes image preprocessing, PyTorch FP16 image inference at --batch-size 32 --img-size 640, postprocessing and NMS. Average NMS time included in this chart is 1-2ms/img. Reproduce by `python test.py --img 640 --conf 0.1` 30 | ** All checkpoints are trained to 300 epochs with default settings and hyperparameters (no autoaugmentation). 31 | 32 | 33 | ## Requirements 34 | 35 | Python 3.7 or later with all `requirements.txt` dependencies installed, including `torch >= 1.5`. To install run: 36 | ```bash 37 | $ pip install -U -r requirements.txt 38 | ``` 39 | 40 | 41 | ## Tutorials 42 | 43 | * [Notebook](https://github.com/ultralytics/yolov5/blob/master/tutorial.ipynb) Open In Colab 44 | * [Train Custom Data](https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data) 45 | * [Google Cloud Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/GCP-Quickstart) 46 | * [Docker Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/Docker-Quickstart) ![Docker Pulls](https://img.shields.io/docker/pulls/ultralytics/yolov5?logo=docker) 47 | 48 | 49 | ## Inference 50 | 51 | Inference can be run on most common media formats. Model [checkpoints](https://drive.google.com/open?id=1Drs_Aiu7xx6S-ix95f9kNsA6ueKRpN2J) are downloaded automatically if available. Results are saved to `./inference/output`. 52 | ```bash 53 | $ python detect.py --source file.jpg # image 54 | file.mp4 # video 55 | ./dir # directory 56 | 0 # webcam 57 | rtsp://170.93.143.139/rtplive/470011e600ef003a004ee33696235daa # rtsp stream 58 | http://112.50.243.8/PLTV/88888888/224/3221225900/1.m3u8 # http stream 59 | ``` 60 | 61 | To run inference on examples in the `./inference/images` folder: 62 | 63 | ```bash 64 | $ python detect.py --source ./inference/images/ --weights yolov5s.pt --conf 0.4 65 | 66 | Namespace(agnostic_nms=False, augment=False, classes=None, conf_thres=0.4, device='', fourcc='mp4v', half=False, img_size=640, iou_thres=0.5, output='inference/output', save_txt=False, source='./inference/images/', view_img=False, weights='yolov5s.pt') 67 | Using CUDA device0 _CudaDeviceProperties(name='Tesla P100-PCIE-16GB', total_memory=16280MB) 68 | 69 | Downloading https://drive.google.com/uc?export=download&id=1R5T6rIyy3lLwgFXNms8whc-387H0tMQO as yolov5s.pt... Done (2.6s) 70 | 71 | image 1/2 inference/images/bus.jpg: 640x512 3 persons, 1 buss, Done. (0.009s) 72 | image 2/2 inference/images/zidane.jpg: 384x640 2 persons, 2 ties, Done. (0.009s) 73 | Results saved to /content/yolov5/inference/output 74 | ``` 75 | 76 | 77 | 78 | ## Reproduce Our Training 79 | 80 | Download [COCO](https://github.com/ultralytics/yolov5/blob/master/data/get_coco2017.sh), install [Apex](https://github.com/NVIDIA/apex) and run command below. Training times for YOLOv5s/m/l/x are 2/4/6/8 days on a single V100 (multi-GPU times faster). Use the largest `--batch-size` your GPU allows (batch sizes shown for 16 GB devices). 81 | ```bash 82 | $ python train.py --data coco.yaml --cfg yolov5s.yaml --weights '' --batch-size 64 83 | yolov5m 48 84 | yolov5l 32 85 | yolov5x 16 86 | ``` 87 | 88 | 89 | 90 | ## Reproduce Our Environment 91 | 92 | To access an up-to-date working environment (with all dependencies including CUDA/CUDNN, Python and PyTorch preinstalled), consider a: 93 | 94 | - **GCP** Deep Learning VM with $300 free credit offer: See our [GCP Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/GCP-Quickstart) 95 | - **Google Colab Notebook** with 12 hours of free GPU time. Open In Colab 96 | - **Docker Image** https://hub.docker.com/r/ultralytics/yolov5. See [Docker Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/Docker-Quickstart) ![Docker Pulls](https://img.shields.io/docker/pulls/ultralytics/yolov5?logo=docker) 97 | 98 | 99 | ## Citation 100 | 101 | [![DOI](https://zenodo.org/badge/146165888.svg)](https://zenodo.org/badge/latestdoi/146165888) 102 | 103 | 104 | ## About Us 105 | 106 | Ultralytics is a U.S.-based particle physics and AI startup with over 6 years of expertise supporting government, academic and business clients. We offer a wide range of vision AI services, spanning from simple expert advice up to delivery of fully customized, end-to-end production solutions, including: 107 | - **Cloud-based AI** surveillance systems operating on **hundreds of HD video streams in realtime.** 108 | - **Edge AI** integrated into custom iOS and Android apps for realtime **30 FPS video inference.** 109 | - **Custom data training**, hyperparameter evolution, and model exportation to any destination. 110 | 111 | For business inquiries and professional support requests please visit us at https://www.ultralytics.com. 112 | 113 | 114 | ## Contact 115 | 116 | **Issues should be raised directly in the repository.** For business inquiries or professional support requests please visit https://www.ultralytics.com or email Glenn Jocher at glenn.jocher@ultralytics.com. 117 | -------------------------------------------------------------------------------- /data/coco.yaml: -------------------------------------------------------------------------------- 1 | # COCO 2017 dataset http://cocodataset.org 2 | # Download command: bash yolov5/data/get_coco2017.sh 3 | # Train command: python train.py --data ./data/coco.yaml 4 | # Dataset should be placed next to yolov5 folder: 5 | # /parent_folder 6 | # /coco 7 | # /yolov5 8 | 9 | 10 | # train and val datasets (image directory or *.txt file with image paths) 11 | train: ../coco/train2017.txt # 118k images 12 | val: ../coco/val2017.txt # 5k images 13 | test: ../coco/test-dev2017.txt # 20k images for submission to https://competitions.codalab.org/competitions/20794 14 | 15 | # number of classes 16 | nc: 80 17 | 18 | # class names 19 | names: ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 20 | 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 21 | 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 22 | 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 23 | 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 24 | 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 25 | 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 26 | 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 27 | 'hair drier', 'toothbrush'] 28 | 29 | # Print classes 30 | # with open('data/coco.yaml') as f: 31 | # d = yaml.load(f, Loader=yaml.FullLoader) # dict 32 | # for i, x in enumerate(d['names']): 33 | # print(i, x) -------------------------------------------------------------------------------- /data/coco128.yaml: -------------------------------------------------------------------------------- 1 | # COCO 2017 dataset http://cocodataset.org - first 128 training images 2 | # Download command: python -c "from yolov5.utils.google_utils import gdrive_download; gdrive_download('1n_oKgR81BJtqk75b00eAjdv03qVCQn2f','coco128.zip')" 3 | # Train command: python train.py --data ./data/coco128.yaml 4 | # Dataset should be placed next to yolov5 folder: 5 | # /parent_folder 6 | # /coco128 7 | # /yolov5 8 | 9 | 10 | # train and val datasets (image directory or *.txt file with image paths) 11 | train: ../coco128/images/train2017/ 12 | val: ../coco128/images/train2017/ 13 | 14 | # number of classes 15 | nc: 80 16 | 17 | # class names 18 | names: ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 19 | 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 20 | 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 21 | 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 22 | 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 23 | 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 24 | 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 25 | 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 26 | 'hair drier', 'toothbrush'] -------------------------------------------------------------------------------- /data/drive.yaml: -------------------------------------------------------------------------------- 1 | train: G:\drive\images\train2017 2 | val: G:\drive\images\val2017 3 | 4 | # number of classes 5 | nc: 3 6 | 7 | # class names 8 | names: ['smoke', 'call', 'drink'] 9 | 10 | -------------------------------------------------------------------------------- /data/get_coco2017.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Zip coco folder 3 | # zip -r coco.zip coco 4 | # tar -czvf coco.tar.gz coco 5 | 6 | # Download labels from Google Drive, accepting presented query 7 | filename="coco2017labels.zip" 8 | fileid="1cXZR_ckHki6nddOmcysCuuJFM--T-Q6L" 9 | curl -c ./cookie -s -L "https://drive.google.com/uc?export=download&id=${fileid}" > /dev/null 10 | curl -Lb ./cookie "https://drive.google.com/uc?export=download&confirm=`awk '/download/ {print $NF}' ./cookie`&id=${fileid}" -o ${filename} 11 | rm ./cookie 12 | 13 | # Unzip labels 14 | unzip -q ${filename} # for coco.zip 15 | # tar -xzf ${filename} # for coco.tar.gz 16 | rm ${filename} 17 | 18 | # Download and unzip images 19 | cd coco/images 20 | f="train2017.zip" && curl http://images.cocodataset.org/zips/$f -o $f && unzip -q $f && rm $f # 19G, 118k images 21 | f="val2017.zip" && curl http://images.cocodataset.org/zips/$f -o $f && unzip -q $f && rm $f # 1G, 5k images 22 | # f="test2017.zip" && curl http://images.cocodataset.org/zips/$f -o $f && unzip -q $f && rm $f # 7G, 41k images 23 | 24 | # cd out 25 | cd ../.. 26 | -------------------------------------------------------------------------------- /detect.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | import torch.backends.cudnn as cudnn 4 | 5 | from utils import google_utils 6 | from utils.datasets import * 7 | from utils.utils import * 8 | 9 | 10 | def detect(save_img=False): 11 | out, source, weights, view_img, save_txt, imgsz = \ 12 | opt.output, opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size 13 | webcam = source == '0' or source.startswith('rtsp') or source.startswith('http') or source.endswith('.txt') 14 | 15 | # Initialize 16 | device = torch_utils.select_device(opt.device) 17 | if os.path.exists(out): 18 | shutil.rmtree(out) # delete output folder 19 | os.makedirs(out) # make new output folder 20 | half = device.type != 'cpu' # half precision only supported on CUDA 21 | 22 | # Load model 23 | google_utils.attempt_download(weights) 24 | model = torch.load(weights, map_location=device)['model'].float() # load to FP32 25 | # torch.save(torch.load(weights, map_location=device), weights) # update model if SourceChangeWarning 26 | # model.fuse() 27 | model.to(device).eval() 28 | if half: 29 | model.half() # to FP16 30 | 31 | # Second-stage classifier 32 | classify = False 33 | if classify: 34 | modelc = torch_utils.load_classifier(name='resnet101', n=2) # initialize 35 | modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']) # load weights 36 | modelc.to(device).eval() 37 | 38 | # Set Dataloader 39 | vid_path, vid_writer = None, None 40 | if webcam: 41 | view_img = True 42 | cudnn.benchmark = True # set True to speed up constant image size inference 43 | dataset = LoadStreams(source, img_size=imgsz) 44 | else: 45 | save_img = True 46 | dataset = LoadImages(source, img_size=imgsz) 47 | 48 | # Get names and colors 49 | names = model.names if hasattr(model, 'names') else model.modules.names 50 | colors = [[random.randint(0, 255) for _ in range(3)] for _ in range(len(names))] 51 | 52 | # Run inference 53 | t0 = time.time() 54 | img = torch.zeros((1, 3, imgsz, imgsz), device=device) # init img 55 | _ = model(img.half() if half else img) if device.type != 'cpu' else None # run once 56 | for path, img, im0s, vid_cap in dataset: 57 | img = torch.from_numpy(img).to(device) 58 | img = img.half() if half else img.float() # uint8 to fp16/32 59 | img /= 255.0 # 0 - 255 to 0.0 - 1.0 60 | if img.ndimension() == 3: 61 | img = img.unsqueeze(0) 62 | 63 | # Inference 64 | t1 = torch_utils.time_synchronized() 65 | pred = model(img, augment=opt.augment)[0] 66 | 67 | # Apply NMS 68 | pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms) 69 | t2 = torch_utils.time_synchronized() 70 | 71 | # Apply Classifier 72 | if classify: 73 | pred = apply_classifier(pred, modelc, img, im0s) 74 | 75 | # Process detections 76 | for i, det in enumerate(pred): # detections per image 77 | if webcam: # batch_size >= 1 78 | p, s, im0 = path[i], '%g: ' % i, im0s[i].copy() 79 | else: 80 | p, s, im0 = path, '', im0s 81 | 82 | save_path = str(Path(out) / Path(p).name) 83 | s += '%gx%g ' % img.shape[2:] # print string 84 | gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] #  normalization gain whwh 85 | if det is not None and len(det): 86 | # Rescale boxes from img_size to im0 size 87 | det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round() 88 | 89 | # Print results 90 | for c in det[:, -1].unique(): 91 | n = (det[:, -1] == c).sum() # detections per class 92 | s += '%g %ss, ' % (n, names[int(c)]) # add to string 93 | 94 | # Write results 95 | for *xyxy, conf, cls in det: 96 | if save_txt: # Write to file 97 | xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh 98 | with open(save_path[:save_path.rfind('.')] + '.txt', 'a') as file: 99 | file.write(('%g ' * 5 + '\n') % (cls, *xywh)) # label format 100 | 101 | if save_img or view_img: # Add bbox to image 102 | label = '%s %.2f' % (names[int(cls)], conf) 103 | plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3) 104 | 105 | # Print time (inference + NMS) 106 | print('%sDone. (%.3fs)' % (s, t2 - t1)) 107 | 108 | # Stream results 109 | if view_img: 110 | cv2.imshow(p, im0) 111 | if cv2.waitKey(1) == ord('q'): # q to quit 112 | raise StopIteration 113 | 114 | # Save results (image with detections) 115 | if save_img: 116 | if dataset.mode == 'images': 117 | cv2.imwrite(save_path, im0) 118 | else: 119 | if vid_path != save_path: # new video 120 | vid_path = save_path 121 | if isinstance(vid_writer, cv2.VideoWriter): 122 | vid_writer.release() # release previous video writer 123 | 124 | fps = vid_cap.get(cv2.CAP_PROP_FPS) 125 | w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) 126 | h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) 127 | vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*opt.fourcc), fps, (w, h)) 128 | vid_writer.write(im0) 129 | 130 | if save_txt or save_img: 131 | print('Results saved to %s' % os.getcwd() + os.sep + out) 132 | if platform == 'darwin': # MacOS 133 | os.system('open ' + save_path) 134 | 135 | print('Done. (%.3fs)' % (time.time() - t0)) 136 | 137 | 138 | if __name__ == '__main__': 139 | parser = argparse.ArgumentParser() 140 | parser.add_argument('--weights', type=str, default='weights/best.pt', help='model.pt path') 141 | parser.add_argument('--source', type=str, default='inference/images', help='source') # file/folder, 0 for webcam 142 | parser.add_argument('--output', type=str, default='inference/output', help='output folder') # output folder 143 | parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)') 144 | parser.add_argument('--conf-thres', type=float, default=0.4, help='object confidence threshold') 145 | parser.add_argument('--iou-thres', type=float, default=0.5, help='IOU threshold for NMS') 146 | parser.add_argument('--fourcc', type=str, default='mp4v', help='output video codec (verify ffmpeg support)') 147 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') 148 | parser.add_argument('--view-img', action='store_true', help='display results') 149 | parser.add_argument('--save-txt', action='store_true', help='save results to *.txt') 150 | parser.add_argument('--classes', nargs='+', type=int, help='filter by class') 151 | parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS') 152 | parser.add_argument('--augment', action='store_true', help='augmented inference') 153 | opt = parser.parse_args() 154 | opt.img_size = check_img_size(opt.img_size) 155 | print(opt) 156 | 157 | with torch.no_grad(): 158 | detect() 159 | -------------------------------------------------------------------------------- /hubconf.py: -------------------------------------------------------------------------------- 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 | 10 | import os 11 | 12 | import torch 13 | 14 | from models.yolo import Model 15 | from utils import google_utils 16 | 17 | 18 | def create(name, pretrained, channels, classes): 19 | """Creates a specified YOLOv5 model 20 | 21 | Arguments: 22 | name (str): name of model, i.e. 'yolov5s' 23 | pretrained (bool): load pretrained weights into the model 24 | channels (int): number of input channels 25 | classes (int): number of model classes 26 | 27 | Returns: 28 | pytorch model 29 | """ 30 | config = os.path.join(os.path.dirname(__file__), 'models', '%s.yaml' % name) # model.yaml path 31 | model = Model(config, channels, classes) 32 | if pretrained: 33 | ckpt = '%s.pt' % name # checkpoint filename 34 | google_utils.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 | 41 | def yolov5s(pretrained=False, channels=3, classes=80): 42 | """YOLOv5-small model from https://github.com/ultralytics/yolov5 43 | 44 | Arguments: 45 | pretrained (bool): load pretrained weights into the model, default=False 46 | channels (int): number of input channels, default=3 47 | classes (int): number of model classes, default=80 48 | 49 | Returns: 50 | pytorch model 51 | """ 52 | return create('yolov5s', pretrained, channels, classes) 53 | 54 | 55 | def yolov5m(pretrained=False, channels=3, classes=80): 56 | """YOLOv5-medium model from https://github.com/ultralytics/yolov5 57 | 58 | Arguments: 59 | pretrained (bool): load pretrained weights into the model, default=False 60 | channels (int): number of input channels, default=3 61 | classes (int): number of model classes, default=80 62 | 63 | Returns: 64 | pytorch model 65 | """ 66 | return create('yolov5m', pretrained, channels, classes) 67 | 68 | 69 | def yolov5l(pretrained=False, channels=3, classes=80): 70 | """YOLOv5-large model from https://github.com/ultralytics/yolov5 71 | 72 | Arguments: 73 | pretrained (bool): load pretrained weights into the model, default=False 74 | channels (int): number of input channels, default=3 75 | classes (int): number of model classes, default=80 76 | 77 | Returns: 78 | pytorch model 79 | """ 80 | return create('yolov5l', pretrained, channels, classes) 81 | 82 | 83 | def yolov5x(pretrained=False, channels=3, classes=80): 84 | """YOLOv5-xlarge model from https://github.com/ultralytics/yolov5 85 | 86 | Arguments: 87 | pretrained (bool): load pretrained weights into the model, default=False 88 | channels (int): number of input channels, default=3 89 | classes (int): number of model classes, default=80 90 | 91 | Returns: 92 | pytorch model 93 | """ 94 | return create('yolov5x', pretrained, channels, classes) 95 | -------------------------------------------------------------------------------- /labels.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lieweiAI/action-detection/b8b174d363cf3dac4c94c7736126edc91838c81f/labels.png -------------------------------------------------------------------------------- /models/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lieweiAI/action-detection/b8b174d363cf3dac4c94c7736126edc91838c81f/models/__init__.py -------------------------------------------------------------------------------- /models/common.py: -------------------------------------------------------------------------------- 1 | # This file contains modules common to various models 2 | 3 | 4 | from utils.utils import * 5 | 6 | 7 | def DWConv(c1, c2, k=1, s=1, act=True): 8 | # Depthwise convolution 9 | return Conv(c1, c2, k, s, g=math.gcd(c1, c2), act=act) 10 | 11 | 12 | class Conv(nn.Module): 13 | # Standard convolution 14 | def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups 15 | super(Conv, self).__init__() 16 | self.conv = nn.Conv2d(c1, c2, k, s, k // 2, groups=g, bias=False) 17 | self.bn = nn.BatchNorm2d(c2) 18 | self.act = nn.LeakyReLU(0.1, inplace=True) if act else nn.Identity() 19 | 20 | def forward(self, x): 21 | return self.act(self.bn(self.conv(x))) 22 | 23 | def fuseforward(self, x): 24 | return self.act(self.conv(x)) 25 | 26 | 27 | class Bottleneck(nn.Module): 28 | # Standard bottleneck 29 | def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion 30 | super(Bottleneck, self).__init__() 31 | c_ = int(c2 * e) # hidden channels 32 | self.cv1 = Conv(c1, c_, 1, 1) 33 | self.cv2 = Conv(c_, c2, 3, 1, g=g) 34 | self.add = shortcut and c1 == c2 35 | 36 | def forward(self, x): 37 | return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x)) 38 | 39 | 40 | class BottleneckCSP(nn.Module): 41 | # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks 42 | def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion 43 | super(BottleneckCSP, self).__init__() 44 | c_ = int(c2 * e) # hidden channels 45 | self.cv1 = Conv(c1, c_, 1, 1) 46 | self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False) 47 | self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False) 48 | self.cv4 = Conv(c2, c2, 1, 1) 49 | self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3) 50 | self.act = nn.LeakyReLU(0.1, inplace=True) 51 | self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)]) 52 | 53 | def forward(self, x): 54 | y1 = self.cv3(self.m(self.cv1(x))) 55 | y2 = self.cv2(x) 56 | return self.cv4(self.act(self.bn(torch.cat((y1, y2), dim=1)))) 57 | 58 | 59 | class SPP(nn.Module): 60 | # Spatial pyramid pooling layer used in YOLOv3-SPP 61 | def __init__(self, c1, c2, k=(5, 9, 13)): 62 | super(SPP, self).__init__() 63 | c_ = c1 // 2 # hidden channels 64 | self.cv1 = Conv(c1, c_, 1, 1) 65 | self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1) 66 | self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k]) 67 | 68 | def forward(self, x): 69 | x = self.cv1(x) 70 | return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1)) 71 | 72 | 73 | class Flatten(nn.Module): 74 | # Use after nn.AdaptiveAvgPool2d(1) to remove last 2 dimensions 75 | def forward(self, x): 76 | return x.view(x.size(0), -1) 77 | 78 | 79 | class Focus(nn.Module): 80 | # Focus wh information into c-space 81 | def __init__(self, c1, c2, k=1): 82 | super(Focus, self).__init__() 83 | self.conv = Conv(c1 * 4, c2, k, 1) 84 | 85 | def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2) 86 | return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1)) 87 | 88 | 89 | class Concat(nn.Module): 90 | # Concatenate a list of tensors along dimension 91 | def __init__(self, dimension=1): 92 | super(Concat, self).__init__() 93 | self.d = dimension 94 | 95 | def forward(self, x): 96 | return torch.cat(x, self.d) 97 | -------------------------------------------------------------------------------- /models/experimental.py: -------------------------------------------------------------------------------- 1 | from models.common import * 2 | 3 | 4 | class Sum(nn.Module): 5 | # Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070 6 | def __init__(self, n, weight=False): # n: number of inputs 7 | super(Sum, self).__init__() 8 | self.weight = weight # apply weights boolean 9 | self.iter = range(n - 1) # iter object 10 | if weight: 11 | self.w = nn.Parameter(-torch.arange(1., n) / 2, requires_grad=True) # layer weights 12 | 13 | def forward(self, x): 14 | y = x[0] # no weight 15 | if self.weight: 16 | w = torch.sigmoid(self.w) * 2 17 | for i in self.iter: 18 | y = y + x[i + 1] * w[i] 19 | else: 20 | for i in self.iter: 21 | y = y + x[i + 1] 22 | return y 23 | 24 | 25 | class GhostConv(nn.Module): 26 | # Ghost Convolution https://github.com/huawei-noah/ghostnet 27 | def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups 28 | super(GhostConv, self).__init__() 29 | c_ = c2 // 2 # hidden channels 30 | self.cv1 = Conv(c1, c_, k, s, g, act) 31 | self.cv2 = Conv(c_, c_, 5, 1, c_, act) 32 | 33 | def forward(self, x): 34 | y = self.cv1(x) 35 | return torch.cat([y, self.cv2(y)], 1) 36 | 37 | 38 | class GhostBottleneck(nn.Module): 39 | # Ghost Bottleneck https://github.com/huawei-noah/ghostnet 40 | def __init__(self, c1, c2, k, s): 41 | super(GhostBottleneck, self).__init__() 42 | c_ = c2 // 2 43 | self.conv = nn.Sequential(GhostConv(c1, c_, 1, 1), # pw 44 | DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw 45 | GhostConv(c_, c2, 1, 1, act=False)) # pw-linear 46 | self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False), 47 | Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity() 48 | 49 | def forward(self, x): 50 | return self.conv(x) + self.shortcut(x) 51 | 52 | 53 | class ConvPlus(nn.Module): 54 | # Plus-shaped convolution 55 | def __init__(self, c1, c2, k=3, s=1, g=1, bias=True): # ch_in, ch_out, kernel, stride, groups 56 | super(ConvPlus, self).__init__() 57 | self.cv1 = nn.Conv2d(c1, c2, (k, 1), s, (k // 2, 0), groups=g, bias=bias) 58 | self.cv2 = nn.Conv2d(c1, c2, (1, k), s, (0, k // 2), groups=g, bias=bias) 59 | 60 | def forward(self, x): 61 | return self.cv1(x) + self.cv2(x) 62 | 63 | 64 | class MixConv2d(nn.Module): 65 | # Mixed Depthwise Conv https://arxiv.org/abs/1907.09595 66 | def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): 67 | super(MixConv2d, self).__init__() 68 | groups = len(k) 69 | if equal_ch: # equal c_ per group 70 | i = torch.linspace(0, groups - 1E-6, c2).floor() # c2 indices 71 | c_ = [(i == g).sum() for g in range(groups)] # intermediate channels 72 | else: # equal weight.numel() per group 73 | b = [c2] + [0] * groups 74 | a = np.eye(groups + 1, groups, k=-1) 75 | a -= np.roll(a, 1, axis=1) 76 | a *= np.array(k) ** 2 77 | a[0] = 1 78 | c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b 79 | 80 | self.m = nn.ModuleList([nn.Conv2d(c1, int(c_[g]), k[g], s, k[g] // 2, bias=False) for g in range(groups)]) 81 | self.bn = nn.BatchNorm2d(c2) 82 | self.act = nn.LeakyReLU(0.1, inplace=True) 83 | 84 | def forward(self, x): 85 | return x + self.act(self.bn(torch.cat([m(x) for m in self.m], 1))) 86 | -------------------------------------------------------------------------------- /models/onnx_export.py: -------------------------------------------------------------------------------- 1 | """Exports a pytorch *.pt model to *.onnx format 2 | 3 | Usage: 4 | $ export PYTHONPATH="$PWD" && python models/onnx_export.py --weights ./weights/yolov5s.pt --img 640 --batch 1 5 | """ 6 | 7 | import argparse 8 | 9 | import onnx 10 | 11 | from models.common import * 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 | print(opt) 20 | 21 | # Parameters 22 | f = opt.weights.replace('.pt', '.onnx') # onnx filename 23 | img = torch.zeros((opt.batch_size, 3, *opt.img_size)) # image size, (1, 3, 320, 192) iDetection 24 | 25 | # Load pytorch model 26 | google_utils.attempt_download(opt.weights) 27 | model = torch.load(opt.weights, map_location=torch.device('cpu'))['model'].float() 28 | model.eval() 29 | model.fuse() 30 | 31 | # Export to onnx 32 | model.model[-1].export = True # set Detect() layer export=True 33 | _ = model(img) # dry run 34 | torch.onnx.export(model, img, f, verbose=False, opset_version=11, input_names=['images'], 35 | output_names=['output']) # output_names=['classes', 'boxes'] 36 | 37 | # Check onnx model 38 | model = onnx.load(f) # load onnx model 39 | onnx.checker.check_model(model) # check onnx model 40 | print(onnx.helper.printable_graph(model.graph)) # print a human readable representation of the graph 41 | print('Export complete. ONNX model saved to %s\nView with https://github.com/lutzroeder/netron' % f) 42 | -------------------------------------------------------------------------------- /models/yolo.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | from models.experimental import * 4 | 5 | 6 | class Detect(nn.Module): 7 | def __init__(self, nc=80, anchors=()): # detection layer 8 | super(Detect, self).__init__() 9 | self.stride = None # strides computed during build 10 | self.nc = nc # number of classes 11 | self.no = nc + 5 # number of outputs per anchor 12 | self.nl = len(anchors) # number of detection layers 13 | self.na = len(anchors[0]) // 2 # number of anchors 14 | self.grid = [torch.zeros(1)] * self.nl # init grid 15 | a = torch.tensor(anchors).float().view(self.nl, -1, 2) 16 | self.register_buffer('anchors', a) # shape(nl,na,2) 17 | self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2) 18 | self.export = False # onnx export 19 | 20 | def forward(self, x): 21 | # x = x.copy() # for profiling 22 | z = [] # inference output 23 | self.training |= self.export 24 | for i in range(self.nl): 25 | bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85) 26 | x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous() 27 | 28 | if not self.training: # inference 29 | if self.grid[i].shape[2:4] != x[i].shape[2:4]: 30 | self.grid[i] = self._make_grid(nx, ny).to(x[i].device) 31 | 32 | y = x[i].sigmoid() 33 | y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i].to(x[i].device)) * self.stride[i] # xy 34 | y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh 35 | z.append(y.view(bs, -1, self.no)) 36 | 37 | return x if self.training else (torch.cat(z, 1), x) 38 | 39 | @staticmethod 40 | def _make_grid(nx=20, ny=20): 41 | yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)]) 42 | return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float() 43 | 44 | 45 | class Model(nn.Module): 46 | def __init__(self, model_cfg='yolov5s.yaml', ch=3, nc=None): # model, input channels, number of classes 47 | super(Model, self).__init__() 48 | if type(model_cfg) is dict: 49 | self.md = model_cfg # model dict 50 | else: # is *.yaml 51 | with open(model_cfg) as f: 52 | self.md = yaml.load(f, Loader=yaml.FullLoader) # model dict 53 | 54 | # Define model 55 | if nc: 56 | self.md['nc'] = nc # override yaml value 57 | self.model, self.save = parse_model(self.md, ch=[ch]) # model, savelist, ch_out 58 | # print([x.shape for x in self.forward(torch.zeros(1, ch, 64, 64))]) 59 | 60 | # Build strides, anchors 61 | m = self.model[-1] # Detect() 62 | m.stride = torch.tensor([128 / x.shape[-2] for x in self.forward(torch.zeros(1, ch, 128, 128))]) # forward 63 | m.anchors /= m.stride.view(-1, 1, 1) 64 | check_anchor_order(m) 65 | self.stride = m.stride 66 | 67 | # Init weights, biases 68 | torch_utils.initialize_weights(self) 69 | self._initialize_biases() # only run once 70 | torch_utils.model_info(self) 71 | print('') 72 | 73 | def forward(self, x, augment=False, profile=False): 74 | if augment: 75 | img_size = x.shape[-2:] # height, width 76 | s = [0.83, 0.67] # scales 77 | y = [] 78 | for i, xi in enumerate((x, 79 | torch_utils.scale_img(x.flip(3), s[0]), # flip-lr and scale 80 | torch_utils.scale_img(x, s[1]), # scale 81 | )): 82 | # cv2.imwrite('img%g.jpg' % i, 255 * xi[0].numpy().transpose((1, 2, 0))[:, :, ::-1]) 83 | y.append(self.forward_once(xi)[0]) 84 | 85 | y[1][..., :4] /= s[0] # scale 86 | y[1][..., 0] = img_size[1] - y[1][..., 0] # flip lr 87 | y[2][..., :4] /= s[1] # scale 88 | return torch.cat(y, 1), None # augmented inference, train 89 | else: 90 | return self.forward_once(x, profile) # single-scale inference, train 91 | 92 | def forward_once(self, x, profile=False): 93 | y, dt = [], [] # outputs 94 | for m in self.model: 95 | if m.f != -1: # if not from previous layer 96 | 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 97 | 98 | if profile: 99 | import thop 100 | o = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # FLOPS 101 | t = torch_utils.time_synchronized() 102 | for _ in range(10): 103 | _ = m(x) 104 | dt.append((torch_utils.time_synchronized() - t) * 100) 105 | print('%10.1f%10.0f%10.1fms %-40s' % (o, m.np, dt[-1], m.type)) 106 | 107 | x = m(x) # run 108 | y.append(x if m.i in self.save else None) # save output 109 | 110 | if profile: 111 | print('%.1fms total' % sum(dt)) 112 | return x 113 | 114 | def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency 115 | # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1. 116 | m = self.model[-1] # Detect() module 117 | for f, s in zip(m.f, m.stride): #  from 118 | mi = self.model[f % m.i] 119 | b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85) 120 | b[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image) 121 | b[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls 122 | mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True) 123 | 124 | def _print_biases(self): 125 | m = self.model[-1] # Detect() module 126 | for f in sorted([x % m.i for x in m.f]): #  from 127 | b = self.model[f].bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85) 128 | print(('%g Conv2d.bias:' + '%10.3g' * 6) % (f, *b[:5].mean(1).tolist(), b[5:].mean())) 129 | 130 | # def _print_weights(self): 131 | # for m in self.model.modules(): 132 | # if type(m) is Bottleneck: 133 | # print('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights 134 | 135 | def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers 136 | print('Fusing layers...') 137 | for m in self.model.modules(): 138 | if type(m) is Conv: 139 | m.conv = torch_utils.fuse_conv_and_bn(m.conv, m.bn) # update conv 140 | m.bn = None # remove batchnorm 141 | m.forward = m.fuseforward # update forward 142 | torch_utils.model_info(self) 143 | 144 | 145 | def parse_model(md, ch): # model_dict, input_channels(3) 146 | print('\n%3s%15s%3s%10s %-40s%-30s' % ('', 'from', 'n', 'params', 'module', 'arguments')) 147 | anchors, nc, gd, gw = md['anchors'], md['nc'], md['depth_multiple'], md['width_multiple'] 148 | na = (len(anchors[0]) // 2) # number of anchors 149 | no = na * (nc + 5) # number of outputs = anchors * (classes + 5) 150 | 151 | layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out 152 | for i, (f, n, m, args) in enumerate(md['backbone'] + md['head']): # from, number, module, args 153 | m = eval(m) if isinstance(m, str) else m # eval strings 154 | for j, a in enumerate(args): 155 | try: 156 | args[j] = eval(a) if isinstance(a, str) else a # eval strings 157 | except: 158 | pass 159 | 160 | n = max(round(n * gd), 1) if n > 1 else n # depth gain 161 | if m in [nn.Conv2d, Conv, Bottleneck, SPP, DWConv, MixConv2d, Focus, ConvPlus, BottleneckCSP]: 162 | c1, c2 = ch[f], args[0] 163 | 164 | # Normal 165 | # if i > 0 and args[0] != no: # channel expansion factor 166 | # ex = 1.75 # exponential (default 2.0) 167 | # e = math.log(c2 / ch[1]) / math.log(2) 168 | # c2 = int(ch[1] * ex ** e) 169 | # if m != Focus: 170 | c2 = make_divisible(c2 * gw, 8) if c2 != no else c2 171 | 172 | # Experimental 173 | # if i > 0 and args[0] != no: # channel expansion factor 174 | # ex = 1 + gw # exponential (default 2.0) 175 | # ch1 = 32 # ch[1] 176 | # e = math.log(c2 / ch1) / math.log(2) # level 1-n 177 | # c2 = int(ch1 * ex ** e) 178 | # if m != Focus: 179 | # c2 = make_divisible(c2, 8) if c2 != no else c2 180 | 181 | args = [c1, c2, *args[1:]] 182 | if m is BottleneckCSP: 183 | args.insert(2, n) 184 | n = 1 185 | elif m is nn.BatchNorm2d: 186 | args = [ch[f]] 187 | elif m is Concat: 188 | c2 = sum([ch[-1 if x == -1 else x + 1] for x in f]) 189 | elif m is Detect: 190 | f = f or list(reversed([(-1 if j == i else j - 1) for j, x in enumerate(ch) if x == no])) 191 | else: 192 | c2 = ch[f] 193 | 194 | m_ = nn.Sequential(*[m(*args) for _ in range(n)]) if n > 1 else m(*args) # module 195 | t = str(m)[8:-2].replace('__main__.', '') # module type 196 | np = sum([x.numel() for x in m_.parameters()]) # number params 197 | m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params 198 | print('%3s%15s%3s%10.0f %-40s%-30s' % (i, f, n, np, t, args)) # print 199 | save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist 200 | layers.append(m_) 201 | ch.append(c2) 202 | return nn.Sequential(*layers), sorted(save) 203 | 204 | 205 | if __name__ == '__main__': 206 | parser = argparse.ArgumentParser() 207 | parser.add_argument('--cfg', type=str, default='yolov5m-p6.yaml', help='model.yaml') 208 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') 209 | opt = parser.parse_args() 210 | opt.cfg = check_file(opt.cfg) # check file 211 | device = torch_utils.select_device(opt.device) 212 | 213 | # Create model 214 | model = Model(opt.cfg).to(device) 215 | model.train() 216 | 217 | # Profile 218 | # img = torch.rand(8 if torch.cuda.is_available() else 1, 3, 640, 640).to(device) 219 | # y = model(img, profile=True) 220 | # print([y[0].shape] + [x.shape for x in y[1]]) 221 | 222 | # ONNX export 223 | # model.model[-1].export = True 224 | # torch.onnx.export(model, img, f.replace('.yaml', '.onnx'), verbose=True, opset_version=11) 225 | 226 | # Tensorboard 227 | # from torch.utils.tensorboard import SummaryWriter 228 | # tb_writer = SummaryWriter() 229 | # print("Run 'tensorboard --logdir=models/runs' to view tensorboard at http://localhost:6006/") 230 | # tb_writer.add_graph(model.model, img) # add model to tensorboard 231 | # tb_writer.add_image('test', img[0], dataformats='CWH') # add model to tensorboard 232 | -------------------------------------------------------------------------------- /models/yolov3-spp.yaml: -------------------------------------------------------------------------------- 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]], # 11 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]], 35 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 16 (P5/32-large) 36 | 37 | [-3, 1, Conv, [256, 1, 1]], 38 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 39 | [[-1, 8], 1, Concat, [1]], # cat backbone P4 40 | [-1, 1, Bottleneck, [512, False]], 41 | [-1, 1, Bottleneck, [512, False]], 42 | [-1, 1, Conv, [256, 1, 1]], 43 | [-1, 1, Conv, [512, 3, 1]], 44 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 24 (P4/16-medium) 45 | 46 | [-3, 1, Conv, [128, 1, 1]], 47 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 48 | [[-1, 6], 1, Concat, [1]], # cat backbone P3 49 | [-1, 1, Bottleneck, [256, False]], 50 | [-1, 2, Bottleneck, [256, False]], 51 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 30 (P3/8-small) 52 | 53 | [[], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 54 | ] 55 | -------------------------------------------------------------------------------- /models/yolov5l.yaml: -------------------------------------------------------------------------------- 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 | ] 25 | 26 | # YOLOv5 head 27 | head: 28 | [[-1, 3, BottleneckCSP, [1024, False]], # 9 29 | 30 | [-1, 1, Conv, [512, 1, 1]], 31 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 32 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 33 | [-1, 3, BottleneckCSP, [512, False]], # 13 34 | 35 | [-1, 1, Conv, [256, 1, 1]], 36 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 37 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 38 | [-1, 3, BottleneckCSP, [256, False]], 39 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 18 (P3/8-small) 40 | 41 | [-2, 1, Conv, [256, 3, 2]], 42 | [[-1, 14], 1, Concat, [1]], # cat head P4 43 | [-1, 3, BottleneckCSP, [512, False]], 44 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 22 (P4/16-medium) 45 | 46 | [-2, 1, Conv, [512, 3, 2]], 47 | [[-1, 10], 1, Concat, [1]], # cat head P5 48 | [-1, 3, BottleneckCSP, [1024, False]], 49 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 26 (P5/32-large) 50 | 51 | [[], 1, Detect, [nc, anchors]], # Detect(P5, P4, P3) 52 | ] 53 | -------------------------------------------------------------------------------- /models/yolov5m.yaml: -------------------------------------------------------------------------------- 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 | - [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 | ] 25 | 26 | # YOLOv5 head 27 | head: 28 | [[-1, 3, BottleneckCSP, [1024, False]], # 9 29 | 30 | [-1, 1, Conv, [512, 1, 1]], 31 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 32 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 33 | [-1, 3, BottleneckCSP, [512, False]], # 13 34 | 35 | [-1, 1, Conv, [256, 1, 1]], 36 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 37 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 38 | [-1, 3, BottleneckCSP, [256, False]], 39 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 18 (P3/8-small) 40 | 41 | [-2, 1, Conv, [256, 3, 2]], 42 | [[-1, 14], 1, Concat, [1]], # cat head P4 43 | [-1, 3, BottleneckCSP, [512, False]], 44 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 22 (P4/16-medium) 45 | 46 | [-2, 1, Conv, [512, 3, 2]], 47 | [[-1, 10], 1, Concat, [1]], # cat head P5 48 | [-1, 3, BottleneckCSP, [1024, False]], 49 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 26 (P5/32-large) 50 | 51 | [[], 1, Detect, [nc, anchors]], # Detect(P5, P4, P3) 52 | ] 53 | -------------------------------------------------------------------------------- /models/yolov5s.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 3 # 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 | - [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 | ] 25 | 26 | # YOLOv5 head 27 | head: 28 | [[-1, 3, BottleneckCSP, [1024, False]], # 9 29 | 30 | [-1, 1, Conv, [512, 1, 1]], 31 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 32 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 33 | [-1, 3, BottleneckCSP, [512, False]], # 13 34 | 35 | [-1, 1, Conv, [256, 1, 1]], 36 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 37 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 38 | [-1, 3, BottleneckCSP, [256, False]], 39 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 18 (P3/8-small) 40 | 41 | [-2, 1, Conv, [256, 3, 2]], 42 | [[-1, 14], 1, Concat, [1]], # cat head P4 43 | [-1, 3, BottleneckCSP, [512, False]], 44 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 22 (P4/16-medium) 45 | 46 | [-2, 1, Conv, [512, 3, 2]], 47 | [[-1, 10], 1, Concat, [1]], # cat head P5 48 | [-1, 3, BottleneckCSP, [1024, False]], 49 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 26 (P5/32-large) 50 | 51 | [[], 1, Detect, [nc, anchors]], # Detect(P5, P4, P3) 52 | ] 53 | -------------------------------------------------------------------------------- /models/yolov5x.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 80 # 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 | - [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 | ] 25 | 26 | # YOLOv5 head 27 | head: 28 | [[-1, 3, BottleneckCSP, [1024, False]], # 9 29 | 30 | [-1, 1, Conv, [512, 1, 1]], 31 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 32 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 33 | [-1, 3, BottleneckCSP, [512, False]], # 13 34 | 35 | [-1, 1, Conv, [256, 1, 1]], 36 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 37 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 38 | [-1, 3, BottleneckCSP, [256, False]], 39 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 18 (P3/8-small) 40 | 41 | [-2, 1, Conv, [256, 3, 2]], 42 | [[-1, 14], 1, Concat, [1]], # cat head P4 43 | [-1, 3, BottleneckCSP, [512, False]], 44 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 22 (P4/16-medium) 45 | 46 | [-2, 1, Conv, [512, 3, 2]], 47 | [[-1, 10], 1, Concat, [1]], # cat head P5 48 | [-1, 3, BottleneckCSP, [1024, False]], 49 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 26 (P5/32-large) 50 | 51 | [[], 1, Detect, [nc, anchors]], # Detect(P5, P4, P3) 52 | ] 53 | -------------------------------------------------------------------------------- /my_utils/data_aug.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | @Author : LiuZhian 4 | @Time : 2019/4/24 0024 上午 9:19 5 | @Comment : 6 | """ 7 | import os 8 | 9 | from xml.dom.minidom import parse, Document 10 | from my_utils.imgaug_utils import get_inner_bbs 11 | import numpy as np 12 | 13 | def save_xml(aug_info, dst_xml_dir): 14 | coor_array, img_info = aug_info 15 | img_name, img_h, img_w, img_c = list(map(str, img_info)) 16 | xml_name = os.path.split(img_name)[-1].split(".")[0] 17 | 18 | # 1.创建DOM树对象 19 | dom = Document() 20 | # 2.创建根节点。每次都要用DOM对象来创建任何节点。 21 | root_node = dom.createElement('root') 22 | # 3.用DOM对象添加根节点 23 | dom.appendChild(root_node) 24 | 25 | 26 | path_node = dom.createElement('path') 27 | root_node.appendChild(path_node) 28 | path_text = dom.createTextNode(img_name) 29 | path_node.appendChild(path_text) 30 | 31 | outputs_node = dom.createElement('outputs') 32 | root_node.appendChild(outputs_node) 33 | 34 | object_node = dom.createElement('object') 35 | outputs_node.appendChild(object_node) 36 | 37 | for row_data in coor_array: 38 | cls_name = inv_trans_cls_name(int(row_data[4])) 39 | item_node = dom.createElement('item') 40 | object_node.appendChild(item_node) 41 | 42 | name_node = dom.createElement('name') 43 | item_node.appendChild(name_node) 44 | name_text = dom.createTextNode(cls_name) 45 | name_node.appendChild(name_text) 46 | 47 | bndbox_node = dom.createElement('bndbox') 48 | item_node.appendChild(bndbox_node) 49 | 50 | xmin_node = dom.createElement('xmin') 51 | bndbox_node.appendChild(xmin_node) 52 | xmin_text = dom.createTextNode(str(row_data[0])) 53 | xmin_node.appendChild(xmin_text) 54 | 55 | ymin_node = dom.createElement('ymin') 56 | bndbox_node.appendChild(ymin_node) 57 | ymin_text = dom.createTextNode(str(row_data[1])) 58 | ymin_node.appendChild(ymin_text) 59 | 60 | xmax_node = dom.createElement('xmax') 61 | bndbox_node.appendChild(xmax_node) 62 | xmax_text = dom.createTextNode(str(row_data[2])) 63 | xmax_node.appendChild(xmax_text) 64 | 65 | ymax_node = dom.createElement('ymax') 66 | bndbox_node.appendChild(ymax_node) 67 | ymax_text = dom.createTextNode(str(row_data[3])) 68 | ymax_node.appendChild(ymax_text) 69 | 70 | size_node = dom.createElement('size') 71 | root_node.appendChild(size_node) 72 | 73 | width_node = dom.createElement('width') 74 | size_node.appendChild(width_node) 75 | width_text = dom.createTextNode(img_w) 76 | width_node.appendChild(width_text) 77 | 78 | height_node = dom.createElement('height') 79 | size_node.appendChild(height_node) 80 | height_text = dom.createTextNode(img_h) 81 | height_node.appendChild(height_text) 82 | 83 | depth_node = dom.createElement('depth') 84 | size_node.appendChild(depth_node) 85 | depth_text = dom.createTextNode(img_c) 86 | depth_node.appendChild(depth_text) 87 | 88 | # 每一个结点对象(包括dom对象本身)都有输出XML内容的方法,如:toxml()--字符串, toprettyxml()--美化树形格式。 89 | 90 | try: 91 | with open(rf'{dst_xml_dir}/{xml_name}.xml', 'w') as f: 92 | # 4.writexml()第一个参数是目标文件对象,第二个参数是根节点的缩进格式,第三个参数是其他子节点的缩进格式, 93 | # 第四个参数制定了换行格式,第五个参数制定了xml内容的编码。 94 | dom.writexml(f, indent='', addindent='\t', newl='\n', encoding='utf-8') 95 | print(rf'dst: {dst_xml_dir}/{xml_name}.xml') 96 | except Exception as err: 97 | print('错误:{err}'.format(err=err)) 98 | 99 | 100 | def trans_cls_name(name): 101 | if name == "call": 102 | return 0 103 | elif name == "smoke": 104 | return 1 105 | elif name == "drink": 106 | return 2 107 | else: 108 | raise ValueError(f"wrong class name! {name}") 109 | 110 | def inv_trans_cls_name(value): 111 | if value == 0: 112 | return "call" 113 | elif value == 1: 114 | return "smoke" 115 | elif value == 2: 116 | return "drink" 117 | else: 118 | raise ValueError(f"wrong class name! {value}") 119 | 120 | def change_xml_info(src_xml_path, src_img_dir, dst_img_dir, dst_xml_dir, p_number): 121 | ''' 122 | :param p_number: Numbers of images to enhance 123 | :return: 124 | ''' 125 | print(f"src: {src_xml_path}") 126 | dom = parse(src_xml_path) 127 | root = dom.documentElement 128 | img_name = root.getElementsByTagName("path")[0].childNodes[0].data 129 | img_name = os.path.split(img_name)[-1].split(".")[0] 130 | img_path = f"{src_img_dir}/{img_name}.jpg" 131 | item = root.getElementsByTagName("item") 132 | 133 | # label = root.getElementsByTagName("name")[0].childNodes[0].data 134 | 135 | coor_list = [] 136 | for box in item: 137 | cls_name = box.getElementsByTagName("name")[0].childNodes[0].data 138 | x1 = max(0, int(box.getElementsByTagName("xmin")[0].childNodes[0].data)) 139 | y1 = max(0, int(box.getElementsByTagName("ymin")[0].childNodes[0].data)) 140 | x2 = max(0, int(box.getElementsByTagName("xmax")[0].childNodes[0].data)) 141 | y2 = max(0, int(box.getElementsByTagName("ymax")[0].childNodes[0].data)) 142 | cls_name = trans_cls_name(cls_name) 143 | coor_list.append([x1,y1,x2,y2,cls_name]) 144 | aug_list = get_inner_bbs(img_path, dst_img_dir, np.array(coor_list), p_number) 145 | if not aug_list: 146 | return 147 | for aug_info in aug_list: 148 | save_xml(aug_info, dst_xml_dir) 149 | 150 | 151 | if __name__ == '__main__': 152 | xml_dir = r"E:\imgs_and_labels\labels" 153 | src_img_dir = r"E:\imgs_and_labels\imgs" 154 | # dst_img_path = r"G:\yolov5-master\data\augmentation" 155 | dst_img_path = r"E:\imgs_and_labels" 156 | dst_xml_path = r"E:\imgs_and_labels" 157 | epochs = 3 158 | 159 | # for xml_path in os.listdir(xml_dir): 160 | # change_xml_info(f"{xml_dir}/{xml_path}", src_img_dir, dst_img_path, dst_xml_path, epochs) 161 | change_xml_info(r"E:\imgs_and_labels\labels\1_40.xml", src_img_dir, dst_img_path, dst_xml_path, 3) 162 | -------------------------------------------------------------------------------- /my_utils/imgaug_utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | from PIL import Image 3 | import numpy as np 4 | import imgaug as ia 5 | import imgaug.augmenters as iaa 6 | from imgaug.augmentables.bbs import BoundingBoxesOnImage 7 | 8 | 9 | ia.seed(1) 10 | 11 | GREEN = [0, 255, 0] 12 | ORANGE = [255, 140, 0] 13 | RED = [255, 0, 0] 14 | 15 | # Pad image with a 1px white and (BY-1)px black border 16 | def _pad(image, by): 17 | image_border1 = ia.augmenters.size.pad(image, top=1, right=1, bottom=1, left=1, 18 | mode="constant", cval=255) 19 | image_border2 = ia.augmenters.size.pad(image_border1, top=by-1, right=by-1, 20 | bottom=by-1, left=by-1, 21 | mode="constant", cval=0) 22 | return image_border2 23 | 24 | # Draw BBs on an image 25 | # and before doing that, extend the image plane by BORDER pixels. 26 | # Mark BBs inside the image plane with green color, those partially inside 27 | # with orange and those fully outside with red. 28 | def draw_bbs(image, bbs, border): 29 | image_border = _pad(image, border) 30 | for bb in bbs.bounding_boxes: 31 | if bb.is_fully_within_image(image.shape): 32 | color = GREEN 33 | elif bb.is_partly_within_image(image.shape): 34 | color = ORANGE 35 | else: 36 | color = RED 37 | image_border = bb.shift(x=border, y=border)\ 38 | .draw_on_image(image_border, size=2, color=color) 39 | 40 | return image_border 41 | 42 | def get_inner_bbs(image_path, dst_img_dir, array_info, p_numbers): 43 | ''' 44 | :param image_path: src img path 45 | :param dst_img_dir: img save path 46 | :param coor_array: label coor array 47 | :param p_numbers: Numbers of images to enhance 48 | :return: [(bbs_array, img_info), 49 | (bbs_array, img_info)] 50 | ''' 51 | 52 | 53 | 54 | 55 | try: 56 | assert array_info.shape[1] == 5 57 | coor_array = array_info[:, :-1] 58 | cls_array = array_info[:, -1] 59 | 60 | image = Image.open(image_path) 61 | image = np.array(image) 62 | img_name = os.path.split(image_path)[-1].split(".")[0] 63 | bbs = BoundingBoxesOnImage.from_xyxy_array(coor_array, shape=image.shape) 64 | except Exception as e: 65 | print(f"err:{e}") 66 | print(array_info.shape) 67 | print(image_path) 68 | return None 69 | 70 | # # Draw the original picture 71 | # image_before = draw_bbs(image, bbs, 100) 72 | # ia.imshow(image_before) 73 | 74 | # Image augmentation sequence 75 | seq = iaa.Sequential([ 76 | iaa.Fliplr(0.5), 77 | iaa.Crop(percent=(0, 0.1)), 78 | iaa.Sometimes( 79 | 0.5, 80 | iaa.GaussianBlur(sigma=(0, 0.5)) 81 | ), 82 | # Strengthen or weaken the contrast in each image. 83 | iaa.LinearContrast((0.75, 1.5)), 84 | iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.05 * 255), per_channel=0.5), 85 | # change illumination 86 | iaa.Multiply((0.3, 1.2), per_channel=0.2), 87 | # affine transformation 88 | iaa.Affine( 89 | scale={"x": (0.8, 1.2), "y": (0.8, 1.2)}, 90 | translate_percent={"x": (-0.2, 0.2), "y": (-0.2, 0.2)}, 91 | rotate=(-5, 5), 92 | shear=(-8, 8) 93 | ) 94 | ], random_order=True) # apply augmenters in random order 95 | 96 | res_list = [] 97 | # gen img and coor 98 | try: 99 | for epoch in range(p_numbers): 100 | image_aug, bbs_aug = seq(image=image, bounding_boxes=bbs) 101 | # bbs_aug = bbs_aug.remove_out_of_image().clip_out_of_image() 102 | 103 | # # draw aug img and label 104 | image_after = bbs_aug.draw_on_image(image_aug, size=2, color=[0, 0, 255]) 105 | ia.imshow(image_after) 106 | 107 | # save img 108 | h, w, c = image_aug.shape 109 | 110 | img_aug_name = rf'{dst_img_dir}/{img_name}_{epoch}.jpg' 111 | im = Image.fromarray(image_aug) 112 | 113 | im.save(img_aug_name) 114 | 115 | 116 | bbs_array = bbs_aug.to_xyxy_array() 117 | result_array = np.column_stack((bbs_array, cls_array)) 118 | res_list.append([result_array, (img_aug_name, h, w, c)]) 119 | except Exception as e: 120 | print(e) 121 | print(img_aug_name) 122 | return None 123 | # return coor and img info 124 | return res_list 125 | 126 | 127 | 128 | 129 | 130 | if __name__ == '__main__': 131 | bbs = np.array([[25, 75, 25, 75], [100, 150, 25, 75], [175, 225, 25, 75]]) 132 | get_inner_bbs(r"/inference/output/smoke81.jpg", r"/data/augmentation", bbs, 3) -------------------------------------------------------------------------------- /my_utils/my_utils.rar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lieweiAI/action-detection/b8b174d363cf3dac4c94c7736126edc91838c81f/my_utils/my_utils.rar -------------------------------------------------------------------------------- /my_utils/parse_xml.py: -------------------------------------------------------------------------------- 1 | from xml.dom.minidom import parse 2 | from PIL import Image 3 | import os 4 | 5 | # xml_dir = r"E:yolov3\data\path\outputs" 6 | # xml_dir = r"G:\img_label\train_xml" 7 | # xml_dir = r"G:\yolov5-master\data\augmentation\outputs" 8 | xml_dir = r"E:\imgs_and_labels\labels" 9 | xml_file_list = os.listdir(xml_dir) 10 | 11 | 12 | def parse_2_txt(): 13 | for file_path in xml_file_list: 14 | xml_path = os.path.join(xml_dir, file_path) 15 | dom = parse(xml_path) 16 | root = dom.documentElement 17 | img_name = root.getElementsByTagName("path")[0].childNodes[0].data 18 | label_name = os.path.split(img_name)[-1].split(".")[0] 19 | 20 | img_size = root.getElementsByTagName("size")[0] 21 | img_w = int(img_size.getElementsByTagName("width")[0].childNodes[0].data) 22 | img_h = int(img_size.getElementsByTagName("height")[0].childNodes[0].data) 23 | # img_c = img_size.getElementsByTagName("depth")[0].childNodes[0].data 24 | # objects = root.getElementsByTagName("object") 25 | item = root.getElementsByTagName("item") 26 | with open(rf"E:\imgs_and_labels\txt_labels/{label_name}.txt", "w") as f: 27 | for box in item: 28 | cls_name = box.getElementsByTagName("name")[0].childNodes[0].data 29 | # a = box.getElementsByTagName("xmin")[0].childNodes[0].data 30 | 31 | x1 = float(box.getElementsByTagName("xmin")[0].childNodes[0].data) 32 | y1 = float(box.getElementsByTagName("ymin")[0].childNodes[0].data) 33 | x2 = float(box.getElementsByTagName("xmax")[0].childNodes[0].data) 34 | y2 = float(box.getElementsByTagName("ymax")[0].childNodes[0].data) 35 | 36 | if min(x1, x2) > img_w or min(y1, y2)>img_h: 37 | print(f"bbs out of range: x1:{x1},y1:{y1},x2:{x2},y2:{y2}") 38 | print(xml_path) 39 | continue 40 | 41 | if max(x1, x2) < 0 or max(y1, y2) < 0: 42 | print(f"bbs out of range: x1:{x1},y1:{y1},x2:{x2},y2:{y2}") 43 | print(xml_path) 44 | continue 45 | 46 | def maxmin(x, y): 47 | if x > y: 48 | return y 49 | elif x < 0: 50 | return 0 51 | else: 52 | return x 53 | 54 | x1, y1, x2, y2 = map(maxmin, [x1,y1,x2,y2],[img_w, img_h, img_w, img_h]) 55 | 56 | w, h = (x2 - x1) / img_w, (y2 - y1) / img_h 57 | cx, cy = (w / 2 + x1) / img_w, (h / 2 + y1) / img_h 58 | 59 | if not len(list(filter(lambda x: (0 <= x <= 1), [w, h, cx, cy]))) == 4: 60 | print(file_path) 61 | raise ValueError(f"cx:{cx}, cy:{cy}, w:{w}, h:{h}") 62 | 63 | if cls_name == "smoke": 64 | class_num = 0 65 | elif cls_name == "call": 66 | class_num = 1 67 | elif cls_name == "drink": 68 | class_num = 2 69 | else: 70 | raise ValueError("class name error!") 71 | f.writelines(f"{' '.join(list(map(str, [class_num, cx, cy, w, h])))}\n") 72 | 73 | # print(len(objects)) 74 | 75 | 76 | def check_cls_name(): 77 | for file_path in xml_file_list: 78 | xml_path = os.path.join(xml_dir, file_path) 79 | dom = parse(xml_path) 80 | root = dom.documentElement 81 | item = root.getElementsByTagName("item") 82 | for box in item: 83 | cls_name = box.getElementsByTagName("name")[0].childNodes[0].data 84 | if cls_name == "smoker": 85 | print(xml_path) 86 | 87 | 88 | if __name__ == '__main__': 89 | # check_cls_name() 90 | parse_2_txt() 91 | -------------------------------------------------------------------------------- /my_utils/remove_noexist.py: -------------------------------------------------------------------------------- 1 | import os 2 | import shutil 3 | 4 | img_dir = r"G:\drive\images\val2017" 5 | xml_dir = r"E:\imgs_and_labels\labels" 6 | 7 | txt_dir = r"G:\drive\labels\train2017" 8 | dst_txt_dir = r"G:\drive\labels\val2017" 9 | 10 | 11 | 12 | def rm_img(): 13 | for img_path in os.listdir(img_dir): 14 | if img_path.endswith(".jpg"): 15 | txt_path = f"{xml_dir}/{os.path.split(img_path)[-1].split('.')[0]}.xml" # .xml文件,必要时替换为.txt 16 | if not os.path.exists(txt_path): 17 | print(txt_path) 18 | os.remove(f"{img_dir}/{img_path}") 19 | 20 | 21 | def rm_xml(): 22 | for txt_path in os.listdir(xml_dir): 23 | if txt_path.endswith(".xml"): 24 | img_path = f"{img_dir}/{os.path.split(txt_path)[-1].split('.')[0]}.jpg" 25 | if not os.path.exists(img_path): 26 | print(img_path) 27 | os.remove(f"{xml_dir}/{txt_path}") 28 | 29 | 30 | def mv_txt(): 31 | for img_path in os.listdir(img_dir): 32 | try: 33 | txt_name = img_path.split(".")[0] 34 | shutil.move(f"{txt_dir}/{txt_name}.txt", f"{dst_txt_dir}/{txt_name}.txt") 35 | except Exception as e: 36 | print(f"err: {e}") 37 | print(img_path) 38 | if __name__ == '__main__': 39 | mv_txt() 40 | # rm_img() -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # pip install -U -r requirements.txt 2 | Cython 3 | numpy==1.17 4 | opencv-python 5 | torch>=1.4 6 | matplotlib 7 | pillow 8 | tensorboard 9 | PyYAML>=5.3 10 | torchvision 11 | scipy 12 | tqdm 13 | git+https://github.com/cocodataset/cocoapi.git#subdirectory=PythonAPI 14 | 15 | # Nvidia Apex (optional) for mixed precision training -------------------------- 16 | # git clone https://github.com/NVIDIA/apex && cd apex && pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" . --user && cd .. && rm -rf apex 17 | 18 | # Conda commands (in place of pip) --------------------------------------------- 19 | # conda update -yn base -c defaults conda 20 | # conda install -yc anaconda numpy opencv matplotlib tqdm pillow ipython 21 | # conda install -yc conda-forge scikit-image pycocotools tensorboard 22 | # conda install -yc spyder-ide spyder-line-profiler 23 | # conda install -yc pytorch pytorch torchvision 24 | # conda install -yc conda-forge protobuf numpy && pip install onnx==1.6.0 # https://github.com/onnx/onnx#linux-and-macos 25 | -------------------------------------------------------------------------------- /results.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lieweiAI/action-detection/b8b174d363cf3dac4c94c7736126edc91838c81f/results.png -------------------------------------------------------------------------------- /results.txt: -------------------------------------------------------------------------------- 1 | 0/19999 1.94G 0.09479 0.02711 0.03801 0.1599 2 640 0.01535 0.001035 0.02525 0.004363 0.07638 0.02755 0.0285 2 | 1/19999 1.99G 0.07996 0.02483 0.02178 0.1266 5 640 0.1302 0.2073 0.09073 0.01653 0.06813 0.025 0.01206 3 | 2/19999 1.99G 0.07579 0.0239 0.01475 0.1144 1 640 0.1107 0.3243 0.1144 0.02739 0.0677 0.02496 0.01216 4 | 3/19999 1.99G 0.07102 0.02438 0.01308 0.1085 1 640 0.1723 0.4174 0.1925 0.04886 0.05921 0.02392 0.007498 5 | 4/19999 1.99G 0.06633 0.02389 0.01111 0.1013 1 640 0.2216 0.5431 0.2794 0.09128 0.05687 0.02307 0.007023 6 | 5/19999 1.99G 0.06369 0.02345 0.009795 0.09694 4 640 0.1931 0.6247 0.2579 0.07557 0.05607 0.02302 0.00499 7 | 6/19999 1.99G 0.06071 0.02282 0.009015 0.09255 1 640 0.2136 0.6347 0.2827 0.08081 0.0535 0.02323 0.004051 8 | 7/19999 1.99G 0.05965 0.02287 0.008389 0.09091 4 640 0.2428 0.6627 0.328 0.09926 0.05113 0.02286 0.004135 9 | 8/19999 1.99G 0.05748 0.02309 0.008025 0.0886 2 640 0.2484 0.7229 0.3727 0.1154 0.05095 0.0225 0.004082 10 | 9/19999 1.99G 0.05597 0.0227 0.007296 0.08597 2 640 0.2527 0.6944 0.4087 0.1294 0.0491 0.02231 0.003524 11 | 10/19999 1.99G 0.05541 0.02249 0.007216 0.08512 4 640 0.248 0.7169 0.3989 0.1449 0.04955 0.02179 0.003479 12 | 11/19999 1.99G 0.05376 0.0226 0.007324 0.08368 2 640 0.2758 0.7217 0.4345 0.1303 0.04884 0.02178 0.003166 13 | 12/19999 1.99G 0.05318 0.02228 0.006304 0.08176 0 640 0.2668 0.7152 0.308 0.09562 0.04879 0.02308 0.002858 14 | 13/19999 1.99G 0.05257 0.02189 0.006127 0.08059 1 640 0.3137 0.7173 0.4864 0.1834 0.04614 0.02058 0.00275 15 | 14/19999 1.99G 0.05187 0.02215 0.006297 0.08031 2 640 0.2802 0.7523 0.439 0.1573 0.04648 0.02121 0.002762 16 | 15/19999 1.99G 0.05152 0.02157 0.005957 0.07904 3 640 0.2848 0.7382 0.4203 0.1474 0.04636 0.02178 0.002775 17 | 16/19999 1.99G 0.05069 0.02206 0.005904 0.07865 2 640 0.2755 0.7741 0.4035 0.1507 0.04583 0.02138 0.002615 18 | 17/19999 1.99G 0.04991 0.02169 0.005668 0.07727 1 640 0.3154 0.7619 0.4426 0.1617 0.04595 0.02084 0.002162 19 | 18/19999 1.99G 0.04995 0.02148 0.005574 0.07701 1 640 0.3126 0.7435 0.4031 0.1579 0.04514 0.02165 0.002263 20 | 19/19999 1.99G 0.04919 0.02156 0.005628 0.07638 2 640 0.3121 0.7531 0.4033 0.154 0.04448 0.02214 0.002628 21 | 20/19999 1.99G 0.04846 0.02116 0.004931 0.07455 1 640 0.3093 0.7699 0.4288 0.1746 0.04404 0.02124 0.002119 22 | 21/19999 1.99G 0.04864 0.02137 0.005267 0.07528 3 640 0.3085 0.7777 0.427 0.1756 0.04512 0.02093 0.001915 23 | 22/19999 1.99G 0.04707 0.02152 0.004823 0.07341 1 640 0.2995 0.784 0.4853 0.1884 0.04466 0.02102 0.002026 24 | 23/19999 1.99G 0.0468 0.02125 0.004821 0.07287 3 640 0.331 0.7781 0.3906 0.1498 0.04565 0.02156 0.001589 25 | 24/19999 1.99G 0.04655 0.02117 0.004685 0.0724 3 640 0.3204 0.7894 0.4668 0.1727 0.04436 0.02152 0.002194 26 | 25/19999 1.99G 0.04648 0.02027 0.004597 0.07135 2 640 0.3347 0.801 0.4113 0.1484 0.04443 0.02161 0.002346 27 | 26/19999 1.99G 0.04609 0.0211 0.004461 0.07165 3 640 0.3351 0.8046 0.4531 0.1808 0.04292 0.02121 0.001946 28 | 27/19999 1.99G 0.04603 0.02124 0.004902 0.07218 0 640 0.3131 0.7726 0.4245 0.1588 0.04366 0.02231 0.001895 29 | 28/19999 1.99G 0.04571 0.02058 0.00445 0.07074 2 640 0.3191 0.7995 0.3866 0.1498 0.04332 0.02119 0.001916 30 | 29/19999 1.99G 0.04494 0.02082 0.004788 0.07054 1 640 0.3428 0.7688 0.38 0.1447 0.0431 0.02275 0.001808 31 | 30/19999 1.99G 0.04475 0.02085 0.004319 0.06991 5 640 0.3323 0.7792 0.3858 0.1436 0.04301 0.02185 0.002357 32 | 31/19999 1.99G 0.04461 0.02027 0.004323 0.0692 1 640 0.337 0.8373 0.5391 0.2077 0.04268 0.01966 0.001657 33 | 32/19999 1.99G 0.0445 0.02015 0.004282 0.06893 1 640 0.3281 0.8104 0.4804 0.1898 0.04184 0.02116 0.001714 34 | 33/19999 1.99G 0.04356 0.02042 0.004195 0.06818 3 640 0.3458 0.7919 0.5159 0.203 0.04179 0.02138 0.001888 35 | 34/19999 1.99G 0.04317 0.02075 0.004364 0.06828 2 640 0.3583 0.8305 0.5448 0.2198 0.04106 0.02118 0.001912 36 | 35/19999 1.99G 0.04339 0.02058 0.004886 0.06886 2 640 0.3485 0.8231 0.477 0.1895 0.04154 0.02088 0.001644 37 | 36/19999 1.99G 0.04359 0.02062 0.004155 0.06837 4 640 0.3414 0.8181 0.4035 0.1669 0.04176 0.02208 0.001626 38 | 37/19999 1.99G 0.04382 0.02065 0.004382 0.06885 4 640 0.3626 0.8339 0.5025 0.204 0.04218 0.02128 0.001814 39 | 38/19999 1.99G 0.04368 0.01984 0.004374 0.06789 2 640 0.3572 0.827 0.4724 0.1993 0.04142 0.02094 0.00197 40 | 39/19999 1.99G 0.04297 0.01981 0.004165 0.06695 3 640 0.3804 0.7949 0.4794 0.1937 0.04118 0.02136 0.001793 41 | 40/19999 1.99G 0.04273 0.0197 0.004249 0.06668 1 640 0.3703 0.8214 0.4875 0.2031 0.04114 0.02045 0.001755 42 | 41/19999 1.99G 0.04196 0.02013 0.004102 0.06619 2 640 0.3467 0.8141 0.4618 0.1915 0.04095 0.02167 0.001776 43 | 42/19999 1.99G 0.04242 0.01969 0.003726 0.06584 2 640 0.3406 0.8508 0.5022 0.2125 0.04044 0.02115 0.001773 44 | 43/19999 1.99G 0.04219 0.01987 0.003913 0.06597 1 640 0.3857 0.8266 0.4665 0.1998 0.04042 0.02097 0.001955 45 | 44/19999 1.99G 0.04173 0.01959 0.003878 0.06519 1 640 0.376 0.8461 0.5028 0.2092 0.0407 0.02035 0.001837 46 | 45/19999 1.99G 0.04188 0.01949 0.00391 0.06529 2 640 0.3526 0.8252 0.4807 0.2069 0.04141 0.02063 0.001787 47 | 46/19999 1.99G 0.04121 0.01971 0.003795 0.06472 1 640 0.3865 0.8302 0.4948 0.2043 0.04035 0.02113 0.00164 48 | 47/19999 1.99G 0.04175 0.02007 0.004665 0.06649 5 640 0.3836 0.8249 0.4787 0.2057 0.0412 0.02103 0.001824 49 | 48/19999 1.99G 0.04157 0.01975 0.004306 0.06562 1 640 0.3873 0.8073 0.4932 0.2102 0.04139 0.02062 0.001962 50 | 49/19999 1.99G 0.04154 0.01962 0.004227 0.06538 2 640 0.401 0.7979 0.4416 0.1881 0.04073 0.02132 0.002052 51 | 50/19999 1.99G 0.04115 0.01967 0.003957 0.06478 4 640 0.3636 0.8122 0.4149 0.1791 0.04086 0.02184 0.002169 52 | 51/19999 1.99G 0.04104 0.01912 0.004014 0.06417 2 640 0.3857 0.799 0.4507 0.2002 0.03991 0.02087 0.001431 53 | 52/19999 1.99G 0.04043 0.01927 0.003782 0.06349 2 640 0.382 0.8115 0.4501 0.1967 0.0408 0.02105 0.001545 54 | 53/19999 1.99G 0.04049 0.0197 0.003748 0.06394 1 640 0.3915 0.8123 0.4812 0.2135 0.0404 0.0211 0.001879 55 | 54/19999 1.99G 0.04074 0.01938 0.003677 0.0638 3 640 0.3747 0.8177 0.4873 0.2263 0.03946 0.02108 0.001871 56 | 55/19999 1.99G 0.04016 0.01919 0.003939 0.0633 2 640 0.3939 0.8204 0.542 0.2424 0.03954 0.02022 0.001736 57 | 56/19999 1.99G 0.03979 0.01922 0.003592 0.0626 1 640 0.3681 0.8506 0.5118 0.215 0.03943 0.02124 0.001555 58 | 57/19999 1.99G 0.0392 0.01909 0.003111 0.06141 0 640 0.3833 0.8476 0.4896 0.2197 0.03954 0.02064 0.001521 59 | 58/19999 1.99G 0.04012 0.01923 0.003765 0.06311 3 640 0.3884 0.8553 0.4862 0.2046 0.03992 0.02073 0.001579 60 | 59/19999 1.99G 0.03981 0.01927 0.003946 0.06302 1 640 0.394 0.8424 0.5481 0.2471 0.0391 0.0205 0.001479 61 | 60/19999 1.99G 0.03946 0.01921 0.003846 0.06252 2 640 0.3855 0.8625 0.5441 0.2505 0.03914 0.01978 0.00165 62 | 61/19999 1.99G 0.03974 0.01932 0.003661 0.06272 4 640 0.3881 0.8449 0.4545 0.1977 0.03978 0.02139 0.00183 63 | 62/19999 1.99G 0.03935 0.01919 0.00377 0.0623 1 640 0.3667 0.8227 0.4837 0.2231 0.04022 0.02113 0.001636 64 | 63/19999 1.99G 0.03931 0.01913 0.003623 0.06206 3 640 0.3909 0.8332 0.4712 0.2124 0.03977 0.0208 0.001639 65 | 64/19999 1.99G 0.03894 0.01914 0.003396 0.06147 0 640 0.3988 0.8382 0.5055 0.2256 0.03947 0.02014 0.001336 66 | 65/19999 1.99G 0.03865 0.01921 0.003725 0.06159 2 640 0.3872 0.8105 0.4573 0.2075 0.03964 0.02123 0.001661 67 | 66/19999 1.99G 0.03917 0.01882 0.003521 0.06152 3 640 0.385 0.8319 0.5125 0.2398 0.03905 0.02034 0.001624 68 | 67/19999 1.99G 0.03836 0.01903 0.00356 0.06095 0 640 0.4003 0.8316 0.4917 0.2295 0.03852 0.02084 0.002074 69 | 68/19999 1.99G 0.0381 0.01873 0.003331 0.06016 1 640 0.4203 0.8607 0.5423 0.2482 0.03823 0.0203 0.001514 70 | 69/19999 1.99G 0.038 0.01842 0.003094 0.05952 3 640 0.4031 0.854 0.5829 0.2723 0.03837 0.01968 0.001494 71 | 70/19999 1.99G 0.03849 0.01863 0.003468 0.06058 1 640 0.4127 0.8613 0.5237 0.2438 0.0383 0.01999 0.001646 72 | 71/19999 1.99G 0.03857 0.01932 0.00349 0.06137 1 640 0.4006 0.8225 0.4931 0.2312 0.03871 0.02084 0.001674 73 | 72/19999 1.99G 0.03853 0.01847 0.00365 0.06065 3 640 0.4051 0.8174 0.4606 0.2095 0.03892 0.0215 0.001803 74 | 73/19999 1.99G 0.0384 0.01849 0.003539 0.06043 2 640 0.3895 0.8427 0.531 0.2557 0.03799 0.02079 0.001908 75 | 74/19999 1.99G 0.03853 0.01846 0.003378 0.06037 4 640 0.4035 0.8497 0.5528 0.2627 0.03763 0.0199 0.001378 76 | 75/19999 1.99G 0.03769 0.01807 0.003415 0.05917 1 640 0.4034 0.8427 0.5293 0.2481 0.03788 0.0204 0.001517 77 | 76/19999 1.99G 0.03764 0.0184 0.003322 0.05937 4 640 0.4182 0.8479 0.5241 0.247 0.03761 0.02032 0.00149 78 | 77/19999 1.99G 0.03769 0.01851 0.003439 0.05964 3 640 0.4031 0.8401 0.5285 0.2504 0.03773 0.02049 0.001732 79 | 78/19999 1.99G 0.03809 0.01888 0.003582 0.06056 1 640 0.4049 0.8197 0.4483 0.2061 0.03898 0.02179 0.001679 80 | 79/19999 1.99G 0.0379 0.01887 0.003582 0.06034 1 640 0.4073 0.8317 0.5563 0.2656 0.03776 0.01991 0.001527 81 | 80/19999 1.99G 0.03744 0.01872 0.003977 0.06013 1 640 0.4027 0.8735 0.6111 0.2851 0.03824 0.01928 0.001181 82 | 81/19999 1.99G 0.03725 0.01854 0.003079 0.05887 2 640 0.4124 0.8395 0.5554 0.2676 0.03809 0.02 0.00136 83 | 82/19999 1.99G 0.03748 0.01824 0.003317 0.05904 0 640 0.4209 0.8322 0.5256 0.2431 0.0384 0.02066 0.001465 84 | 83/19999 1.99G 0.03763 0.01819 0.003182 0.059 1 640 0.4093 0.8483 0.5014 0.2402 0.03781 0.02036 0.001536 85 | 84/19999 1.99G 0.03708 0.01832 0.003271 0.05868 3 640 0.4043 0.8245 0.5084 0.2475 0.03876 0.02062 0.001496 86 | 85/19999 1.99G 0.03659 0.01849 0.003084 0.05816 0 640 0.4104 0.8327 0.5423 0.2588 0.03793 0.02068 0.001468 87 | 86/19999 1.99G 0.03694 0.01828 0.003291 0.05851 2 640 0.4179 0.8262 0.5636 0.2758 0.03702 0.02066 0.001533 88 | 87/19999 1.99G 0.03706 0.01847 0.003343 0.05887 3 640 0.4125 0.8383 0.5511 0.2692 0.03767 0.01993 0.001426 89 | 88/19999 1.99G 0.03725 0.01825 0.003373 0.05887 1 640 0.426 0.8352 0.5293 0.2596 0.03744 0.02049 0.0017 90 | 89/19999 1.99G 0.03622 0.01826 0.003052 0.05753 4 640 0.4119 0.8228 0.5151 0.2407 0.03826 0.02073 0.001432 91 | 90/19999 1.99G 0.0365 0.01779 0.003145 0.05743 3 640 0.4131 0.8543 0.5375 0.2568 0.03757 0.02012 0.001507 92 | 91/19999 1.99G 0.03619 0.01842 0.0034 0.05801 1 640 0.4114 0.8236 0.506 0.2403 0.03725 0.02086 0.001307 93 | 92/19999 1.99G 0.03645 0.01812 0.003077 0.05764 0 640 0.4166 0.8528 0.6098 0.2899 0.03779 0.01937 0.001279 94 | 93/19999 1.99G 0.03656 0.01827 0.003312 0.05814 1 640 0.3987 0.8401 0.4821 0.2329 0.03791 0.02094 0.001383 95 | 94/19999 1.99G 0.0362 0.01848 0.003419 0.05809 2 640 0.3937 0.8215 0.5105 0.2464 0.03787 0.02048 0.001533 96 | 95/19999 1.99G 0.0362 0.01814 0.003234 0.05757 2 640 0.4289 0.8416 0.5169 0.2356 0.03787 0.02087 0.001408 97 | 96/19999 1.99G 0.0359 0.01782 0.002918 0.05664 1 640 0.4278 0.8339 0.5235 0.254 0.03719 0.02061 0.001519 98 | 97/19999 1.99G 0.03577 0.01777 0.002964 0.05651 3 640 0.4121 0.835 0.5321 0.2558 0.03704 0.02079 0.001506 99 | 98/19999 1.99G 0.03578 0.01784 0.002793 0.05642 2 640 0.4179 0.8167 0.5473 0.2601 0.03822 0.0206 0.001591 100 | 99/19999 1.99G 0.03595 0.01814 0.003104 0.05719 2 640 0.4317 0.8653 0.5833 0.284 0.03666 0.01962 0.001315 101 | 100/19999 1.99G 0.03569 0.01765 0.002823 0.05616 3 640 0.4056 0.8296 0.4987 0.2299 0.03785 0.02128 0.001537 102 | 101/19999 1.99G 0.03591 0.01793 0.003007 0.05685 1 640 0.4355 0.8464 0.5555 0.268 0.03682 0.02039 0.001185 103 | 102/19999 1.99G 0.03571 0.0179 0.003043 0.05665 1 640 0.4279 0.8581 0.5918 0.2883 0.03694 0.0201 0.001223 104 | 103/19999 1.99G 0.03564 0.01756 0.003281 0.05648 1 640 0.4183 0.829 0.5125 0.2499 0.03762 0.02062 0.00161 105 | 104/19999 1.99G 0.03566 0.01781 0.002854 0.05632 1 640 0.4217 0.8323 0.511 0.2468 0.03769 0.02067 0.001343 106 | 105/19999 1.99G 0.03517 0.01795 0.002817 0.05594 1 640 0.4403 0.8551 0.559 0.2657 0.03734 0.0204 0.001508 107 | 106/19999 1.99G 0.03594 0.01719 0.002933 0.05606 2 640 0.425 0.8212 0.5182 0.2486 0.03748 0.0213 0.001492 108 | 107/19999 1.99G 0.03542 0.01813 0.002997 0.05655 1 640 0.4222 0.8508 0.5739 0.2793 0.03661 0.02006 0.001384 109 | 108/19999 1.99G 0.03556 0.01774 0.003033 0.05634 2 640 0.4273 0.8437 0.5644 0.2696 0.0369 0.02036 0.001204 110 | 109/19999 1.99G 0.03564 0.01763 0.003206 0.05648 2 640 0.4227 0.8428 0.5411 0.2711 0.0367 0.02031 0.001394 111 | 110/19999 1.99G 0.03572 0.01777 0.002821 0.05632 4 640 0.4276 0.8584 0.5489 0.2754 0.03686 0.02006 0.001241 112 | 111/19999 1.99G 0.03532 0.01763 0.002875 0.05583 1 640 0.4214 0.8337 0.5236 0.2606 0.03674 0.02089 0.001455 113 | 112/19999 1.99G 0.03545 0.01792 0.003082 0.05645 1 640 0.4065 0.8158 0.5346 0.27 0.03691 0.02048 0.001474 114 | 113/19999 1.99G 0.03505 0.0176 0.002881 0.05553 2 640 0.4189 0.8355 0.5676 0.2752 0.03739 0.01997 0.001557 115 | 114/19999 1.99G 0.03504 0.01774 0.002904 0.05569 2 640 0.4237 0.8209 0.5294 0.2617 0.03703 0.02098 0.001507 116 | 115/19999 1.99G 0.03463 0.01732 0.00324 0.05519 2 640 0.4259 0.8262 0.5547 0.2784 0.03683 0.02018 0.001577 117 | 116/19999 1.99G 0.03532 0.01754 0.003191 0.05605 3 640 0.4249 0.8523 0.5431 0.269 0.03657 0.02043 0.001655 118 | 117/19999 1.99G 0.03473 0.01716 0.003052 0.05494 2 640 0.4291 0.8519 0.5501 0.2774 0.03638 0.0203 0.00138 119 | 118/19999 1.99G 0.03488 0.01726 0.002928 0.05507 1 640 0.443 0.8482 0.6004 0.2956 0.03635 0.0197 0.001218 120 | 119/19999 1.99G 0.03499 0.0171 0.002853 0.05495 1 640 0.4222 0.8439 0.5459 0.2753 0.03679 0.02064 0.001389 121 | 120/19999 1.99G 0.03506 0.01726 0.002809 0.05513 2 640 0.4286 0.8299 0.5689 0.294 0.03586 0.01995 0.001602 122 | 121/19999 1.99G 0.03508 0.01731 0.002896 0.05528 1 640 0.4228 0.8498 0.5656 0.2861 0.03623 0.02013 0.00151 123 | 122/19999 1.99G 0.03528 0.01715 0.003013 0.05544 1 640 0.424 0.8405 0.5579 0.2743 0.03635 0.02015 0.001369 124 | 123/19999 1.99G 0.03451 0.01731 0.002858 0.05467 4 640 0.421 0.8255 0.5558 0.2772 0.03671 0.0206 0.001286 125 | 124/19999 1.99G 0.03421 0.01751 0.003172 0.0549 0 640 0.4245 0.8363 0.5599 0.2788 0.03593 0.02057 0.001565 126 | 125/19999 1.99G 0.03487 0.01748 0.003266 0.05562 2 640 0.4312 0.843 0.5334 0.2662 0.03606 0.02063 0.001457 127 | 126/19999 1.99G 0.03408 0.01697 0.002936 0.05398 0 640 0.4394 0.8429 0.5491 0.2738 0.03556 0.02086 0.00123 128 | 127/19999 1.99G 0.0345 0.01714 0.002792 0.05443 1 640 0.424 0.8396 0.5578 0.2834 0.03619 0.02035 0.001303 129 | 128/19999 1.99G 0.03498 0.01752 0.003183 0.05569 1 640 0.4299 0.8449 0.5685 0.2791 0.03627 0.01967 0.001176 130 | 129/19999 1.99G 0.03484 0.01742 0.002989 0.05525 1 640 0.425 0.8407 0.562 0.2791 0.03663 0.01972 0.001116 131 | 130/19999 1.99G 0.0344 0.01731 0.00272 0.05443 0 640 0.4352 0.8333 0.5362 0.2645 0.03692 0.02035 0.001264 132 | 131/19999 1.99G 0.03444 0.01709 0.002969 0.0545 1 640 0.4294 0.8292 0.5515 0.275 0.03648 0.02108 0.001368 133 | 132/19999 1.99G 0.03415 0.01684 0.002747 0.05373 5 640 0.4322 0.8352 0.5647 0.281 0.03622 0.02091 0.001425 134 | 133/19999 1.99G 0.03417 0.01692 0.002829 0.05392 0 640 0.4283 0.8312 0.5581 0.2809 0.03636 0.02088 0.001227 135 | 134/19999 1.99G 0.03476 0.01717 0.003465 0.05539 4 640 0.4309 0.8365 0.5381 0.272 0.03643 0.0209 0.001304 136 | 135/19999 1.99G 0.03413 0.01693 0.002961 0.05402 1 640 0.4392 0.8628 0.5375 0.271 0.03582 0.02089 0.001186 137 | 136/19999 1.99G 0.03429 0.01727 0.002755 0.05432 2 640 0.4328 0.8507 0.5512 0.2812 0.03574 0.02034 0.001203 138 | 137/19999 1.99G 0.03424 0.01681 0.002953 0.054 1 640 0.4332 0.8467 0.5552 0.2796 0.03601 0.02066 0.001118 139 | 138/19999 1.99G 0.03435 0.0168 0.002914 0.05406 1 640 0.4515 0.8571 0.5983 0.3022 0.0356 0.01996 0.001181 140 | 139/19999 1.99G 0.03391 0.01694 0.002768 0.05362 4 640 0.4402 0.8497 0.5894 0.3009 0.03567 0.02001 0.001128 141 | 140/19999 1.99G 0.03419 0.01667 0.002967 0.05383 3 640 0.4405 0.8535 0.5793 0.2919 0.03579 0.02012 0.00117 142 | 141/19999 1.99G 0.0342 0.01717 0.002822 0.05419 1 640 0.4413 0.8602 0.5607 0.2821 0.03604 0.0203 0.001077 143 | 142/19999 1.99G 0.03429 0.01712 0.003105 0.05452 2 640 0.4364 0.8586 0.5598 0.2765 0.03606 0.02045 0.001138 144 | 143/19999 1.99G 0.03402 0.01713 0.002931 0.05408 2 640 0.4355 0.8283 0.5464 0.2731 0.03627 0.02086 0.001388 145 | 144/19999 1.99G 0.03379 0.01669 0.002753 0.05323 1 640 0.4435 0.8406 0.5499 0.2761 0.03605 0.02066 0.001406 146 | 145/19999 1.99G 0.034 0.01703 0.002812 0.05384 3 640 0.437 0.8417 0.5723 0.2877 0.03604 0.02053 0.001284 147 | 146/19999 1.99G 0.03383 0.01682 0.002609 0.05326 2 640 0.4366 0.8559 0.5594 0.2798 0.03591 0.02055 0.001173 148 | 147/19999 1.99G 0.03337 0.01655 0.002698 0.05263 2 640 0.4401 0.8556 0.554 0.2788 0.03578 0.02091 0.001286 149 | 148/19999 1.99G 0.03344 0.01686 0.002965 0.05326 1 640 0.4288 0.8409 0.5478 0.2843 0.03537 0.02083 0.001229 150 | 149/19999 1.99G 0.03383 0.01658 0.003025 0.05344 1 640 0.4334 0.8334 0.5452 0.281 0.03546 0.02108 0.001399 151 | 150/19999 1.99G 0.03361 0.0165 0.00272 0.05283 1 640 0.4404 0.8376 0.555 0.2875 0.0355 0.02107 0.001385 152 | 151/19999 1.99G 0.03314 0.01684 0.002581 0.05257 1 640 0.4358 0.8356 0.5642 0.2914 0.03564 0.02076 0.001401 153 | 152/19999 1.99G 0.03358 0.01675 0.002804 0.05313 1 640 0.4244 0.8343 0.5441 0.2815 0.03546 0.02117 0.001469 154 | 153/19999 1.99G 0.03332 0.01667 0.002588 0.05258 4 640 0.4213 0.8594 0.566 0.2927 0.03521 0.02023 0.001393 155 | 154/19999 1.99G 0.03271 0.01642 0.002541 0.05167 2 640 0.4203 0.8449 0.5603 0.2937 0.03528 0.02024 0.001334 156 | 155/19999 1.99G 0.03357 0.01662 0.002661 0.05285 1 640 0.425 0.8505 0.5828 0.2993 0.0353 0.02021 0.001264 157 | 156/19999 1.99G 0.03339 0.01646 0.002785 0.05263 2 640 0.4368 0.8607 0.6054 0.3138 0.03526 0.02007 0.001265 158 | 157/19999 1.99G 0.03347 0.01672 0.002483 0.05268 1 640 0.4313 0.8492 0.5771 0.3007 0.03538 0.02018 0.001192 159 | 158/19999 1.99G 0.03304 0.01624 0.002527 0.0518 2 640 0.4388 0.8642 0.5685 0.2945 0.03518 0.02061 0.001121 160 | 159/19999 1.99G 0.03313 0.01646 0.002983 0.05257 3 640 0.4407 0.8669 0.5804 0.2981 0.03496 0.02025 0.001086 161 | 160/19999 1.99G 0.03312 0.01664 0.002646 0.0524 1 640 0.4391 0.8538 0.5809 0.3043 0.03502 0.01992 0.001099 162 | 161/19999 1.99G 0.03334 0.0165 0.002565 0.0524 0 640 0.4304 0.847 0.5654 0.293 0.03529 0.02045 0.0012 163 | 162/19999 1.99G 0.03272 0.01645 0.00264 0.05181 2 640 0.4282 0.8382 0.5579 0.2911 0.03554 0.02101 0.001212 164 | 163/19999 1.99G 0.03312 0.01645 0.002565 0.05213 0 640 0.4303 0.8456 0.5633 0.2902 0.0354 0.02098 0.001251 165 | 164/19999 1.99G 0.03357 0.01607 0.002983 0.05263 1 640 0.4309 0.8372 0.552 0.2872 0.03505 0.02132 0.001233 166 | 165/19999 1.99G 0.03315 0.01638 0.002799 0.05232 0 640 0.4353 0.8471 0.555 0.2933 0.03483 0.02113 0.001289 167 | 166/19999 1.99G 0.03247 0.01605 0.002397 0.05092 1 640 0.434 0.8457 0.5659 0.3001 0.03469 0.02081 0.001393 168 | -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import json 3 | 4 | from torch.utils.data import DataLoader 5 | 6 | from utils import google_utils 7 | from utils.datasets import * 8 | from utils.utils import * 9 | 10 | 11 | def test(data, 12 | weights=None, 13 | batch_size=16, 14 | imgsz=640, 15 | conf_thres=0.001, 16 | iou_thres=0.6, # for NMS 17 | save_json=False, 18 | single_cls=False, 19 | augment=False, 20 | verbose=False, 21 | model=None, 22 | dataloader=None, 23 | merge=False): 24 | # Initialize/load model and set device 25 | if model is None: 26 | training = False 27 | device = torch_utils.select_device(opt.device, batch_size=batch_size) 28 | half = device.type != 'cpu' # half precision only supported on CUDA 29 | 30 | # Remove previous 31 | for f in glob.glob('test_batch*.jpg'): 32 | os.remove(f) 33 | 34 | # Load model 35 | google_utils.attempt_download(weights) 36 | model = torch.load(weights, map_location=device)['model'].float() # load to FP32 37 | torch_utils.model_info(model) 38 | model.fuse() 39 | model.to(device) 40 | if half: 41 | model.half() # to FP16 42 | 43 | # Multi-GPU disabled, incompatible with .half() 44 | # if device.type != 'cpu' and torch.cuda.device_count() > 1: 45 | # model = nn.DataParallel(model) 46 | 47 | else: # called by train.py 48 | training = True 49 | device = next(model.parameters()).device # get model device 50 | # half disabled https://github.com/ultralytics/yolov5/issues/99 51 | half = False # device.type != 'cpu' and torch.cuda.device_count() == 1 52 | if half: 53 | model.half() # to FP16 54 | 55 | # Configure 56 | model.eval() 57 | with open(data) as f: 58 | data = yaml.load(f, Loader=yaml.FullLoader) # model dict 59 | nc = 1 if single_cls else int(data['nc']) # number of classes 60 | iouv = torch.linspace(0.5, 0.95, 10).to(device) # iou vector for mAP@0.5:0.95 61 | # iouv = iouv[0].view(1) # comment for mAP@0.5:0.95 62 | niou = iouv.numel() 63 | 64 | # Dataloader 65 | if dataloader is None: # not training 66 | img = torch.zeros((1, 3, imgsz, imgsz), device=device) # init img 67 | _ = model(img.half() if half else img) if device.type != 'cpu' else None # run once 68 | 69 | merge = opt.merge # use Merge NMS 70 | path = data['test'] if opt.task == 'test' else data['val'] # path to val/test images 71 | dataset = LoadImagesAndLabels(path, 72 | imgsz, 73 | batch_size, 74 | rect=True, # rectangular inference 75 | single_cls=opt.single_cls, # single class mode 76 | pad=0.5) # padding 77 | batch_size = min(batch_size, len(dataset)) 78 | nw = min([os.cpu_count(), batch_size if batch_size > 1 else 0, 8]) # number of workers 79 | dataloader = DataLoader(dataset, 80 | batch_size=batch_size, 81 | num_workers=nw, 82 | pin_memory=True, 83 | collate_fn=dataset.collate_fn) 84 | 85 | seen = 0 86 | names = model.names if hasattr(model, 'names') else model.module.names 87 | coco91class = coco80_to_coco91_class() 88 | s = ('%20s' + '%12s' * 6) % ('Class', 'Images', 'Targets', 'P', 'R', 'mAP@.5', 'mAP@.5:.95') 89 | p, r, f1, mp, mr, map50, map, t0, t1 = 0., 0., 0., 0., 0., 0., 0., 0., 0. 90 | loss = torch.zeros(3, device=device) 91 | jdict, stats, ap, ap_class = [], [], [], [] 92 | for batch_i, (img, targets, paths, shapes) in enumerate(tqdm(dataloader, desc=s)): 93 | img = img.to(device) 94 | img = img.half() if half else img.float() # uint8 to fp16/32 95 | img /= 255.0 # 0 - 255 to 0.0 - 1.0 96 | targets = targets.to(device) 97 | nb, _, height, width = img.shape # batch size, channels, height, width 98 | whwh = torch.Tensor([width, height, width, height]).to(device) 99 | 100 | # Disable gradients 101 | with torch.no_grad(): 102 | # Run model 103 | t = torch_utils.time_synchronized() 104 | inf_out, train_out = model(img, augment=augment) # inference and training outputs 105 | t0 += torch_utils.time_synchronized() - t 106 | 107 | # Compute loss 108 | if training: # if model has loss hyperparameters 109 | loss += compute_loss([x.float() for x in train_out], targets, model)[1][:3] # GIoU, obj, cls 110 | 111 | # Run NMS 112 | t = torch_utils.time_synchronized() 113 | output = non_max_suppression(inf_out, conf_thres=conf_thres, iou_thres=iou_thres, merge=merge) 114 | t1 += torch_utils.time_synchronized() - t 115 | 116 | # Statistics per image 117 | for si, pred in enumerate(output): 118 | labels = targets[targets[:, 0] == si, 1:] 119 | nl = len(labels) 120 | tcls = labels[:, 0].tolist() if nl else [] # target class 121 | seen += 1 122 | 123 | if pred is None: 124 | if nl: 125 | stats.append((torch.zeros(0, niou, dtype=torch.bool), torch.Tensor(), torch.Tensor(), tcls)) 126 | continue 127 | 128 | # Append to text file 129 | # with open('test.txt', 'a') as file: 130 | # [file.write('%11.5g' * 7 % tuple(x) + '\n') for x in pred] 131 | 132 | # Clip boxes to image bounds 133 | clip_coords(pred, (height, width)) 134 | 135 | # Append to pycocotools JSON dictionary 136 | if save_json: 137 | # [{"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236}, ... 138 | image_id = int(Path(paths[si]).stem.split('_')[-1]) 139 | box = pred[:, :4].clone() # xyxy 140 | scale_coords(img[si].shape[1:], box, shapes[si][0], shapes[si][1]) # to original shape 141 | box = xyxy2xywh(box) # xywh 142 | box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner 143 | for p, b in zip(pred.tolist(), box.tolist()): 144 | jdict.append({'image_id': image_id, 145 | 'category_id': coco91class[int(p[5])], 146 | 'bbox': [round(x, 3) for x in b], 147 | 'score': round(p[4], 5)}) 148 | 149 | # Assign all predictions as incorrect 150 | correct = torch.zeros(pred.shape[0], niou, dtype=torch.bool, device=device) 151 | if nl: 152 | detected = [] # target indices 153 | tcls_tensor = labels[:, 0] 154 | 155 | # target boxes 156 | tbox = xywh2xyxy(labels[:, 1:5]) * whwh 157 | 158 | # Per target class 159 | for cls in torch.unique(tcls_tensor): 160 | ti = (cls == tcls_tensor).nonzero().view(-1) # prediction indices 161 | pi = (cls == pred[:, 5]).nonzero().view(-1) # target indices 162 | 163 | # Search for detections 164 | if pi.shape[0]: 165 | # Prediction to target ious 166 | ious, i = box_iou(pred[pi, :4], tbox[ti]).max(1) # best ious, indices 167 | 168 | # Append detections 169 | for j in (ious > iouv[0]).nonzero(): 170 | d = ti[i[j]] # detected target 171 | if d not in detected: 172 | detected.append(d) 173 | correct[pi[j]] = ious[j] > iouv # iou_thres is 1xn 174 | if len(detected) == nl: # all targets already located in image 175 | break 176 | 177 | # Append statistics (correct, conf, pcls, tcls) 178 | stats.append((correct.cpu(), pred[:, 4].cpu(), pred[:, 5].cpu(), tcls)) 179 | 180 | # Plot images 181 | if batch_i < 1: 182 | f = 'test_batch%g_gt.jpg' % batch_i # filename 183 | plot_images(img, targets, paths, f, names) # ground truth 184 | f = 'test_batch%g_pred.jpg' % batch_i 185 | plot_images(img, output_to_target(output, width, height), paths, f, names) # predictions 186 | 187 | # Compute statistics 188 | stats = [np.concatenate(x, 0) for x in zip(*stats)] # to numpy 189 | if len(stats): 190 | p, r, ap, f1, ap_class = ap_per_class(*stats) 191 | p, r, ap50, ap = p[:, 0], r[:, 0], ap[:, 0], ap.mean(1) # [P, R, AP@0.5, AP@0.5:0.95] 192 | mp, mr, map50, map = p.mean(), r.mean(), ap50.mean(), ap.mean() 193 | nt = np.bincount(stats[3].astype(np.int64), minlength=nc) # number of targets per class 194 | else: 195 | nt = torch.zeros(1) 196 | 197 | # Print results 198 | pf = '%20s' + '%12.3g' * 6 # print format 199 | print(pf % ('all', seen, nt.sum(), mp, mr, map50, map)) 200 | 201 | # Print results per class 202 | if verbose and nc > 1 and len(stats): 203 | for i, c in enumerate(ap_class): 204 | print(pf % (names[c], seen, nt[c], p[i], r[i], ap50[i], ap[i])) 205 | 206 | # Print speeds 207 | t = tuple(x / seen * 1E3 for x in (t0, t1, t0 + t1)) + (imgsz, imgsz, batch_size) # tuple 208 | if not training: 209 | print('Speed: %.1f/%.1f/%.1f ms inference/NMS/total per %gx%g image at batch-size %g' % t) 210 | 211 | # Save JSON 212 | if save_json and map50 and len(jdict): 213 | imgIds = [int(Path(x).stem.split('_')[-1]) for x in dataloader.dataset.img_files] 214 | f = 'detections_val2017_%s_results.json' % \ 215 | (weights.split(os.sep)[-1].replace('.pt', '') if weights else '') # filename 216 | print('\nCOCO mAP with pycocotools... saving %s...' % f) 217 | with open(f, 'w') as file: 218 | json.dump(jdict, file) 219 | 220 | try: 221 | from pycocotools.coco import COCO 222 | from pycocotools.cocoeval import COCOeval 223 | 224 | # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb 225 | cocoGt = COCO(glob.glob('../coco/annotations/instances_val*.json')[0]) # initialize COCO ground truth api 226 | cocoDt = cocoGt.loadRes(f) # initialize COCO pred api 227 | 228 | cocoEval = COCOeval(cocoGt, cocoDt, 'bbox') 229 | cocoEval.params.imgIds = imgIds # image IDs to evaluate 230 | cocoEval.evaluate() 231 | cocoEval.accumulate() 232 | cocoEval.summarize() 233 | map, map50 = cocoEval.stats[:2] # update results (mAP@0.5:0.95, mAP@0.5) 234 | except: 235 | print('WARNING: pycocotools must be installed with numpy==1.17 to run correctly. ' 236 | 'See https://github.com/cocodataset/cocoapi/issues/356') 237 | 238 | # Return results 239 | maps = np.zeros(nc) + map 240 | for i, c in enumerate(ap_class): 241 | maps[c] = ap[i] 242 | return (mp, mr, map50, map, *(loss.cpu() / len(dataloader)).tolist()), maps, t 243 | 244 | 245 | if __name__ == '__main__': 246 | parser = argparse.ArgumentParser(prog='test.py') 247 | parser.add_argument('--weights', type=str, default='weights/yolov5s.pt', help='model.pt path') 248 | parser.add_argument('--data', type=str, default='data/coco.yaml', help='*.data path') 249 | parser.add_argument('--batch-size', type=int, default=32, help='size of each image batch') 250 | parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)') 251 | parser.add_argument('--conf-thres', type=float, default=0.001, help='object confidence threshold') 252 | parser.add_argument('--iou-thres', type=float, default=0.65, help='IOU threshold for NMS') 253 | parser.add_argument('--save-json', action='store_true', help='save a cocoapi-compatible JSON results file') 254 | parser.add_argument('--task', default='val', help="'val', 'test', 'study'") 255 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') 256 | parser.add_argument('--single-cls', action='store_true', help='treat as single-class dataset') 257 | parser.add_argument('--augment', action='store_true', help='augmented inference') 258 | parser.add_argument('--merge', action='store_true', help='use Merge NMS') 259 | parser.add_argument('--verbose', action='store_true', help='report mAP by class') 260 | opt = parser.parse_args() 261 | opt.img_size = check_img_size(opt.img_size) 262 | opt.save_json = opt.save_json or opt.data.endswith('coco.yaml') 263 | opt.data = check_file(opt.data) # check file 264 | print(opt) 265 | 266 | # task = 'val', 'test', 'study' 267 | if opt.task in ['val', 'test']: # (default) run normally 268 | test(opt.data, 269 | opt.weights, 270 | opt.batch_size, 271 | opt.img_size, 272 | opt.conf_thres, 273 | opt.iou_thres, 274 | opt.save_json, 275 | opt.single_cls, 276 | opt.augment, 277 | opt.verbose) 278 | 279 | elif opt.task == 'study': # run over a range of settings and save/plot 280 | for weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt', 'yolov3-spp.pt']: 281 | f = 'study_%s_%s.txt' % (Path(opt.data).stem, Path(weights).stem) # filename to save to 282 | x = list(range(352, 832, 64)) # x axis 283 | y = [] # y axis 284 | for i in x: # img-size 285 | print('\nRunning %s point %s...' % (f, i)) 286 | r, _, t = test(opt.data, weights, opt.batch_size, i, opt.conf_thres, opt.iou_thres, opt.save_json) 287 | y.append(r + t) # results and times 288 | np.savetxt(f, y, fmt='%10.4g') # save 289 | os.system('zip -r study.zip study_*.txt') 290 | # plot_study_txt(f, x) # plot 291 | -------------------------------------------------------------------------------- /test_batch0_gt.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lieweiAI/action-detection/b8b174d363cf3dac4c94c7736126edc91838c81f/test_batch0_gt.jpg -------------------------------------------------------------------------------- /test_batch0_pred.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lieweiAI/action-detection/b8b174d363cf3dac4c94c7736126edc91838c81f/test_batch0_pred.jpg -------------------------------------------------------------------------------- /train.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | import torch.distributed as dist 4 | import torch.nn.functional as F 5 | import torch.optim as optim 6 | import torch.optim.lr_scheduler as lr_scheduler 7 | import torch.utils.data 8 | from torch.utils.tensorboard import SummaryWriter 9 | 10 | import test # import test.py to get mAP after each epoch 11 | from models.yolo import Model 12 | from utils import google_utils 13 | from utils.datasets import * 14 | from utils.utils import * 15 | 16 | mixed_precision = True 17 | try: # Mixed precision training https://github.com/NVIDIA/apex 18 | from apex import amp 19 | except: 20 | # print('Apex recommended for faster mixed precision training: https://github.com/NVIDIA/apex') 21 | mixed_precision = False # not installed 22 | 23 | wdir = 'weights' + os.sep # weights dir 24 | os.makedirs(wdir, exist_ok=True) 25 | last = wdir + 'last.pt' 26 | best = wdir + 'best.pt' 27 | results_file = 'results.txt' 28 | 29 | # Hyperparameters 30 | hyp = {'lr0': 0.01, # initial learning rate (SGD=1E-2, Adam=1E-3) 31 | 'momentum': 0.937, # SGD momentum 32 | 'weight_decay': 5e-4, # optimizer weight decay 33 | 'giou': 0.05, # giou loss gain 34 | 'cls': 0.58, # cls loss gain 35 | 'cls_pw': 1.0, # cls BCELoss positive_weight 36 | 'obj': 1.0, # obj loss gain (*=img_size/320 if img_size != 320) 37 | 'obj_pw': 1.0, # obj BCELoss positive_weight 38 | 'iou_t': 0.20, # iou training threshold 39 | 'anchor_t': 4.0, # anchor-multiple threshold 40 | 'fl_gamma': 0.0, # focal loss gamma (efficientDet default is gamma=1.5) 41 | 'hsv_h': 0.014, # image HSV-Hue augmentation (fraction) 42 | 'hsv_s': 0.68, # image HSV-Saturation augmentation (fraction) 43 | 'hsv_v': 0.36, # image HSV-Value augmentation (fraction) 44 | 'degrees': 0.0, # image rotation (+/- deg) 45 | 'translate': 0.0, # image translation (+/- fraction) 46 | 'scale': 0.5, # image scale (+/- gain) 47 | 'shear': 0.0} # image shear (+/- deg) 48 | print(hyp) 49 | 50 | # Overwrite hyp with hyp*.txt (optional) 51 | f = glob.glob('hyp*.txt') 52 | if f: 53 | print('Using %s' % f[0]) 54 | for k, v in zip(hyp.keys(), np.loadtxt(f[0])): 55 | hyp[k] = v 56 | 57 | # Print focal loss if gamma > 0 58 | if hyp['fl_gamma']: 59 | print('Using FocalLoss(gamma=%g)' % hyp['fl_gamma']) 60 | 61 | 62 | def train(hyp): 63 | epochs = opt.epochs # 300 64 | batch_size = opt.batch_size # 64 65 | weights = opt.weights # initial training weights 66 | 67 | # Configure 68 | init_seeds(1) 69 | with open(opt.data) as f: 70 | data_dict = yaml.load(f, Loader=yaml.FullLoader) # model dict 71 | train_path = data_dict['train'] 72 | test_path = data_dict['val'] 73 | nc = 1 if opt.single_cls else int(data_dict['nc']) # number of classes 74 | 75 | # Remove previous results 76 | for f in glob.glob('*_batch*.jpg') + glob.glob(results_file): 77 | os.remove(f) 78 | 79 | # Create model 80 | model = Model(opt.cfg).to(device) 81 | assert model.md['nc'] == nc, '%s nc=%g classes but %s nc=%g classes' % (opt.data, nc, opt.cfg, model.md['nc']) 82 | 83 | # Image sizes 84 | gs = int(max(model.stride)) # grid size (max stride) 85 | imgsz, imgsz_test = [check_img_size(x, gs) for x in opt.img_size] # verify imgsz are gs-multiples 86 | 87 | # Optimizer 88 | nbs = 64 # nominal batch size 89 | accumulate = max(round(nbs / batch_size), 1) # accumulate loss before optimizing 90 | hyp['weight_decay'] *= batch_size * accumulate / nbs # scale weight_decay 91 | pg0, pg1, pg2 = [], [], [] # optimizer parameter groups 92 | for k, v in model.named_parameters(): 93 | if v.requires_grad: 94 | if '.bias' in k: 95 | pg2.append(v) # biases 96 | elif '.weight' in k and '.bn' not in k: 97 | pg1.append(v) # apply weight decay 98 | else: 99 | pg0.append(v) # all else 100 | 101 | optimizer = optim.Adam(pg0, lr=hyp['lr0']) if opt.adam else \ 102 | optim.SGD(pg0, lr=hyp['lr0'], momentum=hyp['momentum'], nesterov=True) 103 | optimizer.add_param_group({'params': pg1, 'weight_decay': hyp['weight_decay']}) # add pg1 with weight_decay 104 | optimizer.add_param_group({'params': pg2}) # add pg2 (biases) 105 | print('Optimizer groups: %g .bias, %g conv.weight, %g other' % (len(pg2), len(pg1), len(pg0))) 106 | del pg0, pg1, pg2 107 | 108 | # Load Model 109 | google_utils.attempt_download(weights) 110 | start_epoch, best_fitness = 0, 0.0 111 | if weights.endswith('.pt'): # pytorch format 112 | ckpt = torch.load(weights, map_location=device) # load checkpoint 113 | 114 | # load model 115 | try: 116 | ckpt['model'] = {k: v for k, v in ckpt['model'].float().state_dict().items() 117 | if model.state_dict()[k].shape == v.shape} # to FP32, filter 118 | model.load_state_dict(ckpt['model'], strict=False) 119 | except KeyError as e: 120 | s = "%s is not compatible with %s. Specify --weights '' or specify a --cfg compatible with %s." \ 121 | % (opt.weights, opt.cfg, opt.weights) 122 | raise KeyError(s) from e 123 | 124 | # load optimizer 125 | if ckpt['optimizer'] is not None: 126 | optimizer.load_state_dict(ckpt['optimizer']) 127 | best_fitness = ckpt['best_fitness'] 128 | 129 | # load results 130 | if ckpt.get('training_results') is not None: 131 | with open(results_file, 'w') as file: 132 | file.write(ckpt['training_results']) # write results.txt 133 | 134 | start_epoch = ckpt['epoch'] + 1 135 | del ckpt 136 | 137 | # Mixed precision training https://github.com/NVIDIA/apex 138 | if mixed_precision: 139 | model, optimizer = amp.initialize(model, optimizer, opt_level='O1', verbosity=0) 140 | 141 | # Scheduler https://arxiv.org/pdf/1812.01187.pdf 142 | lf = lambda x: (((1 + math.cos(x * math.pi / epochs)) / 2) ** 1.0) * 0.9 + 0.1 # cosine 143 | scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf) 144 | scheduler.last_epoch = start_epoch - 1 # do not move 145 | # https://discuss.pytorch.org/t/a-problem-occured-when-resuming-an-optimizer/28822 146 | # plot_lr_scheduler(optimizer, scheduler, epochs) 147 | 148 | # Initialize distributed training 149 | if device.type != 'cpu' and torch.cuda.device_count() > 1 and torch.distributed.is_available(): 150 | dist.init_process_group(backend='nccl', # distributed backend 151 | init_method='tcp://127.0.0.1:9999', # init method 152 | world_size=1, # number of nodes 153 | rank=0) # node rank 154 | model = torch.nn.parallel.DistributedDataParallel(model) 155 | # pip install torch==1.4.0+cu100 torchvision==0.5.0+cu100 -f https://download.pytorch.org/whl/torch_stable.html 156 | 157 | # Dataset 158 | dataset = LoadImagesAndLabels(train_path, imgsz, batch_size, 159 | augment=True, 160 | hyp=hyp, # augmentation hyperparameters 161 | rect=opt.rect, # rectangular training 162 | cache_images=opt.cache_images, 163 | single_cls=opt.single_cls) 164 | mlc = np.concatenate(dataset.labels, 0)[:, 0].max() # max label class 165 | assert mlc < nc, 'Label class %g exceeds nc=%g in %s. Correct your labels or your model.' % (mlc, nc, opt.cfg) 166 | 167 | # Dataloader 168 | batch_size = min(batch_size, len(dataset)) 169 | nw = min([os.cpu_count(), batch_size if batch_size > 1 else 0, 8]) # number of workers 170 | dataloader = torch.utils.data.DataLoader(dataset, 171 | batch_size=batch_size, 172 | num_workers=nw, 173 | shuffle=not opt.rect, # Shuffle=True unless rectangular training is used 174 | pin_memory=True, 175 | collate_fn=dataset.collate_fn) 176 | 177 | # Testloader 178 | testloader = torch.utils.data.DataLoader(LoadImagesAndLabels(test_path, imgsz_test, batch_size, 179 | hyp=hyp, 180 | rect=True, 181 | cache_images=opt.cache_images, 182 | single_cls=opt.single_cls), 183 | batch_size=batch_size, 184 | num_workers=nw, 185 | pin_memory=True, 186 | collate_fn=dataset.collate_fn) 187 | 188 | # Model parameters 189 | hyp['cls'] *= nc / 80. # scale coco-tuned hyp['cls'] to current dataset 190 | model.nc = nc # attach number of classes to model 191 | model.hyp = hyp # attach hyperparameters to model 192 | model.gr = 1.0 # giou loss ratio (obj_loss = 1.0 or giou) 193 | model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) # attach class weights 194 | model.names = data_dict['names'] 195 | 196 | # Class frequency 197 | labels = np.concatenate(dataset.labels, 0) 198 | c = torch.tensor(labels[:, 0]) # classes 199 | # cf = torch.bincount(c.long(), minlength=nc) + 1. 200 | # model._initialize_biases(cf.to(device)) 201 | if tb_writer: 202 | plot_labels(labels) 203 | tb_writer.add_histogram('classes', c, 0) 204 | 205 | # Check anchors 206 | if not opt.noautoanchor: 207 | check_anchors(dataset, model=model, thr=hyp['anchor_t'], imgsz=imgsz) 208 | 209 | # Exponential moving average 210 | ema = torch_utils.ModelEMA(model) 211 | 212 | # Start training 213 | t0 = time.time() 214 | nb = len(dataloader) # number of batches 215 | n_burn = max(3 * nb, 1e3) # burn-in iterations, max(3 epochs, 1k iterations) 216 | maps = np.zeros(nc) # mAP per class 217 | results = (0, 0, 0, 0, 0, 0, 0) # 'P', 'R', 'mAP', 'F1', 'val GIoU', 'val Objectness', 'val Classification' 218 | print('Image sizes %g train, %g test' % (imgsz, imgsz_test)) 219 | print('Using %g dataloader workers' % nw) 220 | print('Starting training for %g epochs...' % epochs) 221 | # torch.autograd.set_detect_anomaly(True) 222 | for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------ 223 | model.train() 224 | 225 | # Update image weights (optional) 226 | if dataset.image_weights: 227 | w = model.class_weights.cpu().numpy() * (1 - maps) ** 2 # class weights 228 | image_weights = labels_to_image_weights(dataset.labels, nc=nc, class_weights=w) 229 | dataset.indices = random.choices(range(dataset.n), weights=image_weights, k=dataset.n) # rand weighted idx 230 | 231 | mloss = torch.zeros(4, device=device) # mean losses 232 | print(('\n' + '%10s' * 8) % ('Epoch', 'gpu_mem', 'GIoU', 'obj', 'cls', 'total', 'targets', 'img_size')) 233 | pbar = tqdm(enumerate(dataloader), total=nb) # progress bar 234 | for i, (imgs, targets, paths, _) in pbar: # batch ------------------------------------------------------------- 235 | ni = i + nb * epoch # number integrated batches (since train start) 236 | imgs = imgs.to(device).float() / 255.0 # uint8 to float32, 0 - 255 to 0.0 - 1.0 237 | 238 | # Burn-in 239 | if ni <= n_burn: 240 | xi = [0, n_burn] # x interp 241 | # model.gr = np.interp(ni, xi, [0.0, 1.0]) # giou loss ratio (obj_loss = 1.0 or giou) 242 | accumulate = max(1, np.interp(ni, xi, [1, nbs / batch_size]).round()) 243 | for j, x in enumerate(optimizer.param_groups): 244 | # bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0 245 | x['lr'] = np.interp(ni, xi, [0.1 if j == 2 else 0.0, x['initial_lr'] * lf(epoch)]) 246 | if 'momentum' in x: 247 | x['momentum'] = np.interp(ni, xi, [0.9, hyp['momentum']]) 248 | 249 | # Multi-scale 250 | if opt.multi_scale: 251 | sz = random.randrange(imgsz * 0.5, imgsz * 1.5 + gs) // gs * gs # size 252 | sf = sz / max(imgs.shape[2:]) # scale factor 253 | if sf != 1: 254 | ns = [math.ceil(x * sf / gs) * gs for x in imgs.shape[2:]] # new shape (stretched to gs-multiple) 255 | imgs = F.interpolate(imgs, size=ns, mode='bilinear', align_corners=False) 256 | 257 | # Forward 258 | pred = model(imgs) 259 | 260 | # Loss 261 | loss, loss_items = compute_loss(pred, targets.to(device), model) 262 | if not torch.isfinite(loss): 263 | print('WARNING: non-finite loss, ending training ', loss_items) 264 | return results 265 | 266 | # Backward 267 | if mixed_precision: 268 | with amp.scale_loss(loss, optimizer) as scaled_loss: 269 | scaled_loss.backward() 270 | else: 271 | loss.backward() 272 | 273 | # Optimize 274 | if ni % accumulate == 0: 275 | optimizer.step() 276 | optimizer.zero_grad() 277 | ema.update(model) 278 | 279 | # Print 280 | mloss = (mloss * i + loss_items) / (i + 1) # update mean losses 281 | mem = '%.3gG' % (torch.cuda.memory_cached() / 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 = 'train_batch%g.jpg' % i # filename 289 | res = plot_images(images=imgs, targets=targets, paths=paths, fname=f) 290 | if tb_writer: 291 | tb_writer.add_image(f, res, 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 | # mAP 300 | ema.update_attr(model) 301 | final_epoch = epoch + 1 == epochs 302 | if not opt.notest or final_epoch: # Calculate mAP 303 | results, maps, times = test.test(opt.data, 304 | batch_size=batch_size, 305 | imgsz=imgsz_test, 306 | save_json=final_epoch and opt.data.endswith(os.sep + 'coco.yaml'), 307 | model=ema.ema, 308 | single_cls=opt.single_cls, 309 | dataloader=testloader) 310 | 311 | # Write 312 | with open(results_file, 'a') as f: 313 | f.write(s + '%10.4g' * 7 % results + '\n') # P, R, mAP, F1, test_losses=(GIoU, obj, cls) 314 | if len(opt.name) and opt.bucket: 315 | os.system('gsutil cp results.txt gs://%s/results/results%s.txt' % (opt.bucket, opt.name)) 316 | 317 | # Tensorboard 318 | if tb_writer: 319 | tags = ['train/giou_loss', 'train/obj_loss', 'train/cls_loss', 320 | 'metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/F1', 321 | 'val/giou_loss', 'val/obj_loss', 'val/cls_loss'] 322 | for x, tag in zip(list(mloss[:-1]) + list(results), tags): 323 | tb_writer.add_scalar(tag, x, epoch) 324 | 325 | # Update best mAP 326 | fi = fitness(np.array(results).reshape(1, -1)) # fitness_i = weighted combination of [P, R, mAP, F1] 327 | if fi > best_fitness: 328 | best_fitness = fi 329 | 330 | # Save model 331 | save = (not opt.nosave) or (final_epoch and not opt.evolve) 332 | if save: 333 | with open(results_file, 'r') as f: # create checkpoint 334 | ckpt = {'epoch': epoch, 335 | 'best_fitness': best_fitness, 336 | 'training_results': f.read(), 337 | 'model': ema.ema.module if hasattr(model, 'module') else ema.ema, 338 | 'optimizer': None if final_epoch else optimizer.state_dict()} 339 | 340 | # Save last, best and delete 341 | torch.save(ckpt, last) 342 | if (best_fitness == fi) and not final_epoch: 343 | torch.save(ckpt, best) 344 | del ckpt 345 | 346 | # end epoch ---------------------------------------------------------------------------------------------------- 347 | # end training 348 | 349 | n = opt.name 350 | if len(n): 351 | n = '_' + n if not n.isnumeric() else n 352 | fresults, flast, fbest = 'results%s.txt' % n, wdir + 'last%s.pt' % n, wdir + 'best%s.pt' % n 353 | for f1, f2 in zip([wdir + 'last.pt', wdir + 'best.pt', 'results.txt'], [flast, fbest, fresults]): 354 | if os.path.exists(f1): 355 | os.rename(f1, f2) # rename 356 | ispt = f2.endswith('.pt') # is *.pt 357 | strip_optimizer(f2) if ispt else None # strip optimizer 358 | os.system('gsutil cp %s gs://%s/weights' % (f2, opt.bucket)) if opt.bucket and ispt else None # upload 359 | 360 | if not opt.evolve: 361 | plot_results() # save as results.png 362 | print('%g epochs completed in %.3f hours.\n' % (epoch - start_epoch + 1, (time.time() - t0) / 3600)) 363 | dist.destroy_process_group() if device.type != 'cpu' and torch.cuda.device_count() > 1 else None 364 | torch.cuda.empty_cache() 365 | return results 366 | 367 | 368 | if __name__ == '__main__': 369 | check_git_status() 370 | parser = argparse.ArgumentParser() 371 | parser.add_argument('--epochs', type=int, default=20000) 372 | parser.add_argument('--batch-size', type=int, default=4) 373 | parser.add_argument('--cfg', type=str, default='models/yolov5s.yaml', help='*.cfg path') 374 | parser.add_argument('--data', type=str, default='data/drive.yaml', help='*.data path') 375 | parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='train,test sizes') 376 | parser.add_argument('--rect', action='store_true', help='rectangular training') 377 | parser.add_argument('--resume', action='store_true', help='resume training from last.pt') 378 | parser.add_argument('--nosave', action='store_true', help='only save final checkpoint') 379 | parser.add_argument('--notest', action='store_true', help='only test final epoch') 380 | parser.add_argument('--noautoanchor', action='store_true', help='disable autoanchor check') 381 | parser.add_argument('--evolve', action='store_true', help='evolve hyperparameters') 382 | parser.add_argument('--bucket', type=str, default='', help='gsutil bucket') 383 | parser.add_argument('--cache-images', action='store_true', help='cache images for faster training') 384 | parser.add_argument('--weights', type=str, default=r'weights\yolov5s.pt', help='initial weights path') 385 | parser.add_argument('--name', default='', help='renames results.txt to results_name.txt if supplied') 386 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') 387 | parser.add_argument('--adam', action='store_true', help='use adam optimizer') 388 | parser.add_argument('--multi-scale', action='store_true', help='vary img-size +/- 50%') 389 | parser.add_argument('--single-cls', action='store_true', help='train as single-class dataset') 390 | opt = parser.parse_args() 391 | opt.weights = last if opt.resume else opt.weights 392 | opt.cfg = check_file(opt.cfg) # check file 393 | opt.data = check_file(opt.data) # check file 394 | opt.img_size.extend([opt.img_size[-1]] * (2 - len(opt.img_size))) # extend to 2 sizes (train, test) 395 | device = torch_utils.select_device(opt.device, apex=mixed_precision, batch_size=opt.batch_size) 396 | if device.type == 'cpu': 397 | mixed_precision = False 398 | 399 | # Train 400 | if not opt.evolve: 401 | tb_writer = SummaryWriter(comment=opt.name) 402 | print('Start Tensorboard with "tensorboard --logdir=runs", view at http://localhost:6006/') 403 | train(hyp) 404 | 405 | # Evolve hyperparameters (optional) 406 | else: 407 | tb_writer = None 408 | opt.notest, opt.nosave = True, True # only test/save final epoch 409 | if opt.bucket: 410 | os.system('gsutil cp gs://%s/evolve.txt .' % opt.bucket) # download evolve.txt if exists 411 | 412 | for _ in range(10): # generations to evolve 413 | if os.path.exists('evolve.txt'): # if evolve.txt exists: select best hyps and mutate 414 | # Select parent(s) 415 | parent = 'single' # parent selection method: 'single' or 'weighted' 416 | x = np.loadtxt('evolve.txt', ndmin=2) 417 | n = min(5, len(x)) # number of previous results to consider 418 | x = x[np.argsort(-fitness(x))][:n] # top n mutations 419 | w = fitness(x) - fitness(x).min() # weights 420 | if parent == 'single' or len(x) == 1: 421 | # x = x[random.randint(0, n - 1)] # random selection 422 | x = x[random.choices(range(n), weights=w)[0]] # weighted selection 423 | elif parent == 'weighted': 424 | x = (x * w.reshape(n, 1)).sum(0) / w.sum() # weighted combination 425 | 426 | # Mutate 427 | mp, s = 0.9, 0.2 # mutation probability, sigma 428 | npr = np.random 429 | npr.seed(int(time.time())) 430 | g = np.array([1, 1, 1, 1, 1, 1, 1, 0, .1, 1, 0, 1, 1, 1, 1, 1, 1, 1]) # gains 431 | ng = len(g) 432 | v = np.ones(ng) 433 | while all(v == 1): # mutate until a change occurs (prevent duplicates) 434 | v = (g * (npr.random(ng) < mp) * npr.randn(ng) * npr.random() * s + 1).clip(0.3, 3.0) 435 | for i, k in enumerate(hyp.keys()): # plt.hist(v.ravel(), 300) 436 | hyp[k] = x[i + 7] * v[i] # mutate 437 | 438 | # Clip to limits 439 | keys = ['lr0', 'iou_t', 'momentum', 'weight_decay', 'hsv_s', 'hsv_v', 'translate', 'scale', 'fl_gamma'] 440 | limits = [(1e-5, 1e-2), (0.00, 0.70), (0.60, 0.98), (0, 0.001), (0, .9), (0, .9), (0, .9), (0, .9), (0, 3)] 441 | for k, v in zip(keys, limits): 442 | hyp[k] = np.clip(hyp[k], v[0], v[1]) 443 | 444 | # Train mutation 445 | results = train(hyp.copy()) 446 | 447 | # Write mutation results 448 | print_mutation(hyp, results, opt.bucket) 449 | 450 | # Plot results 451 | # plot_evolution_results(hyp) 452 | -------------------------------------------------------------------------------- /train_batch0.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lieweiAI/action-detection/b8b174d363cf3dac4c94c7736126edc91838c81f/train_batch0.jpg -------------------------------------------------------------------------------- /train_batch1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lieweiAI/action-detection/b8b174d363cf3dac4c94c7736126edc91838c81f/train_batch1.jpg -------------------------------------------------------------------------------- /train_batch2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lieweiAI/action-detection/b8b174d363cf3dac4c94c7736126edc91838c81f/train_batch2.jpg -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lieweiAI/action-detection/b8b174d363cf3dac4c94c7736126edc91838c81f/utils/__init__.py -------------------------------------------------------------------------------- /utils/activations.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | import torch.nn as nn 5 | 6 | 7 | # Swish ------------------------------------------------------------------------ 8 | class SwishImplementation(torch.autograd.Function): 9 | @staticmethod 10 | def forward(ctx, x): 11 | ctx.save_for_backward(x) 12 | return x * torch.sigmoid(x) 13 | 14 | @staticmethod 15 | def backward(ctx, grad_output): 16 | x = ctx.saved_tensors[0] 17 | sx = torch.sigmoid(x) 18 | return grad_output * (sx * (1 + x * (1 - sx))) 19 | 20 | 21 | class MemoryEfficientSwish(nn.Module): 22 | @staticmethod 23 | def forward(x): 24 | return SwishImplementation.apply(x) 25 | 26 | 27 | class HardSwish(nn.Module): # https://arxiv.org/pdf/1905.02244.pdf 28 | @staticmethod 29 | def forward(x): 30 | return x * F.hardtanh(x + 3, 0., 6., True) / 6. 31 | 32 | 33 | class Swish(nn.Module): 34 | @staticmethod 35 | def forward(x): 36 | return x * torch.sigmoid(x) 37 | 38 | 39 | # Mish ------------------------------------------------------------------------ 40 | class MishImplementation(torch.autograd.Function): 41 | @staticmethod 42 | def forward(ctx, x): 43 | ctx.save_for_backward(x) 44 | return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x))) 45 | 46 | @staticmethod 47 | def backward(ctx, grad_output): 48 | x = ctx.saved_tensors[0] 49 | sx = torch.sigmoid(x) 50 | fx = F.softplus(x).tanh() 51 | return grad_output * (fx + x * sx * (1 - fx * fx)) 52 | 53 | 54 | class MemoryEfficientMish(nn.Module): 55 | @staticmethod 56 | def forward(x): 57 | return MishImplementation.apply(x) 58 | 59 | 60 | class Mish(nn.Module): # https://github.com/digantamisra98/Mish 61 | @staticmethod 62 | def forward(x): 63 | return x * F.softplus(x).tanh() 64 | -------------------------------------------------------------------------------- /utils/google_utils.py: -------------------------------------------------------------------------------- 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 time 7 | from pathlib import Path 8 | 9 | 10 | def attempt_download(weights): 11 | # Attempt to download pretrained weights if not found locally 12 | weights = weights.strip() 13 | msg = weights + ' missing, try downloading from https://drive.google.com/drive/folders/1Drs_Aiu7xx6S-ix95f9kNsA6ueKRpN2J' 14 | 15 | r = 1 16 | if len(weights) > 0 and not os.path.isfile(weights): 17 | d = {'yolov3-spp.pt': '1mM67oNw4fZoIOL1c8M3hHmj66d8e-ni_', # yolov3-spp.yaml 18 | 'yolov5s.pt': '1R5T6rIyy3lLwgFXNms8whc-387H0tMQO', # yolov5s.yaml 19 | 'yolov5m.pt': '1vobuEExpWQVpXExsJ2w-Mbf3HJjWkQJr', # yolov5m.yaml 20 | 'yolov5l.pt': '1hrlqD1Wdei7UT4OgT785BEk1JwnSvNEV', # yolov5l.yaml 21 | 'yolov5x.pt': '1mM8aZJlWTxOg7BZJvNUMrTnA2AbeCVzS', # yolov5x.yaml 22 | } 23 | 24 | file = Path(weights).name 25 | if file in d: 26 | r = gdrive_download(id=d[file], name=weights) 27 | 28 | if not (r == 0 and os.path.exists(weights) and os.path.getsize(weights) > 1E6): # weights exist and > 1MB 29 | os.remove(weights) if os.path.exists(weights) else None # remove partial downloads 30 | s = "curl -L -o %s 'https://storage.googleapis.com/ultralytics/yolov5/ckpt/%s'" % (weights, file) 31 | r = os.system(s) # execute, capture return values 32 | 33 | # Error check 34 | if not (r == 0 and os.path.exists(weights) and os.path.getsize(weights) > 1E6): # weights exist and > 1MB 35 | os.remove(weights) if os.path.exists(weights) else None # remove partial downloads 36 | raise Exception(msg) 37 | 38 | 39 | def gdrive_download(id='1HaXkef9z6y5l4vUnCYgdmEAj61c6bfWO', name='coco.zip'): 40 | # https://gist.github.com/tanaikech/f0f2d122e05bf5f971611258c22c110f 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 | os.system("curl -c ./cookie -s -L \"https://drive.google.com/uc?export=download&id=%s\" > /dev/null" % id) 51 | if os.path.exists('cookie'): # large file 52 | s = "curl -Lb ./cookie \"https://drive.google.com/uc?export=download&confirm=`awk '/download/ {print $NF}' ./cookie`&id=%s\" -o %s" % ( 53 | id, name) 54 | else: # small file 55 | s = "curl -s -L -o %s 'https://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 | # def upload_blob(bucket_name, source_file_name, destination_blob_name): 75 | # # Uploads a file to a bucket 76 | # # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python 77 | # 78 | # storage_client = storage.Client() 79 | # bucket = storage_client.get_bucket(bucket_name) 80 | # blob = bucket.blob(destination_blob_name) 81 | # 82 | # blob.upload_from_filename(source_file_name) 83 | # 84 | # print('File {} uploaded to {}.'.format( 85 | # source_file_name, 86 | # destination_blob_name)) 87 | # 88 | # 89 | # def download_blob(bucket_name, source_blob_name, destination_file_name): 90 | # # Uploads a blob from a bucket 91 | # storage_client = storage.Client() 92 | # bucket = storage_client.get_bucket(bucket_name) 93 | # blob = bucket.blob(source_blob_name) 94 | # 95 | # blob.download_to_filename(destination_file_name) 96 | # 97 | # print('Blob {} downloaded to {}.'.format( 98 | # source_blob_name, 99 | # destination_file_name)) 100 | -------------------------------------------------------------------------------- /utils/torch_utils.py: -------------------------------------------------------------------------------- 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='', apex=False, 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 ' + ('Apex ' if apex else '') # apex for mixed precision https://github.com/NVIDIA/apex 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 initialize_weights(model): 58 | for m in model.modules(): 59 | t = type(m) 60 | if t is nn.Conv2d: 61 | pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') 62 | elif t is nn.BatchNorm2d: 63 | m.eps = 1e-4 64 | m.momentum = 0.03 65 | elif t in [nn.LeakyReLU, nn.ReLU, nn.ReLU6]: 66 | m.inplace = True 67 | 68 | 69 | def find_modules(model, mclass=nn.Conv2d): 70 | # finds layer indices matching module class 'mclass' 71 | return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)] 72 | 73 | 74 | def fuse_conv_and_bn(conv, bn): 75 | # https://tehnokv.com/posts/fusing-batchnorm-and-conv/ 76 | with torch.no_grad(): 77 | # init 78 | fusedconv = torch.nn.Conv2d(conv.in_channels, 79 | conv.out_channels, 80 | kernel_size=conv.kernel_size, 81 | stride=conv.stride, 82 | padding=conv.padding, 83 | bias=True) 84 | 85 | # prepare filters 86 | w_conv = conv.weight.clone().view(conv.out_channels, -1) 87 | w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var))) 88 | fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.size())) 89 | 90 | # prepare spatial bias 91 | if conv.bias is not None: 92 | b_conv = conv.bias 93 | else: 94 | b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) 95 | b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps)) 96 | fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn) 97 | 98 | return fusedconv 99 | 100 | 101 | def model_info(model, verbose=False): 102 | # Plots a line-by-line description of a PyTorch model 103 | n_p = sum(x.numel() for x in model.parameters()) # number parameters 104 | n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients 105 | if verbose: 106 | print('%5s %40s %9s %12s %20s %10s %10s' % ('layer', 'name', 'gradient', 'parameters', 'shape', 'mu', 'sigma')) 107 | for i, (name, p) in enumerate(model.named_parameters()): 108 | name = name.replace('module_list.', '') 109 | print('%5g %40s %9s %12g %20s %10.3g %10.3g' % 110 | (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std())) 111 | 112 | try: # FLOPS 113 | from thop import profile 114 | macs, _ = profile(model, inputs=(torch.zeros(1, 3, 480, 640),), verbose=False) 115 | fs = ', %.1f GFLOPS' % (macs / 1E9 * 2) 116 | except: 117 | fs = '' 118 | 119 | print('Model Summary: %g layers, %g parameters, %g gradients%s' % (len(list(model.parameters())), n_p, n_g, fs)) 120 | 121 | 122 | def load_classifier(name='resnet101', n=2): 123 | # Loads a pretrained model reshaped to n-class output 124 | model = models.__dict__[name](pretrained=True) 125 | 126 | # Display model properties 127 | input_size = [3, 224, 224] 128 | input_space = 'RGB' 129 | input_range = [0, 1] 130 | mean = [0.485, 0.456, 0.406] 131 | std = [0.229, 0.224, 0.225] 132 | for x in [input_size, input_space, input_range, mean, std]: 133 | print(x + ' =', eval(x)) 134 | 135 | # Reshape output to n classes 136 | filters = model.fc.weight.shape[1] 137 | model.fc.bias = torch.nn.Parameter(torch.zeros(n), requires_grad=True) 138 | model.fc.weight = torch.nn.Parameter(torch.zeros(n, filters), requires_grad=True) 139 | model.fc.out_features = n 140 | return model 141 | 142 | 143 | def scale_img(img, ratio=1.0, same_shape=False): # img(16,3,256,416), r=ratio 144 | # scales img(bs,3,y,x) by ratio 145 | h, w = img.shape[2:] 146 | s = (int(h * ratio), int(w * ratio)) # new size 147 | img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize 148 | if not same_shape: # pad/crop img 149 | gs = 32 # (pixels) grid size 150 | h, w = [math.ceil(x * ratio / gs) * gs for x in (h, w)] 151 | return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean 152 | 153 | 154 | class ModelEMA: 155 | """ Model Exponential Moving Average from https://github.com/rwightman/pytorch-image-models 156 | Keep a moving average of everything in the model state_dict (parameters and buffers). 157 | This is intended to allow functionality like 158 | https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage 159 | A smoothed version of the weights is necessary for some training schemes to perform well. 160 | E.g. Google's hyper-params for training MNASNet, MobileNet-V3, EfficientNet, etc that use 161 | RMSprop with a short 2.4-3 epoch decay period and slow LR decay rate of .96-.99 requires EMA 162 | smoothing of weights to match results. Pay attention to the decay constant you are using 163 | relative to your update count per epoch. 164 | To keep EMA from using GPU resources, set device='cpu'. This will save a bit of memory but 165 | disable validation of the EMA weights. Validation will have to be done manually in a separate 166 | process, or after the training stops converging. 167 | This class is sensitive where it is initialized in the sequence of model init, 168 | GPU assignment and distributed training wrappers. 169 | I've tested with the sequence in my own train.py for torch.DataParallel, apex.DDP, and single-GPU. 170 | """ 171 | 172 | def __init__(self, model, decay=0.9999, device=''): 173 | # make a copy of the model for accumulating moving average of weights 174 | self.ema = deepcopy(model) 175 | self.ema.eval() 176 | self.updates = 0 # number of EMA updates 177 | self.decay = lambda x: decay * (1 - math.exp(-x / 2000)) # decay exponential ramp (to help early epochs) 178 | self.device = device # perform ema on different device from model if set 179 | if device: 180 | self.ema.to(device=device) 181 | for p in self.ema.parameters(): 182 | p.requires_grad_(False) 183 | 184 | def update(self, model): 185 | self.updates += 1 186 | d = self.decay(self.updates) 187 | with torch.no_grad(): 188 | if type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel): 189 | msd, esd = model.module.state_dict(), self.ema.module.state_dict() 190 | else: 191 | msd, esd = model.state_dict(), self.ema.state_dict() 192 | 193 | for k, v in esd.items(): 194 | if v.dtype.is_floating_point: 195 | v *= d 196 | v += (1. - d) * msd[k].detach() 197 | 198 | def update_attr(self, model): 199 | # Assign attributes (which may change during training) 200 | for k in model.__dict__.keys(): 201 | if not k.startswith('_'): 202 | setattr(self.ema, k, getattr(model, k)) 203 | -------------------------------------------------------------------------------- /utils/video2rgb.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | 3 | import os 4 | import cv2 5 | 6 | 7 | 8 | 9 | def video2frame(video_src_path, frame_save_path, interval): 10 | """ 11 | 将视频按固定间隔读取写入图片 12 | :param video_src_path: 视频存放路径 13 | :param frame_save_path: 保存路径 14 | :param interval: 保存帧间隔 15 | :return: 帧图片 16 | """ 17 | videos = os.listdir(video_src_path) 18 | for video in videos: 19 | if not video.endswith(".mp4"): 20 | videos.remove(video) 21 | 22 | for each_video in videos: 23 | each_video_name = each_video[:-4] 24 | video_save_name = each_video.split(".")[0] 25 | each_video_full_path = os.path.join(video_src_path, each_video) 26 | 27 | cap = cv2.VideoCapture(each_video_full_path) 28 | frame_index = 0 29 | frame_count = 0 30 | if cap.isOpened(): 31 | success = True 32 | else: 33 | success = False 34 | print("读取失败!") 35 | 36 | while (success): 37 | success, frame = cap.read() 38 | print("ok") 39 | if frame_index % interval == 0: 40 | cv2.imwrite("‪E://1.jpg", frame) 41 | frame_count += 1 42 | 43 | frame_index += 1 44 | 45 | cap.release() 46 | 47 | 48 | if __name__ == '__main__': 49 | videos_src_path = r"E:\videos" 50 | frames_save_path = r"‪E:\images" 51 | time_interval = 50 52 | video2frame(videos_src_path, frames_save_path, time_interval) 53 | 54 | -------------------------------------------------------------------------------- /weights/best.pt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lieweiAI/action-detection/b8b174d363cf3dac4c94c7736126edc91838c81f/weights/best.pt -------------------------------------------------------------------------------- /weights/download_weights.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Download common models 3 | 4 | python3 -c "from utils.google_utils import *; 5 | attempt_download('weights/yolov5s.pt'); 6 | attempt_download('weights/yolov5m.pt'); 7 | attempt_download('weights/yolov5l.pt'); 8 | attempt_download('weights/yolov5x.pt')" 9 | -------------------------------------------------------------------------------- /weights/last.pt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lieweiAI/action-detection/b8b174d363cf3dac4c94c7736126edc91838c81f/weights/last.pt -------------------------------------------------------------------------------- /weights/yolov5s.pt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lieweiAI/action-detection/b8b174d363cf3dac4c94c7736126edc91838c81f/weights/yolov5s.pt --------------------------------------------------------------------------------