├── .dockerignore ├── Dockerfile ├── LICENSE ├── README.md ├── README.pdf ├── README_YOLO_v5.md ├── README_v3.md ├── data ├── coco.yaml ├── coco128.yaml ├── get_coco2017.sh └── score.yaml ├── datasets ├── 01_check_img.py ├── 02_check_box.py ├── 03_train_val_split.py ├── 04_myData_label.py └── score │ ├── images │ └── readme │ └── labels │ └── readme ├── detect.py ├── gen_wts.py ├── hubconf.py ├── inference ├── images │ ├── bus.jpg │ └── zidane.jpg └── output │ ├── bus.jpg │ └── zidane.jpg ├── models ├── common.py ├── experimental.py ├── onnx_export.py ├── score │ └── yolov5x.yaml ├── yolo.py ├── yolov3-spp.yaml ├── yolov5l.yaml ├── yolov5m.yaml ├── yolov5s.yaml └── yolov5x.yaml ├── readmepic ├── readme1 │ ├── 82944393-f7644d80-9f4f-11ea-8b87-1a5b04f555f1.jpg │ ├── 83082816-59e54880-a039-11ea-8abe-ab90cc1ec4b0.jpeg │ ├── 84186698-c4d54d00-aa45-11ea-9bde-c632c1230ccd.png │ ├── 84200349-729f2680-aa5b-11ea-8f9a-604c9e01a658.png │ └── YOLOv4_author2.jpg └── readme2 │ ├── pic │ ├── 20200514_p6_5_247_one.jpg │ ├── 78174482-307bb800-740e-11ea-8b09-840693671042.png │ ├── 83666389-bab4d980-a581-11ea-898b-b25471d37b83.jpg │ ├── 83667626-8c37fe00-a583-11ea-997b-0923fe59b29b.jpeg │ ├── 83667635-90641b80-a583-11ea-8075-606316cebb9c.jpeg │ ├── 83667642-90fcb200-a583-11ea-8fa3-338bbf7da194.jpeg │ ├── 83667810-d7eaa780-a583-11ea-8de8-5cca0673d076.png │ ├── datalist.png │ ├── results.png │ ├── t1.jpg │ ├── test_batch0_gt.jpg │ ├── test_batch0_pred.jpg │ ├── train_batch0.jpg │ ├── train_batch1.jpg │ └── train_batch2.jpg │ └── 教程.md ├── requirements.txt ├── results.txt ├── runs └── readme ├── test.py ├── train.py ├── tutorial.ipynb ├── utils ├── __init__.py ├── activations.py ├── datasets.py ├── google_utils.py ├── torch_utils.py └── utils.py ├── weights ├── download_weights.sh └── readme └── yolov5_trt.py /.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 | -------------------------------------------------------------------------------- /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 | # Install dependencies (pip or conda) 5 | RUN pip install -U gsutil 6 | # RUN pip install -U -r requirements.txt 7 | 8 | # Create working directory 9 | RUN mkdir -p /usr/src/app 10 | WORKDIR /usr/src/app 11 | 12 | # Copy contents 13 | COPY . /usr/src/app 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 | ## [YOLO v5](https://github.com/ultralytics/yolov5)在医疗领域中消化内镜目标检测的应用 2 | 3 | ### YOLO v5训练自己数据集详细教程 4 | 5 | :bug: :bug: 现在YOLOv5 已经更新到6.0版本了,但是其训练方式同本Repo是一致的,只需要按照对应版本安装对应Python环境即可,其数据集的构建,配置文件的修改,训练方式等完全与本Repo一致! 6 | 7 | :bug: :bug: 我们提供了YOLOv5 TensorRT调用和INT8量化的C++和Python代码(其TensorRT加速方式不同于本Repo提供的TensorRT调用方式),有需要的大佬可在issues中留言! 8 | 9 | **Xu Jing** 10 | 11 | ------ 12 | :fire: 由于官方新版YOLO v5的backbone和部分参数调整,导致很多小伙伴下载最新官方预训练模型不可用,这里提供原版的YOLO v5的预训练模型的百度云盘下载地址 13 | 14 | 链接:https://pan.baidu.com/s/1SDwp6I_MnRLK45QdB3-yNw 15 | 提取码:423j 16 | 17 | ------ 18 | 19 | + YOLOv4还没有退热,YOLOv5已经发布! 20 | 21 | + 6月9日,Ultralytics公司开源了YOLOv5,离上一次YOLOv4发布不到50天。而且这一次的YOLOv5是完全基于PyTorch实现的! 22 | 23 | + YOLO v5的主要贡献者是YOLO v4中重点介绍的马赛克数据增强的作者 24 | 25 | 26 | 27 | 28 | 29 | 30 | > 本项目描述了如何基于自己的数据集训练YOLO v5 31 | 32 | 33 | 34 | 但是YOLO v4的二作提供给我们的信息和官方提供的还是有一些出入: 35 | 36 | 37 | 38 | 39 | #### 0.环境配置 40 | 41 | 安装必要的python package和配置相关环境 42 | 43 | ``` 44 | # python3.6 45 | # torch==1.3.0 46 | # torchvision==0.4.1 47 | 48 | # git clone yolo v5 repo 49 | git clone https://github.com/ultralytics/yolov5 # clone repo 50 | # 下载官方的样例数据(这一步可以省略) 51 | python3 -c "from yolov5.utils.google_utils import gdrive_download; gdrive_download('1n_oKgR81BJtqk75b00eAjdv03qVCQn2f','coco128.zip')" # download dataset 52 | cd yolov5 53 | # 安装必要的package 54 | pip3 install -U -r requirements.txt 55 | ``` 56 | 57 | #### 1.创建数据集的配置文件`dataset.yaml` 58 | 59 | [data/coco128.yaml](https://github.com/ultralytics/yolov5/blob/master/data/coco128.yaml)来自于COCO train2017数据集的前128个训练图像,可以基于该`yaml`修改自己数据集的`yaml`文件 60 | 61 | ```ymal 62 | # train and val datasets (image directory or *.txt file with image paths) 63 | train: ./datasets/score/images/train/ 64 | val: ./datasets/score/images/val/ 65 | 66 | # number of classes 67 | nc: 3 68 | 69 | # class names 70 | names: ['QP', 'NY', 'QG'] 71 | ``` 72 | 73 | #### 2.创建标注文件 74 | 75 | 可以使用LabelImg,Labme,[Labelbox](https://labelbox.com/), [CVAT](https://github.com/opencv/cvat)来标注数据,对于目标检测而言需要标注bounding box即可。然后需要将标注转换为和**darknet format**相同的标注形式,每一个图像生成一个`*.txt`的标注文件(如果该图像没有标注目标则不用创建`*.txt`文件)。创建的`*.txt`文件遵循如下规则: 76 | 77 | - 每一行存放一个标注类别 78 | - 每一行的内容包括`class x_center y_center width height` 79 | - Bounding box 的坐标信息是归一化之后的(0-1) 80 | - class label转化为index时计数是从0开始的 81 | 82 | ```python 83 | def convert(size, box): 84 | ''' 85 | 将标注的xml文件标注转换为darknet形的坐标 86 | ''' 87 | dw = 1./(size[0]) 88 | dh = 1./(size[1]) 89 | x = (box[0] + box[1])/2.0 - 1 90 | y = (box[2] + box[3])/2.0 - 1 91 | w = box[1] - box[0] 92 | h = box[3] - box[2] 93 | x = x*dw 94 | w = w*dw 95 | y = y*dh 96 | h = h*dh 97 | return (x,y,w,h) 98 | ``` 99 | 100 | 每一个标注`*.txt`文件存放在和图像相似的文件目录下,只需要将`/images/*.jpg`替换为`/lables/*.txt`即可(这个在加载数据时代码内部的处理就是这样的,可以自行修改为VOC的数据格式进行加载) 101 | 102 | 例如: 103 | 104 | ``` 105 | datasets/score/images/train/000000109622.jpg # image 106 | datasets/score/labels/train/000000109622.txt # label 107 | ``` 108 | 如果一个标注文件包含5个person类别(person在coco数据集中是排在第一的类别因此index为0): 109 | 110 | Screen Shot 2020-04-01 at 11 44 26 AM 111 | 112 | #### 3.组织训练集的目录 113 | 114 | 将训练集train和验证集val的images和labels文件夹按照如下的方式进行存放 115 | 116 | Screen Shot 2020-04-01 at 11 44 26 AM 117 | 118 | 至此数据准备阶段已经完成,过程中我们假设算法工程师的数据清洗和数据集的划分过程已经自行完成。 119 | 120 | #### 4.选择模型backbone进行模型配置文件的修改 121 | 122 | 在项目的`./models`文件夹下选择一个需要训练的模型,这里我们选择[yolov5x.yaml](https://github.com/ultralytics/yolov5/blob/master/models/yolov5x.yaml),最大的一个模型进行训练,参考官方README中的[table](https://github.com/ultralytics/yolov5#pretrained-checkpoints),了解不同模型的大小和推断速度。如果你选定了一个模型,那么需要修改模型对应的`yaml`文件 123 | 124 | ```yaml 125 | 126 | # parameters 127 | nc: 3 # number of classes <------------------ UPDATE to match your dataset 128 | depth_multiple: 1.33 # model depth multiple 129 | width_multiple: 1.25 # layer channel multiple 130 | 131 | # anchors 132 | anchors: 133 | - [10,13, 16,30, 33,23] # P3/8 134 | - [30,61, 62,45, 59,119] # P4/16 135 | - [116,90, 156,198, 373,326] # P5/32 136 | 137 | # yolov5 backbone 138 | backbone: 139 | # [from, number, module, args] 140 | [[-1, 1, Focus, [64, 3]], # 1-P1/2 141 | [-1, 1, Conv, [128, 3, 2]], # 2-P2/4 142 | [-1, 3, Bottleneck, [128]], 143 | [-1, 1, Conv, [256, 3, 2]], # 4-P3/8 144 | [-1, 9, BottleneckCSP, [256]], 145 | [-1, 1, Conv, [512, 3, 2]], # 6-P4/16 146 | [-1, 9, BottleneckCSP, [512]], 147 | [-1, 1, Conv, [1024, 3, 2]], # 8-P5/32 148 | [-1, 1, SPP, [1024, [5, 9, 13]]], 149 | [-1, 6, BottleneckCSP, [1024]], # 10 150 | ] 151 | 152 | # yolov5 head 153 | head: 154 | [[-1, 3, BottleneckCSP, [1024, False]], # 11 155 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 12 (P5/32-large) 156 | 157 | [-2, 1, nn.Upsample, [None, 2, 'nearest']], 158 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 159 | [-1, 1, Conv, [512, 1, 1]], 160 | [-1, 3, BottleneckCSP, [512, False]], 161 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 17 (P4/16-medium) 162 | 163 | [-2, 1, nn.Upsample, [None, 2, 'nearest']], 164 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 165 | [-1, 1, Conv, [256, 1, 1]], 166 | [-1, 3, BottleneckCSP, [256, False]], 167 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 22 (P3/8-small) 168 | 169 | [[], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 170 | ] 171 | 172 | ``` 173 | 174 | #### 5.Train 175 | 176 | ```bash 177 | # Train yolov5x on score for 300 epochs 178 | 179 | $ python3 train.py --img-size 640 --batch-size 16 --epochs 300 --data ./data/score.yaml --cfg ./models/score/yolov5x.yaml --weights weights/yolov5x.pt 180 | 181 | ``` 182 | 183 | 184 | #### 6.Visualize 185 | 186 | 开始训练后,查看`train*.jpg`图片查看训练数据,标签和数据增强,如果你的图像显示标签或数据增强不正确,你应该查看你的数据集的构建过程是否有问题 187 | 188 | Screen Shot 2020-04-01 at 11 44 26 AM 189 | 190 | 一个训练epoch完成后,查看`test_batch0_gt.jpg`查看batch 0 ground truth的labels 191 | 192 | 193 | Screen Shot 2020-04-01 at 11 44 26 AM 194 | 195 | 查看`test_batch0_pred.jpg`查看test batch 0的预测 196 | 197 | Screen Shot 2020-04-01 at 11 44 26 AM 198 | 199 | 训练的losses和评价指标被保存在Tensorboard和`results.txt`log文件。`results.txt`在训练结束后会被可视化为`results.png` 200 | 201 | ```python 202 | >>> from utils.utils import plot_results 203 | >>> plot_results() 204 | # 如果你是用远程连接请安装配置Xming: https://blog.csdn.net/akuoma/article/details/82182913 205 | ``` 206 | 207 | Screen Shot 2020-04-01 at 11 44 26 AM 208 | 209 | #### 7.推断 210 | 211 | ```python 212 | $ python3 detect.py --source file.jpg # image 213 | file.mp4 # video 214 | ./dir # directory 215 | 0 # webcam 216 | rtsp://170.93.143.139/rtplive/470011e600ef003a004ee33696235daa # rtsp stream 217 | http://112.50.243.8/PLTV/88888888/224/3221225900/1.m3u8 # http stream 218 | ```` 219 | 220 | 221 | ```python 222 | # inference /home/myuser/xujing/EfficientDet-Pytorch/dataset/test/ 文件夹下的图像 223 | $ python3 detect.py --source /home/myuser/xujing/EfficientDet-Pytorch/dataset/test/ --weights weights/best.pt --conf 0.1 224 | 225 | $ python3 detect.py --source ./inference/images/ --weights weights/yolov5x.pt --conf 0.5 226 | 227 | # inference 视频 228 | $ python3 detect.py --source test.mp4 --weights weights/yolov5x.pt --conf 0.4 229 | ``` 230 | 231 | Screen Shot 2020-04-01 at 11 44 26 AM 232 | 233 | Screen Shot 2020-04-01 at 11 44 26 AM 234 | 235 | #### 8.YOLOv5的TensorRT加速 236 | 237 | [请到这里来](./README_v3.md) 238 | 239 | 240 | **Reference** 241 | 242 | [1].https://github.com/ultralytics/yolov5 243 | 244 | [2].https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data 245 | -------------------------------------------------------------------------------- /README.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DataXujing/YOLO-v5/ead1c141106f114d92dddafb6ac8c57d7e96afb4/README.pdf -------------------------------------------------------------------------------- /README_YOLO_v5.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 Latency measures end-to-end latency per image averaged over 5000 COCO val2017 images using a V100 GPU with batch size 32, and includes image preprocessing, PyTorch FP32 inference, postprocessing and NMS. 8 | 9 | - **June 9, 2020**: [CSP](https://github.com/WongKinYiu/CrossStagePartialNetworks) updates to all YOLOv5 models. New models are faster, smaller and more accurate. Credit to @WongKinYiu for his excellent work with CSP. 10 | - **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. 11 | - **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. 12 | 13 | 14 | ## Pretrained Checkpoints 15 | 16 | | Model | APval | APtest | AP50 | LatencyGPU | FPSGPU || params | FLOPs | 17 | |---------- |------ |------ |------ | -------- | ------| ------ |------ | :------: | 18 | | YOLOv5-s ([ckpt](https://drive.google.com/open?id=1Drs_Aiu7xx6S-ix95f9kNsA6ueKRpN2J)) | 35.5 | 35.5 | 55.0 | **2.5ms** | **400** || 7.1M | 12.6B 19 | | YOLOv5-m ([ckpt](https://drive.google.com/open?id=1Drs_Aiu7xx6S-ix95f9kNsA6ueKRpN2J)) | 42.7 | 42.7 | 62.4 | 4.4ms | 227 || 22.0M | 39.0B 20 | | YOLOv5-l ([ckpt](https://drive.google.com/open?id=1Drs_Aiu7xx6S-ix95f9kNsA6ueKRpN2J)) | 45.7 | 45.9 | 65.1 | 6.8ms | 147 || 50.3M | 89.0B 21 | | YOLOv5-x ([ckpt](https://drive.google.com/open?id=1Drs_Aiu7xx6S-ix95f9kNsA6ueKRpN2J)) | **47.2** | **47.3** | **66.6** | 11.7ms | 85 || 95.9M | 170.3B 22 | | YOLOv3-SPP ([ckpt](https://drive.google.com/open?id=1Drs_Aiu7xx6S-ix95f9kNsA6ueKRpN2J)) | 45.6 | 45.5 | 65.2 | 7.9ms | 127 || 63.0M | 118.0B 23 | 24 | ** APtest denotes COCO [test-dev2017](http://cocodataset.org/#upload) server results, all other AP results in the table denote val2017 accuracy. 25 | ** 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` 26 | ** LatencyGPU measures end-to-end latency 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 FP32 inference at batch size 32, postprocessing and NMS. Average NMS time included in this chart is 1-2ms/img. Reproduce by `python test.py --img 640 --conf 0.1` 27 | ** All checkpoints are trained to 300 epochs with default settings and hyperparameters (no autoaugmentation). 28 | 29 | 30 | ## Requirements 31 | 32 | Python 3.7 or later with all `requirements.txt` dependencies installed, including `torch >= 1.5`. To install run: 33 | ```bash 34 | $ pip install -U -r requirements.txt 35 | ``` 36 | 37 | 38 | ## Tutorials 39 | 40 | * Open In Colab 41 | * [Train Custom Data](https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data) 42 | * [Google Cloud Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/GCP-Quickstart) 43 | * [Docker Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/Docker-Quickstart) 44 | 45 | 46 | ## Inference 47 | 48 | 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`. 49 | ```bash 50 | $ python detect.py --source file.jpg # image 51 | file.mp4 # video 52 | ./dir # directory 53 | 0 # webcam 54 | rtsp://170.93.143.139/rtplive/470011e600ef003a004ee33696235daa # rtsp stream 55 | http://112.50.243.8/PLTV/88888888/224/3221225900/1.m3u8 # http stream 56 | ``` 57 | 58 | To run inference on examples in the `./inference/images` folder: 59 | 60 | ```bash 61 | $ python detect.py --source ./inference/images/ --weights yolov5s.pt --conf 0.4 62 | 63 | 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') 64 | Using CUDA device0 _CudaDeviceProperties(name='Tesla P100-PCIE-16GB', total_memory=16280MB) 65 | 66 | Downloading https://drive.google.com/uc?export=download&id=1R5T6rIyy3lLwgFXNms8whc-387H0tMQO as yolov5s.pt... Done (2.6s) 67 | 68 | image 1/2 inference/images/bus.jpg: 640x512 3 persons, 1 buss, Done. (0.009s) 69 | image 2/2 inference/images/zidane.jpg: 384x640 2 persons, 2 ties, Done. (0.009s) 70 | Results saved to /content/yolov5/inference/output 71 | ``` 72 | 73 | 74 | 75 | ## Reproduce Our Training 76 | 77 | Run command below. Training times for yolov5s/m/l/x are 2/4/6/8 days on a single V100 (multi-GPU times faster). 78 | ```bash 79 | $ python train.py --data coco.yaml --cfg yolov5s.yaml --weights '' --batch-size 16 80 | ``` 81 | 82 | 83 | 84 | ## Reproduce Our Environment 85 | 86 | To access an up-to-date working environment (with all dependencies including CUDA/CUDNN, Python and PyTorch preinstalled), consider a: 87 | 88 | - **GCP** Deep Learning VM with $300 free credit offer: See our [GCP Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/GCP-Quickstart) 89 | - **Google Colab Notebook** with 12 hours of free GPU time. Open In Colab 90 | - **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) 91 | 92 | 93 | ## Citation 94 | 95 | [![DOI](https://zenodo.org/badge/146165888.svg)](https://zenodo.org/badge/latestdoi/146165888) 96 | 97 | 98 | ## About Us 99 | 100 | 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: 101 | - **Cloud-based AI** surveillance systems operating on **hundreds of HD video streams in realtime.** 102 | - **Edge AI** integrated into custom iOS and Android apps for realtime **30 FPS video inference.** 103 | - **Custom data training**, hyperparameter evolution, and model exportation to any destination. 104 | 105 | For business inquiries and professional support requests please visit us at https://www.ultralytics.com. 106 | 107 | 108 | ## Contact 109 | 110 | **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. 111 | -------------------------------------------------------------------------------- /README_v3.md: -------------------------------------------------------------------------------- 1 | ### YOLO v5转TensorRT模型并调用 2 | 3 | ### 0.pt模型转wts模型 4 | 5 | ``` 6 | python3 gen_wts.py 7 | # 注意修改代码中模型保存和模型加载的路径 8 | ``` 9 | 10 | 11 | 12 | ### 1.修改部分文件 13 | 14 | + 0.修改CMakeLists.txt 15 | 16 | ``` 17 | cmake_minimum_required(VERSION 2.6) 18 | 19 | project(yolov5) 20 | 21 | add_definitions(-std=c++11) 22 | 23 | option(CUDA_USE_STATIC_CUDA_RUNTIME OFF) 24 | set(CMAKE_CXX_STANDARD 11) 25 | set(CMAKE_BUILD_TYPE Debug) 26 | 27 | find_package(CUDA REQUIRED) 28 | 29 | set(CUDA_NVCC_PLAGS ${CUDA_NVCC_PLAGS};-std=c++11;-g;-G;-gencode;arch=compute_30;code=sm_30) 30 | 31 | include_directories(${PROJECT_SOURCE_DIR}/include) 32 | # include and link dirs of cuda and tensorrt, you need adapt them if yours are different 33 | # cuda 34 | include_directories(/usr/local/cuda/include) 35 | link_directories(/usr/local/cuda/lib64) 36 | 37 | # tensorrt <------------------ 38 | #include_directories(/usr/include/x86_64-linux-gnu/) 39 | #link_directories(/usr/lib/x86_64-linux-gnu/) 40 | 41 | include_directories(/home/myuser/xujing/TensorRT-7.0.0.11/) 42 | link_directories(/home/myuser/xujing/TensorRT-7.0.0.11/) 43 | 44 | 45 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall -Ofast -Wfatal-errors -D_MWAITXINTRIN_H_INCLUDED") 46 | 47 | cuda_add_library(myplugins SHARED ${PROJECT_SOURCE_DIR}/yololayer.cu) 48 | target_link_libraries(myplugins nvinfer cudart) 49 | 50 | find_package(OpenCV) 51 | include_directories(OpenCV_INCLUDE_DIRS) 52 | 53 | add_executable(yolov5 ${PROJECT_SOURCE_DIR}/yolov5.cpp) 54 | target_link_libraries(yolov5 nvinfer) 55 | target_link_libraries(yolov5 cudart) 56 | target_link_libraries(yolov5 myplugins) 57 | target_link_libraries(yolov5 ${OpenCV_LIBS}) 58 | 59 | add_definitions(-O2 -pthread) 60 | 61 | 62 | ``` 63 | 64 | 65 | 66 | + 1.把tensorRT安装包下的bin文件的内容copy到yolov5文件夹 67 | ![](pic/p1.png) 68 | + 2.修改yololayer.h 69 | 70 | ```c++ 71 | static constexpr int MAX_OUTPUT_BBOX_COUNT = 1000; //20000 72 | static constexpr int CLASS_NUM = 17; //需要修改 73 | static constexpr int INPUT_H = 640; //需要修改 74 | static constexpr int INPUT_W = 640; //需要修改 75 | ``` 76 | 77 | 78 | 79 | + 3.修改yolov5.cpp 80 | 81 | ```c++ 82 | #define NET x // s m l x 修改网络类型,我们用的是x 83 | #define NETSTRUCT(str) createEngine_##str 84 | #define CREATENET(net) NETSTRUCT(net) 85 | #define STR1(x) #x 86 | #define STR2(x) STR1(x) 87 | 88 | // #define USE_FP16 // comment out this if want to use FP32 89 | #define DEVICE 0 // GPU id 90 | #define NMS_THRESH 0.45 91 | #define CONF_THRESH 0.25 92 | #define BATCH_SIZE 1 93 | ``` 94 | 95 | 96 | 97 | ### 2.编译YOLOv5 98 | 99 | ```shell 100 | 1. generate yolov5s.wts from pytorch with yolov5s.pt, or download .wts from model zoo 101 | 102 | git clone https://github.com/wang-xinyu/tensorrtx.git 103 | git clone https://github.com/ultralytics/yolov5.git 104 | // download its weights 'yolov5s.pt' 105 | // copy tensorrtx/yolov5/gen_wts.py into ultralytics/yolov5 106 | // ensure the file name is yolov5s.pt and yolov5s.wts in gen_wts.py 107 | // go to ultralytics/yolov5 108 | python gen_wts.py 109 | // a file 'yolov5s.wts' will be generated. 110 | 111 | 2. build tensorrtx/yolov5 and run 112 | 113 | // put yolov5s.wts into tensorrtx/yolov5 114 | // go to tensorrtx/yolov5 115 | // ensure the macro NET in yolov5.cpp is s 116 | mkdir build 117 | cd build 118 | cmake .. 119 | make 120 | ``` 121 | 122 | ### 3.序列化引擎 123 | 124 | ```shell 125 | sudo ./yolov5 -s // serialize model to plan file i.e. 'yolov5s.engine' 126 | # 测试序列化的引擎是否可用 127 | sudo ./yolov5 -d ./sample // deserialize plan file and run inference, the images in samples will be processed. 128 | ``` 129 | 130 | 131 | 132 | ### 4.YOLO v5 tensorRT加速Python调用 133 | 134 | ``` 135 | python3 yolov5_trt.py 136 | # 注意修改模型类别,序列化引擎加载的路径,测试图像的路径 137 | ``` 138 | 139 | 140 | 141 | 142 | 143 | #### Reference 144 | 145 | https://github.com/wang-xinyu/tensorrtx/tree/master/yolov5 146 | 147 | https://github.com/wang-xinyu/tensorrtx/blob/master/tutorials/run_on_windows.md -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /data/score.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: ./datasets/score/images/train/ 12 | val: ./datasets/score/images/val/ 13 | 14 | # number of classes 15 | nc: 3 16 | 17 | # class names 18 | names: ['QP', 'NY', 'QG'] -------------------------------------------------------------------------------- /datasets/01_check_img.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import os 3 | import shutil 4 | 5 | def check_img(img_path): 6 | imgs = os.listdir(img_path) 7 | for img in imgs: 8 | if img.split(".")[-1] !="jpg": 9 | print(img) 10 | shutil.move(img_path+"/"+img,"./error/"+img) 11 | 12 | def check_anno(anno_path): 13 | anno_files = os.listdir(anno_path) 14 | for file in anno_files: 15 | if file.split(".")[-1] !="xml": 16 | print(file) 17 | shutil.move(anno_path+"/"+file,"./error/"+file) 18 | 19 | def ckeck_img_label(img_path,anno_path): 20 | imgs = os.listdir(img_path) 21 | anno_files = os.listdir(anno_path) 22 | 23 | files = [i.split(".")[0] for i in anno_files] 24 | 25 | 26 | for img in imgs: 27 | if img.split(".")[0] not in files: 28 | print(img) 29 | shutil.move(img_path+"/"+img,"./error/"+img) 30 | 31 | imgs = os.listdir(img_path) 32 | images = [j.split(".")[0] for j in imgs] 33 | 34 | for file in anno_files: 35 | if file.split(".")[0] not in images: 36 | print(file) 37 | shutil.move(anno_path+"/"+file,"./error/"+file) 38 | 39 | 40 | if __name__ == "__main__": 41 | img_path = "./myData/JPEGImages" 42 | anno_path = "./myData/Annotations" 43 | 44 | print("============check image=========") 45 | check_img(img_path) 46 | 47 | print("============check anno==========") 48 | check_anno(anno_path) 49 | print("============check both==========") 50 | ckeck_img_label(img_path,anno_path) 51 | -------------------------------------------------------------------------------- /datasets/02_check_box.py: -------------------------------------------------------------------------------- 1 | import xml.etree.ElementTree as xml_tree 2 | import pandas as pd 3 | import numpy as np 4 | import os 5 | import shutil 6 | 7 | 8 | def check_box(path): 9 | files = os.listdir(path) 10 | i = 0 11 | for anna_file in files: 12 | tree = xml_tree.parse(path+"/"+anna_file) 13 | root = tree.getroot() 14 | 15 | # Image shape. 16 | size = root.find('size') 17 | shape = [int(size.find('height').text), 18 | int(size.find('width').text), 19 | int(size.find('depth').text)] 20 | # Find annotations. 21 | bboxes = [] 22 | labels = [] 23 | labels_text = [] 24 | difficult = [] 25 | truncated = [] 26 | 27 | for obj in root.findall('object'): 28 | # label = obj.find('name').text 29 | # labels.append(int(dataset_common.VOC_LABELS[label][0])) 30 | # # labels_text.append(label.encode('ascii')) 31 | # labels_text.append(label.encode('utf-8')) 32 | 33 | 34 | # isdifficult = obj.find('difficult') 35 | # if isdifficult is not None: 36 | # difficult.append(int(isdifficult.text)) 37 | # else: 38 | # difficult.append(0) 39 | 40 | # istruncated = obj.find('truncated') 41 | # if istruncated is not None: 42 | # truncated.append(int(istruncated.text)) 43 | # else: 44 | # truncated.append(0) 45 | 46 | bbox = obj.find('bndbox') 47 | # bboxes.append((float(bbox.find('ymin').text) / shape[0], 48 | # float(bbox.find('xmin').text) / shape[1], 49 | # float(bbox.find('ymax').text) / shape[0], 50 | # float(bbox.find('xmax').text) / shape[1] 51 | # )) 52 | if (float(bbox.find('ymin').text) >= float(bbox.find('ymax').text)) or (float(bbox.find('xmin').text) >= float(bbox.find('xmax').text)): 53 | print(anna_file) 54 | i += 1 55 | try: 56 | shutil.move(path+"/"+anna_file,"./error2/"+anna_file) 57 | shutil.move("./myData/JPEGImages/"+anna_file.split(".")[0]+".jpg","./error2/"+anna_file.split(".")[0]+".jpg") 58 | except: 59 | pass 60 | 61 | print(i) 62 | 63 | 64 | 65 | if __name__ == "__main__": 66 | check_box("./myData/Annotations") -------------------------------------------------------------------------------- /datasets/03_train_val_split.py: -------------------------------------------------------------------------------- 1 | import os 2 | import random 3 | 4 | trainval_percent = 0.1 5 | train_percent = 0.9 6 | xmlfilepath = 'Annotations' 7 | txtsavepath = 'ImageSets/Main' 8 | total_xml = os.listdir(xmlfilepath) 9 | 10 | num = len(total_xml) 11 | lists = range(num) 12 | 13 | tr = int(num * train_percent) 14 | train = random.sample(lists, tr) 15 | 16 | 17 | ftrain = open('./ImageSets/Main/train.txt', 'w') 18 | fval = open('./ImageSets/Main/val.txt', 'w') 19 | 20 | for i in lists: 21 | name = total_xml[i][:-4] + '\n' 22 | if i in train: 23 | ftrain.write(name) 24 | else: 25 | fval.write(name) 26 | 27 | 28 | 29 | ftrain.close() 30 | fval.close() 31 | 32 | # voc Main/train,val 图像名生成 -------------------------------------------------------------------------------- /datasets/04_myData_label.py: -------------------------------------------------------------------------------- 1 | 2 | # _*_ coding:utf-8 _*_ 3 | import xml.etree.ElementTree as ET 4 | import pickle 5 | import os 6 | from os import listdir, getcwd 7 | from os.path import join 8 | import cv2 9 | 10 | # sets=[('myData', 'train'),('myData', 'val'), ('myData', 'test')] # 根据自己数据去定义 11 | sets=[('score', 'train'),('score', 'val')] # 根据自己数据去定义 12 | 13 | class2id = {'QP':0,"NY":1,"QG":2} 14 | # classes = ["plane", "boat", "person"] # 根据自己的类别去定义 15 | 16 | 17 | def convert(size, box): 18 | dw = 1./(size[0]) 19 | dh = 1./(size[1]) 20 | x = (box[0] + box[1])/2.0 - 1 21 | y = (box[2] + box[3])/2.0 - 1 22 | w = box[1] - box[0] 23 | h = box[3] - box[2] 24 | x = x*dw 25 | w = w*dw 26 | y = y*dh 27 | h = h*dh 28 | return (x,y,w,h) 29 | 30 | def convert_annotation(year, image_id,image_set): 31 | in_file = open('./score/Annotations/%s.xml'%(image_id),encoding="utf-8") 32 | out_file = open('./labels/%s/%s.txt'%(image_set,image_id), 'w') 33 | # print(in_file) 34 | tree=ET.parse(in_file) 35 | root = tree.getroot() 36 | # size = root.find('size') 37 | # w = int(size.find('width').text) 38 | # h = int(size.find('height').text) 39 | 40 | img = cv2.imread("./score/JPEGImages/"+image_id+".jpg") 41 | sp = img.shape 42 | 43 | h = sp[0] #height(rows) of image 44 | w = sp[1] #width(colums) of image 45 | 46 | for obj in root.iter('object'): 47 | difficult = obj.find('difficult').text 48 | cls_ = obj.find('name').text 49 | if cls_ not in list(class2id.keys()): 50 | print("没有该label: {}".format(cls_)) 51 | continue 52 | cls_id = class2id[cls_] 53 | xmlbox = obj.find('bndbox') 54 | b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text), float(xmlbox.find('ymax').text)) 55 | bb = convert((w,h), b) 56 | out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n') 57 | 58 | wd = getcwd() 59 | 60 | for year, image_set in sets: 61 | if not os.path.exists('./labels/'+image_set): 62 | os.makedirs('./labels/'+image_set) 63 | image_ids = open('./score/ImageSets/Main/%s.txt'%(image_set)).read().strip().split() 64 | list_file = open('./%s_%s.txt'%(year, image_set), 'w') 65 | for image_id in image_ids: 66 | list_file.write('%s/JPEGImages/%s.jpg\n'%(wd, image_id)) # 写了train或val的list 67 | convert_annotation(year, image_id,image_set) 68 | list_file.close() 69 | 70 | 71 | # labels/标注数据有了 72 | # train val的list数据也有了 73 | -------------------------------------------------------------------------------- /datasets/score/images/readme: -------------------------------------------------------------------------------- 1 | 此处存放训练和验证图片! -------------------------------------------------------------------------------- /datasets/score/labels/readme: -------------------------------------------------------------------------------- 1 | 此处存放训练和验证label! -------------------------------------------------------------------------------- /detect.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | from utils.datasets import * 4 | from utils.utils import * 5 | 6 | 7 | def detect(save_img=False): 8 | out, source, weights, half, view_img, save_txt, imgsz = \ 9 | opt.output, opt.source, opt.weights, opt.half, opt.view_img, opt.save_txt, opt.img_size 10 | webcam = source == '0' or source.startswith('rtsp') or source.startswith('http') or source.endswith('.txt') 11 | 12 | # Initialize 13 | device = torch_utils.select_device(opt.device) 14 | if os.path.exists(out): 15 | shutil.rmtree(out) # delete output folder 16 | os.makedirs(out) # make new output folder 17 | 18 | # Load model 19 | google_utils.attempt_download(weights) 20 | model = torch.load(weights, map_location=device)['model'] 21 | # torch.save(torch.load(weights, map_location=device), weights) # update model if SourceChangeWarning 22 | # model.fuse() 23 | model.to(device).eval() 24 | 25 | # Second-stage classifier 26 | classify = False 27 | if classify: 28 | modelc = torch_utils.load_classifier(name='resnet101', n=2) # initialize 29 | modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']) # load weights 30 | modelc.to(device).eval() 31 | 32 | # Half precision 33 | half = half and device.type != 'cpu' # half precision only supported on CUDA 34 | if half: 35 | model.half() 36 | 37 | # Set Dataloader 38 | vid_path, vid_writer = None, None 39 | if webcam: 40 | view_img = True 41 | torch.backends.cudnn.benchmark = True # set True to speed up constant image size inference 42 | dataset = LoadStreams(source, img_size=imgsz) 43 | else: 44 | save_img = True 45 | dataset = LoadImages(source, img_size=imgsz) 46 | 47 | # Get names and colors 48 | names = model.names if hasattr(model, 'names') else model.modules.names 49 | colors = [[random.randint(0, 255) for _ in range(3)] for _ in range(len(names))] 50 | 51 | # Run inference 52 | t0 = time.time() 53 | img = torch.zeros((1, 3, imgsz, imgsz), device=device) # init img 54 | _ = model(img.half() if half else img.float()) if device.type != 'cpu' else None # run once 55 | for path, img, im0s, vid_cap in dataset: 56 | img = torch.from_numpy(img).to(device) 57 | img = img.half() if half else img.float() # uint8 to fp16/32 58 | img /= 255.0 # 0 - 255 to 0.0 - 1.0 59 | if img.ndimension() == 3: 60 | img = img.unsqueeze(0) 61 | 62 | # Inference 63 | t1 = torch_utils.time_synchronized() 64 | pred = model(img, augment=opt.augment)[0] 65 | t2 = torch_utils.time_synchronized() 66 | 67 | # to float 68 | if half: 69 | pred = pred.float() 70 | 71 | # Apply NMS 72 | pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, 73 | fast=True, classes=opt.classes, agnostic=opt.agnostic_nms) 74 | 75 | # Apply Classifier 76 | if classify: 77 | pred = apply_classifier(pred, modelc, img, im0s) 78 | 79 | # Process detections 80 | for i, det in enumerate(pred): # detections per image 81 | if webcam: # batch_size >= 1 82 | p, s, im0 = path[i], '%g: ' % i, im0s[i].copy() 83 | else: 84 | p, s, im0 = path, '', im0s 85 | 86 | save_path = str(Path(out) / Path(p).name) 87 | s += '%gx%g ' % img.shape[2:] # print string 88 | gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] #  normalization gain whwh 89 | if det is not None and len(det): 90 | # Rescale boxes from img_size to im0 size 91 | det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round() 92 | 93 | # Print results 94 | for c in det[:, -1].unique(): 95 | n = (det[:, -1] == c).sum() # detections per class 96 | s += '%g %ss, ' % (n, names[int(c)]) # add to string 97 | 98 | # Write results 99 | for *xyxy, conf, cls in det: 100 | if save_txt: # Write to file 101 | xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh 102 | with open(save_path[:save_path.rfind('.')] + '.txt', 'a') as file: 103 | file.write(('%g ' * 5 + '\n') % (cls, *xywh)) # label format 104 | 105 | if save_img or view_img: # Add bbox to image 106 | label = '%s %.2f' % (names[int(cls)], conf) 107 | plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3) 108 | 109 | # Print time (inference + NMS) 110 | print('%sDone. (%.3fs)' % (s, t2 - t1)) 111 | 112 | # Stream results 113 | if view_img: 114 | cv2.imshow(p, im0) 115 | if cv2.waitKey(1) == ord('q'): # q to quit 116 | raise StopIteration 117 | 118 | # Save results (image with detections) 119 | if save_img: 120 | if dataset.mode == 'images': 121 | cv2.imwrite(save_path, im0) 122 | else: 123 | font = cv2.FONT_HERSHEY_SIMPLEX 124 | cv2.putText(im0,"YOLO v5 | by Xujing | Tesla V100 32G",(40,40),font, 0.7, (0, 255, 0), 2) 125 | if vid_path != save_path: # new video 126 | vid_path = save_path 127 | if isinstance(vid_writer, cv2.VideoWriter): 128 | vid_writer.release() # release previous video writer 129 | 130 | fps = vid_cap.get(cv2.CAP_PROP_FPS) 131 | w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) 132 | h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) 133 | vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*opt.fourcc), fps, (w, h)) 134 | vid_writer.write(im0) 135 | 136 | if save_txt or save_img: 137 | print('Results saved to %s' % os.getcwd() + os.sep + out) 138 | if platform == 'darwin': # MacOS 139 | os.system('open ' + save_path) 140 | 141 | print('Done. (%.3fs)' % (time.time() - t0)) 142 | 143 | 144 | if __name__ == '__main__': 145 | parser = argparse.ArgumentParser() 146 | parser.add_argument('--weights', type=str, default='weights/yolov5s.pt', help='model.pt path') 147 | parser.add_argument('--source', type=str, default='inference/images', help='source') # file/folder, 0 for webcam 148 | parser.add_argument('--output', type=str, default='inference/output', help='output folder') # output folder 149 | parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)') 150 | parser.add_argument('--conf-thres', type=float, default=0.4, help='object confidence threshold') 151 | parser.add_argument('--iou-thres', type=float, default=0.5, help='IOU threshold for NMS') 152 | parser.add_argument('--fourcc', type=str, default='mp4v', help='output video codec (verify ffmpeg support)') 153 | parser.add_argument('--half', action='store_true', help='half precision FP16 inference') 154 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') 155 | parser.add_argument('--view-img', action='store_true', help='display results') 156 | parser.add_argument('--save-txt', action='store_true', help='save results to *.txt') 157 | parser.add_argument('--classes', nargs='+', type=int, help='filter by class') 158 | parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS') 159 | parser.add_argument('--augment', action='store_true', help='augmented inference') 160 | opt = parser.parse_args() 161 | print(opt) 162 | 163 | with torch.no_grad(): 164 | detect() 165 | -------------------------------------------------------------------------------- /gen_wts.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import struct 3 | from utils.torch_utils import select_device 4 | 5 | # Initialize 6 | device = select_device('cpu') 7 | # Load model 8 | model = torch.load('weights/yolov5s.pt', map_location=device)['model'].float() # load to FP32 9 | model.to(device).eval() 10 | 11 | f = open('yolov5s.wtx', 'w') 12 | f.write('{}\n'.format(len(model.state_dict().keys()))) 13 | for k, v in model.state_dict().items(): 14 | vr = v.reshape(-1).cpu().numpy() 15 | f.write('{} {} '.format(k, len(vr))) 16 | for vv in vr: 17 | f.write(' ') 18 | f.write(struct.pack('>f',float(vv)).hex()) 19 | f.write('\n') 20 | -------------------------------------------------------------------------------- /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 | import torch 10 | 11 | from models.yolo import Model 12 | from utils import google_utils 13 | 14 | 15 | def create(name, pretrained, channels, classes): 16 | """Creates a specified YOLOv5 model 17 | 18 | Arguments: 19 | name (str): name of model, i.e. 'yolov5s' 20 | pretrained (bool): load pretrained weights into the model 21 | channels (int): number of input channels 22 | classes (int): number of model classes 23 | 24 | Returns: 25 | pytorch model 26 | """ 27 | model = Model('models/%s.yaml' % name, channels, classes) 28 | if pretrained: 29 | ckpt = '%s.pt' % name # checkpoint filename 30 | google_utils.attempt_download(ckpt) # download if not found locally 31 | state_dict = torch.load(ckpt)['model'].state_dict() 32 | state_dict = {k: v for k, v in state_dict.items() if model.state_dict()[k].numel() == v.numel()} # filter 33 | model.load_state_dict(state_dict, strict=False) # load 34 | return model 35 | 36 | 37 | def yolov5s(pretrained=False, channels=3, classes=80): 38 | """YOLOv5-small model from https://github.com/ultralytics/yolov5 39 | 40 | Arguments: 41 | pretrained (bool): load pretrained weights into the model, default=False 42 | channels (int): number of input channels, default=3 43 | classes (int): number of model classes, default=80 44 | 45 | Returns: 46 | pytorch model 47 | """ 48 | return create('yolov5s', pretrained, channels, classes) 49 | 50 | 51 | def yolov5m(pretrained=False, channels=3, classes=80): 52 | """YOLOv5-medium model from https://github.com/ultralytics/yolov5 53 | 54 | Arguments: 55 | pretrained (bool): load pretrained weights into the model, default=False 56 | channels (int): number of input channels, default=3 57 | classes (int): number of model classes, default=80 58 | 59 | Returns: 60 | pytorch model 61 | """ 62 | return create('yolov5m', pretrained, channels, classes) 63 | 64 | 65 | def yolov5l(pretrained=False, channels=3, classes=80): 66 | """YOLOv5-large model from https://github.com/ultralytics/yolov5 67 | 68 | Arguments: 69 | pretrained (bool): load pretrained weights into the model, default=False 70 | channels (int): number of input channels, default=3 71 | classes (int): number of model classes, default=80 72 | 73 | Returns: 74 | pytorch model 75 | """ 76 | return create('yolov5l', pretrained, channels, classes) 77 | 78 | 79 | def yolov5x(pretrained=False, channels=3, classes=80): 80 | """YOLOv5-xlarge model from https://github.com/ultralytics/yolov5 81 | 82 | Arguments: 83 | pretrained (bool): load pretrained weights into the model, default=False 84 | channels (int): number of input channels, default=3 85 | classes (int): number of model classes, default=80 86 | 87 | Returns: 88 | pytorch model 89 | """ 90 | return create('yolov5x', pretrained, channels, classes) 91 | -------------------------------------------------------------------------------- /inference/images/bus.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DataXujing/YOLO-v5/ead1c141106f114d92dddafb6ac8c57d7e96afb4/inference/images/bus.jpg -------------------------------------------------------------------------------- /inference/images/zidane.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DataXujing/YOLO-v5/ead1c141106f114d92dddafb6ac8c57d7e96afb4/inference/images/zidane.jpg -------------------------------------------------------------------------------- /inference/output/bus.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DataXujing/YOLO-v5/ead1c141106f114d92dddafb6ac8c57d7e96afb4/inference/output/bus.jpg -------------------------------------------------------------------------------- /inference/output/zidane.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DataXujing/YOLO-v5/ead1c141106f114d92dddafb6ac8c57d7e96afb4/inference/output/zidane.jpg -------------------------------------------------------------------------------- /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 | import torch 5 | $ export PYTHONPATH="$PWD" && python models/onnx_export.py --weights ./weights/yolov5s.pt --img 640 --batch 1 6 | """ 7 | 8 | import argparse 9 | 10 | import onnx 11 | 12 | from models.common import * 13 | 14 | if __name__ == '__main__': 15 | parser = argparse.ArgumentParser() 16 | parser.add_argument('--weights', type=str, default='./yolov5s.pt', help='weights path') 17 | parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image size') 18 | parser.add_argument('--batch-size', type=int, default=1, help='batch size') 19 | opt = parser.parse_args() 20 | print(opt) 21 | 22 | # Parameters 23 | f = opt.weights.replace('.pt', '.onnx') # onnx filename 24 | img = torch.zeros((opt.batch_size, 3, *opt.img_size)) # image size, (1, 3, 320, 192) iDetection 25 | 26 | # Load pytorch model 27 | google_utils.attempt_download(opt.weights) 28 | model = torch.load(opt.weights)['model'] 29 | model.eval() 30 | model.fuse() 31 | 32 | # Export to onnx 33 | model.model[-1].export = True # set Detect() layer export=True 34 | _ = model(img) # dry run 35 | torch.onnx.export(model, img, f, verbose=False, opset_version=11, input_names=['images'], 36 | output_names=['output']) # output_names=['classes', 'boxes'] 37 | 38 | # Check onnx model 39 | model = onnx.load(f) # load onnx model 40 | onnx.checker.check_model(model) # check onnx model 41 | print(onnx.helper.printable_graph(model.graph)) # print a human readable representation of the graph 42 | print('Export complete. ONNX model saved to %s\nView with https://github.com/lutzroeder/netron' % f) 43 | -------------------------------------------------------------------------------- /models/score/yolov5x.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 3 # number of classes 3 | depth_multiple: 1.33 # model depth multiple 4 | width_multiple: 1.25 # layer channel multiple 5 | 6 | # anchors 7 | anchors: 8 | - [10,13, 16,30, 33,23] # P3/8 9 | - [30,61, 62,45, 59,119] # P4/16 10 | - [116,90, 156,198, 373,326] # P5/32 11 | 12 | # yolov5 backbone 13 | backbone: 14 | # [from, number, module, args] 15 | [[-1, 1, Focus, [64, 3]], # 1-P1/2 16 | [-1, 1, Conv, [128, 3, 2]], # 2-P2/4 17 | [-1, 3, Bottleneck, [128]], 18 | [-1, 1, Conv, [256, 3, 2]], # 4-P3/8 19 | [-1, 9, BottleneckCSP, [256]], 20 | [-1, 1, Conv, [512, 3, 2]], # 6-P4/16 21 | [-1, 9, BottleneckCSP, [512]], 22 | [-1, 1, Conv, [1024, 3, 2]], # 8-P5/32 23 | [-1, 1, SPP, [1024, [5, 9, 13]]], 24 | [-1, 6, BottleneckCSP, [1024]], # 10 25 | ] 26 | 27 | # yolov5 head 28 | head: 29 | [[-1, 3, BottleneckCSP, [1024, False]], # 11 30 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 12 (P5/32-large) 31 | 32 | [-2, 1, nn.Upsample, [None, 2, 'nearest']], 33 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 34 | [-1, 1, Conv, [512, 1, 1]], 35 | [-1, 3, BottleneckCSP, [512, False]], 36 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 17 (P4/16-medium) 37 | 38 | [-2, 1, nn.Upsample, [None, 2, 'nearest']], 39 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 40 | [-1, 1, Conv, [256, 1, 1]], 41 | [-1, 3, BottleneckCSP, [256, False]], 42 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 22 (P3/8-small) 43 | 44 | [[], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 45 | ] 46 | -------------------------------------------------------------------------------- /models/yolo.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | import yaml 4 | 5 | from models.experimental import * 6 | 7 | 8 | class Detect(nn.Module): 9 | def __init__(self, nc=80, anchors=()): # detection layer 10 | super(Detect, self).__init__() 11 | self.stride = None # strides computed during build 12 | self.nc = nc # number of classes 13 | self.no = nc + 5 # number of outputs per anchor 14 | self.nl = len(anchors) # number of detection layers 15 | self.na = len(anchors[0]) // 2 # number of anchors 16 | self.grid = [torch.zeros(1)] * self.nl # init grid 17 | a = torch.tensor(anchors).float().view(self.nl, -1, 2) 18 | self.register_buffer('anchors', a) # shape(nl,na,2) 19 | self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2) 20 | self.export = False # onnx export 21 | 22 | def forward(self, x): 23 | # x = x.copy() # for profiling 24 | z = [] # inference output 25 | self.training |= self.export 26 | for i in range(self.nl): 27 | bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85) 28 | x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous() 29 | 30 | if not self.training: # inference 31 | if self.grid[i].shape[2:4] != x[i].shape[2:4]: 32 | self.grid[i] = self._make_grid(nx, ny).to(x[i].device) 33 | 34 | y = x[i].sigmoid() 35 | y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i].to(x[i].device)) * self.stride[i] # xy 36 | y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh 37 | z.append(y.view(bs, -1, self.no)) 38 | 39 | return x if self.training else (torch.cat(z, 1), x) 40 | 41 | @staticmethod 42 | def _make_grid(nx=20, ny=20): 43 | yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)]) 44 | return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float() 45 | 46 | 47 | class Model(nn.Module): 48 | def __init__(self, model_cfg='yolov5s.yaml', ch=3, nc=None): # model, input channels, number of classes 49 | super(Model, self).__init__() 50 | if type(model_cfg) is dict: 51 | self.md = model_cfg # model dict 52 | else: # is *.yaml 53 | with open(model_cfg) as f: 54 | self.md = yaml.load(f, Loader=yaml.FullLoader) # model dict 55 | 56 | # Define model 57 | if nc: 58 | self.md['nc'] = nc # override yaml value 59 | self.model, self.save = parse_model(self.md, ch=[ch]) # model, savelist, ch_out 60 | # print([x.shape for x in self.forward(torch.zeros(1, ch, 64, 64))]) 61 | 62 | # Build strides, anchors 63 | m = self.model[-1] # Detect() 64 | m.stride = torch.tensor([64 / x.shape[-2] for x in self.forward(torch.zeros(1, ch, 64, 64))]) # forward 65 | m.anchors /= m.stride.view(-1, 1, 1) 66 | self.stride = m.stride 67 | 68 | # Init weights, biases 69 | torch_utils.initialize_weights(self) 70 | self._initialize_biases() # only run once 71 | torch_utils.model_info(self) 72 | print('') 73 | 74 | def forward(self, x, augment=False, profile=False): 75 | if augment: 76 | img_size = x.shape[-2:] # height, width 77 | s = [0.83, 0.67] # scales 78 | y = [] 79 | for i, xi in enumerate((x, 80 | torch_utils.scale_img(x.flip(3), s[0]), # flip-lr and scale 81 | torch_utils.scale_img(x, s[1]), # scale 82 | )): 83 | # cv2.imwrite('img%g.jpg' % i, 255 * xi[0].numpy().transpose((1, 2, 0))[:, :, ::-1]) 84 | y.append(self.forward_once(xi)[0]) 85 | 86 | y[1][..., :4] /= s[0] # scale 87 | y[1][..., 0] = img_size[1] - y[1][..., 0] # flip lr 88 | y[2][..., :4] /= s[1] # scale 89 | return torch.cat(y, 1), None # augmented inference, train 90 | else: 91 | return self.forward_once(x, profile) # single-scale inference, train 92 | 93 | def forward_once(self, x, profile=False): 94 | y, dt = [], [] # outputs 95 | for m in self.model: 96 | if m.f != -1: # if not from previous layer 97 | 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 98 | 99 | if profile: 100 | import thop 101 | o = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # FLOPS 102 | t = torch_utils.time_synchronized() 103 | for _ in range(10): 104 | _ = m(x) 105 | dt.append((torch_utils.time_synchronized() - t) * 100) 106 | print('%10.1f%10.0f%10.1fms %-40s' % (o, m.np, dt[-1], m.type)) 107 | 108 | x = m(x) # run 109 | y.append(x if m.i in self.save else None) # save output 110 | 111 | if profile: 112 | print('%.1fms total' % sum(dt)) 113 | return x 114 | 115 | def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency 116 | # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1. 117 | m = self.model[-1] # Detect() module 118 | for f, s in zip(m.f, m.stride): #  from 119 | mi = self.model[f % m.i] 120 | b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85) 121 | b[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image) 122 | b[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls 123 | mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True) 124 | 125 | def _print_biases(self): 126 | m = self.model[-1] # Detect() module 127 | for f in sorted([x % m.i for x in m.f]): #  from 128 | b = self.model[f].bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85) 129 | print(('%g Conv2d.bias:' + '%10.3g' * 6) % (f, *b[:5].mean(1).tolist(), b[5:].mean())) 130 | 131 | # def _print_weights(self): 132 | # for m in self.model.modules(): 133 | # if type(m) is Bottleneck: 134 | # print('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights 135 | 136 | def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers 137 | print('Fusing layers...') 138 | for m in self.model.modules(): 139 | if type(m) is Conv: 140 | m.conv = torch_utils.fuse_conv_and_bn(m.conv, m.bn) # update conv 141 | m.bn = None # remove batchnorm 142 | m.forward = m.fuseforward # update forward 143 | torch_utils.model_info(self) 144 | 145 | 146 | def parse_model(md, ch): # model_dict, input_channels(3) 147 | print('\n%3s%15s%3s%10s %-40s%-30s' % ('', 'from', 'n', 'params', 'module', 'arguments')) 148 | anchors, nc, gd, gw = md['anchors'], md['nc'], md['depth_multiple'], md['width_multiple'] 149 | na = (len(anchors[0]) // 2) # number of anchors 150 | no = na * (nc + 5) # number of outputs = anchors * (classes + 5) 151 | 152 | layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out 153 | for i, (f, n, m, args) in enumerate(md['backbone'] + md['head']): # from, number, module, args 154 | m = eval(m) if isinstance(m, str) else m # eval strings 155 | for j, a in enumerate(args): 156 | try: 157 | args[j] = eval(a) if isinstance(a, str) else a # eval strings 158 | except: 159 | pass 160 | 161 | n = max(round(n * gd), 1) if n > 1 else n # depth gain 162 | if m in [nn.Conv2d, Conv, Bottleneck, SPP, DWConv, MixConv2d, Focus, ConvPlus, BottleneckCSP]: 163 | c1, c2 = ch[f], args[0] 164 | 165 | # Normal 166 | # if i > 0 and args[0] != no: # channel expansion factor 167 | # ex = 1.75 # exponential (default 2.0) 168 | # e = math.log(c2 / ch[1]) / math.log(2) 169 | # c2 = int(ch[1] * ex ** e) 170 | # if m != Focus: 171 | c2 = make_divisible(c2 * gw, 8) if c2 != no else c2 172 | 173 | # Experimental 174 | # if i > 0 and args[0] != no: # channel expansion factor 175 | # ex = 1 + gw # exponential (default 2.0) 176 | # ch1 = 32 # ch[1] 177 | # e = math.log(c2 / ch1) / math.log(2) # level 1-n 178 | # c2 = int(ch1 * ex ** e) 179 | # if m != Focus: 180 | # c2 = make_divisible(c2, 8) if c2 != no else c2 181 | 182 | args = [c1, c2, *args[1:]] 183 | if m is BottleneckCSP: 184 | args.insert(2, n) 185 | n = 1 186 | elif m is nn.BatchNorm2d: 187 | args = [ch[f]] 188 | elif m is Concat: 189 | c2 = sum([ch[-1 if x == -1 else x + 1] for x in f]) 190 | elif m is Detect: 191 | f = f or list(reversed([(-1 if j == i else j - 1) for j, x in enumerate(ch) if x == no])) 192 | else: 193 | c2 = ch[f] 194 | 195 | m_ = nn.Sequential(*[m(*args) for _ in range(n)]) if n > 1 else m(*args) # module 196 | t = str(m)[8:-2].replace('__main__.', '') # module type 197 | np = sum([x.numel() for x in m_.parameters()]) # number params 198 | m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params 199 | print('%3s%15s%3s%10.0f %-40s%-30s' % (i, f, n, np, t, args)) # print 200 | save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist 201 | layers.append(m_) 202 | ch.append(c2) 203 | return nn.Sequential(*layers), sorted(save) 204 | 205 | 206 | if __name__ == '__main__': 207 | parser = argparse.ArgumentParser() 208 | parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml') 209 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') 210 | opt = parser.parse_args() 211 | opt.cfg = glob.glob('./**/' + opt.cfg, recursive=True)[0] # find file 212 | device = torch_utils.select_device(opt.device) 213 | 214 | # Create model 215 | model = Model(opt.cfg).to(device) 216 | model.train() 217 | 218 | # Profile 219 | # img = torch.rand(8 if torch.cuda.is_available() else 1, 3, 640, 640).to(device) 220 | # y = model(img, profile=True) 221 | # print([y[0].shape] + [x.shape for x in y[1]]) 222 | 223 | # ONNX export 224 | # model.model[-1].export = True 225 | # torch.onnx.export(model, img, f.replace('.yaml', '.onnx'), verbose=True, opset_version=11) 226 | 227 | # Tensorboard 228 | # from torch.utils.tensorboard import SummaryWriter 229 | # tb_writer = SummaryWriter() 230 | # print("Run 'tensorboard --logdir=models/runs' to view tensorboard at http://localhost:6006/") 231 | # tb_writer.add_graph(model.model, img) # add model to tensorboard 232 | # tb_writer.add_image('test', img[0], dataformats='CWH') # add model to tensorboard 233 | -------------------------------------------------------------------------------- /models/yolov3-spp.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 80 # number of classes 3 | depth_multiple: 1.0 # expand model depth 4 | width_multiple: 1.0 # expand layer channels 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 | # na = len(anchors[0]) 30 | head: 31 | [[-1, 1, Bottleneck, [1024, False]], # 11 32 | [-1, 1, SPP, [512, [5, 9, 13]]], 33 | [-1, 1, Conv, [1024, 3, 1]], 34 | [-1, 1, Conv, [512, 1, 1]], 35 | [-1, 1, Conv, [1024, 3, 1]], 36 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 16 (P5/32-large) 37 | 38 | [-3, 1, Conv, [256, 1, 1]], 39 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 40 | [[-1, 8], 1, Concat, [1]], # cat backbone P4 41 | [-1, 1, Bottleneck, [512, False]], 42 | [-1, 1, Bottleneck, [512, False]], 43 | [-1, 1, Conv, [256, 1, 1]], 44 | [-1, 1, Conv, [512, 3, 1]], 45 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 24 (P4/16-medium) 46 | 47 | [-3, 1, Conv, [128, 1, 1]], 48 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 49 | [[-1, 6], 1, Concat, [1]], # cat backbone P3 50 | [-1, 1, Bottleneck, [256, False]], 51 | [-1, 2, Bottleneck, [256, False]], 52 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 30 (P3/8-small) 53 | 54 | [[], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 55 | ] 56 | -------------------------------------------------------------------------------- /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 | - [10,13, 16,30, 33,23] # P3/8 9 | - [30,61, 62,45, 59,119] # P4/16 10 | - [116,90, 156,198, 373,326] # P5/32 11 | 12 | # yolov5 backbone 13 | backbone: 14 | # [from, number, module, args] 15 | [[-1, 1, Focus, [64, 3]], # 1-P1/2 16 | [-1, 1, Conv, [128, 3, 2]], # 2-P2/4 17 | [-1, 3, Bottleneck, [128]], 18 | [-1, 1, Conv, [256, 3, 2]], # 4-P3/8 19 | [-1, 9, BottleneckCSP, [256]], 20 | [-1, 1, Conv, [512, 3, 2]], # 6-P4/16 21 | [-1, 9, BottleneckCSP, [512]], 22 | [-1, 1, Conv, [1024, 3, 2]], # 8-P5/32 23 | [-1, 1, SPP, [1024, [5, 9, 13]]], 24 | [-1, 6, BottleneckCSP, [1024]], # 10 25 | ] 26 | 27 | # yolov5 head 28 | head: 29 | [[-1, 3, BottleneckCSP, [1024, False]], # 11 30 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 12 (P5/32-large) 31 | 32 | [-2, 1, nn.Upsample, [None, 2, 'nearest']], 33 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 34 | [-1, 1, Conv, [512, 1, 1]], 35 | [-1, 3, BottleneckCSP, [512, False]], 36 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 17 (P4/16-medium) 37 | 38 | [-2, 1, nn.Upsample, [None, 2, 'nearest']], 39 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 40 | [-1, 1, Conv, [256, 1, 1]], 41 | [-1, 3, BottleneckCSP, [256, False]], 42 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 22 (P3/8-small) 43 | 44 | [[], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 45 | ] 46 | -------------------------------------------------------------------------------- /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 | - [10,13, 16,30, 33,23] # P3/8 9 | - [30,61, 62,45, 59,119] # P4/16 10 | - [116,90, 156,198, 373,326] # P5/32 11 | 12 | # yolov5 backbone 13 | backbone: 14 | # [from, number, module, args] 15 | [[-1, 1, Focus, [64, 3]], # 1-P1/2 16 | [-1, 1, Conv, [128, 3, 2]], # 2-P2/4 17 | [-1, 3, Bottleneck, [128]], 18 | [-1, 1, Conv, [256, 3, 2]], # 4-P3/8 19 | [-1, 9, BottleneckCSP, [256]], 20 | [-1, 1, Conv, [512, 3, 2]], # 6-P4/16 21 | [-1, 9, BottleneckCSP, [512]], 22 | [-1, 1, Conv, [1024, 3, 2]], # 8-P5/32 23 | [-1, 1, SPP, [1024, [5, 9, 13]]], 24 | [-1, 6, BottleneckCSP, [1024]], # 10 25 | ] 26 | 27 | # yolov5 head 28 | head: 29 | [[-1, 3, BottleneckCSP, [1024, False]], # 11 30 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 12 (P5/32-large) 31 | 32 | [-2, 1, nn.Upsample, [None, 2, 'nearest']], 33 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 34 | [-1, 1, Conv, [512, 1, 1]], 35 | [-1, 3, BottleneckCSP, [512, False]], 36 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 17 (P4/16-medium) 37 | 38 | [-2, 1, nn.Upsample, [None, 2, 'nearest']], 39 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 40 | [-1, 1, Conv, [256, 1, 1]], 41 | [-1, 3, BottleneckCSP, [256, False]], 42 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 22 (P3/8-small) 43 | 44 | [[], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 45 | ] 46 | -------------------------------------------------------------------------------- /models/yolov5s.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 80 # number of classes 3 | depth_multiple: 0.33 # model depth multiple 4 | width_multiple: 0.50 # layer channel multiple 5 | 6 | # anchors 7 | anchors: 8 | - [10,13, 16,30, 33,23] # P3/8 9 | - [30,61, 62,45, 59,119] # P4/16 10 | - [116,90, 156,198, 373,326] # P5/32 11 | 12 | # yolov5 backbone 13 | backbone: 14 | # [from, number, module, args] 15 | [[-1, 1, Focus, [64, 3]], # 1-P1/2 16 | [-1, 1, Conv, [128, 3, 2]], # 2-P2/4 17 | [-1, 3, Bottleneck, [128]], 18 | [-1, 1, Conv, [256, 3, 2]], # 4-P3/8 19 | [-1, 9, BottleneckCSP, [256]], 20 | [-1, 1, Conv, [512, 3, 2]], # 6-P4/16 21 | [-1, 9, BottleneckCSP, [512]], 22 | [-1, 1, Conv, [1024, 3, 2]], # 8-P5/32 23 | [-1, 1, SPP, [1024, [5, 9, 13]]], 24 | [-1, 6, BottleneckCSP, [1024]], # 10 25 | ] 26 | 27 | # yolov5 head 28 | head: 29 | [[-1, 3, BottleneckCSP, [1024, False]], # 11 30 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 12 (P5/32-large) 31 | 32 | [-2, 1, nn.Upsample, [None, 2, 'nearest']], 33 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 34 | [-1, 1, Conv, [512, 1, 1]], 35 | [-1, 3, BottleneckCSP, [512, False]], 36 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 17 (P4/16-medium) 37 | 38 | [-2, 1, nn.Upsample, [None, 2, 'nearest']], 39 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 40 | [-1, 1, Conv, [256, 1, 1]], 41 | [-1, 3, BottleneckCSP, [256, False]], 42 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 22 (P3/8-small) 43 | 44 | [[], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 45 | ] 46 | -------------------------------------------------------------------------------- /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 | - [10,13, 16,30, 33,23] # P3/8 9 | - [30,61, 62,45, 59,119] # P4/16 10 | - [116,90, 156,198, 373,326] # P5/32 11 | 12 | # yolov5 backbone 13 | backbone: 14 | # [from, number, module, args] 15 | [[-1, 1, Focus, [64, 3]], # 1-P1/2 16 | [-1, 1, Conv, [128, 3, 2]], # 2-P2/4 17 | [-1, 3, Bottleneck, [128]], 18 | [-1, 1, Conv, [256, 3, 2]], # 4-P3/8 19 | [-1, 9, BottleneckCSP, [256]], 20 | [-1, 1, Conv, [512, 3, 2]], # 6-P4/16 21 | [-1, 9, BottleneckCSP, [512]], 22 | [-1, 1, Conv, [1024, 3, 2]], # 8-P5/32 23 | [-1, 1, SPP, [1024, [5, 9, 13]]], 24 | [-1, 6, BottleneckCSP, [1024]], # 10 25 | ] 26 | 27 | # yolov5 head 28 | head: 29 | [[-1, 3, BottleneckCSP, [1024, False]], # 11 30 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 12 (P5/32-large) 31 | 32 | [-2, 1, nn.Upsample, [None, 2, 'nearest']], 33 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 34 | [-1, 1, Conv, [512, 1, 1]], 35 | [-1, 3, BottleneckCSP, [512, False]], 36 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 17 (P4/16-medium) 37 | 38 | [-2, 1, nn.Upsample, [None, 2, 'nearest']], 39 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 40 | [-1, 1, Conv, [256, 1, 1]], 41 | [-1, 3, BottleneckCSP, [256, False]], 42 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 22 (P3/8-small) 43 | 44 | [[], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 45 | ] 46 | -------------------------------------------------------------------------------- /readmepic/readme1/82944393-f7644d80-9f4f-11ea-8b87-1a5b04f555f1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DataXujing/YOLO-v5/ead1c141106f114d92dddafb6ac8c57d7e96afb4/readmepic/readme1/82944393-f7644d80-9f4f-11ea-8b87-1a5b04f555f1.jpg -------------------------------------------------------------------------------- /readmepic/readme1/83082816-59e54880-a039-11ea-8abe-ab90cc1ec4b0.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DataXujing/YOLO-v5/ead1c141106f114d92dddafb6ac8c57d7e96afb4/readmepic/readme1/83082816-59e54880-a039-11ea-8abe-ab90cc1ec4b0.jpeg -------------------------------------------------------------------------------- /readmepic/readme1/84186698-c4d54d00-aa45-11ea-9bde-c632c1230ccd.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DataXujing/YOLO-v5/ead1c141106f114d92dddafb6ac8c57d7e96afb4/readmepic/readme1/84186698-c4d54d00-aa45-11ea-9bde-c632c1230ccd.png -------------------------------------------------------------------------------- /readmepic/readme1/84200349-729f2680-aa5b-11ea-8f9a-604c9e01a658.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DataXujing/YOLO-v5/ead1c141106f114d92dddafb6ac8c57d7e96afb4/readmepic/readme1/84200349-729f2680-aa5b-11ea-8f9a-604c9e01a658.png -------------------------------------------------------------------------------- /readmepic/readme1/YOLOv4_author2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DataXujing/YOLO-v5/ead1c141106f114d92dddafb6ac8c57d7e96afb4/readmepic/readme1/YOLOv4_author2.jpg -------------------------------------------------------------------------------- /readmepic/readme2/pic/20200514_p6_5_247_one.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DataXujing/YOLO-v5/ead1c141106f114d92dddafb6ac8c57d7e96afb4/readmepic/readme2/pic/20200514_p6_5_247_one.jpg -------------------------------------------------------------------------------- /readmepic/readme2/pic/78174482-307bb800-740e-11ea-8b09-840693671042.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DataXujing/YOLO-v5/ead1c141106f114d92dddafb6ac8c57d7e96afb4/readmepic/readme2/pic/78174482-307bb800-740e-11ea-8b09-840693671042.png -------------------------------------------------------------------------------- /readmepic/readme2/pic/83666389-bab4d980-a581-11ea-898b-b25471d37b83.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DataXujing/YOLO-v5/ead1c141106f114d92dddafb6ac8c57d7e96afb4/readmepic/readme2/pic/83666389-bab4d980-a581-11ea-898b-b25471d37b83.jpg -------------------------------------------------------------------------------- /readmepic/readme2/pic/83667626-8c37fe00-a583-11ea-997b-0923fe59b29b.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DataXujing/YOLO-v5/ead1c141106f114d92dddafb6ac8c57d7e96afb4/readmepic/readme2/pic/83667626-8c37fe00-a583-11ea-997b-0923fe59b29b.jpeg -------------------------------------------------------------------------------- /readmepic/readme2/pic/83667635-90641b80-a583-11ea-8075-606316cebb9c.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DataXujing/YOLO-v5/ead1c141106f114d92dddafb6ac8c57d7e96afb4/readmepic/readme2/pic/83667635-90641b80-a583-11ea-8075-606316cebb9c.jpeg -------------------------------------------------------------------------------- /readmepic/readme2/pic/83667642-90fcb200-a583-11ea-8fa3-338bbf7da194.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DataXujing/YOLO-v5/ead1c141106f114d92dddafb6ac8c57d7e96afb4/readmepic/readme2/pic/83667642-90fcb200-a583-11ea-8fa3-338bbf7da194.jpeg -------------------------------------------------------------------------------- /readmepic/readme2/pic/83667810-d7eaa780-a583-11ea-8de8-5cca0673d076.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DataXujing/YOLO-v5/ead1c141106f114d92dddafb6ac8c57d7e96afb4/readmepic/readme2/pic/83667810-d7eaa780-a583-11ea-8de8-5cca0673d076.png -------------------------------------------------------------------------------- /readmepic/readme2/pic/datalist.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DataXujing/YOLO-v5/ead1c141106f114d92dddafb6ac8c57d7e96afb4/readmepic/readme2/pic/datalist.png -------------------------------------------------------------------------------- /readmepic/readme2/pic/results.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DataXujing/YOLO-v5/ead1c141106f114d92dddafb6ac8c57d7e96afb4/readmepic/readme2/pic/results.png -------------------------------------------------------------------------------- /readmepic/readme2/pic/t1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DataXujing/YOLO-v5/ead1c141106f114d92dddafb6ac8c57d7e96afb4/readmepic/readme2/pic/t1.jpg -------------------------------------------------------------------------------- /readmepic/readme2/pic/test_batch0_gt.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DataXujing/YOLO-v5/ead1c141106f114d92dddafb6ac8c57d7e96afb4/readmepic/readme2/pic/test_batch0_gt.jpg -------------------------------------------------------------------------------- /readmepic/readme2/pic/test_batch0_pred.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DataXujing/YOLO-v5/ead1c141106f114d92dddafb6ac8c57d7e96afb4/readmepic/readme2/pic/test_batch0_pred.jpg -------------------------------------------------------------------------------- /readmepic/readme2/pic/train_batch0.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DataXujing/YOLO-v5/ead1c141106f114d92dddafb6ac8c57d7e96afb4/readmepic/readme2/pic/train_batch0.jpg -------------------------------------------------------------------------------- /readmepic/readme2/pic/train_batch1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DataXujing/YOLO-v5/ead1c141106f114d92dddafb6ac8c57d7e96afb4/readmepic/readme2/pic/train_batch1.jpg -------------------------------------------------------------------------------- /readmepic/readme2/pic/train_batch2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DataXujing/YOLO-v5/ead1c141106f114d92dddafb6ac8c57d7e96afb4/readmepic/readme2/pic/train_batch2.jpg -------------------------------------------------------------------------------- /readmepic/readme2/教程.md: -------------------------------------------------------------------------------- 1 | This guide explains how to train your own **custom dataset** with YOLOv5. 2 | 3 | ## Before You Start 4 | 5 | Clone this repo, download tutorial dataset, and install [requirements.txt](https://github.com/ultralytics/yolov5/blob/master/requirements.txt) dependencies, including **Python>=3.7** and **PyTorch>=1.5**. 6 | 7 | ```bash 8 | git clone https://github.com/ultralytics/yolov5 # clone repo 9 | python3 -c "from yolov5.utils.google_utils import gdrive_download; gdrive_download('1n_oKgR81BJtqk75b00eAjdv03qVCQn2f','coco128.zip')" # download dataset 10 | cd yolov5 11 | pip install -U -r requirements.txt 12 | ``` 13 | 14 | ## Train On Custom Data 15 | 16 | ### 1. Create Dataset.yaml 17 | 18 | [data/coco128.yaml](https://github.com/ultralytics/yolov5/blob/master/data/coco128.yaml) is a small tutorial dataset composed of the first 128 images in [COCO](http://cocodataset.org/#home) train2017. These same 128 images are used for both training and validation in this example. `coco128.yaml` defines 1) a path to a directory of training images (or path to a *.txt file with a list of training images), 2) the same for our validation images, 3) the number of classes, 4) a list of class names: 19 | ```yaml 20 | # train and val datasets (image directory or *.txt file with image paths) 21 | train: ../coco128/images/train2017/ 22 | val: ../coco128/images/train2017/ 23 | 24 | # number of classes 25 | nc: 80 26 | 27 | # class names 28 | names: ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 29 | 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 30 | 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 31 | 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 32 | 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 33 | 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 34 | 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 35 | 'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 36 | 'teddy bear', 'hair drier', 'toothbrush'] 37 | ``` 38 | 39 | 40 | ### 2. Create Labels 41 | 42 | After using a tool like [Labelbox](https://labelbox.com/) or [CVAT](https://github.com/opencv/cvat) to label your images, export your labels to **darknet format**, with one `*.txt` file per image (if no objects in image, no `*.txt` file is required). The `*.txt` file specifications are: 43 | 44 | - One row per object 45 | - Each row is `class x_center y_center width height` format. 46 | - Box coordinates must be in **normalized xywh** format (from 0 - 1). If your boxes are in pixels, divide `x_center` and `width` by image width, and `y_center` and `height` by image height. 47 | - Class numbers are zero-indexed (start from 0). 48 | 49 | Each image's label file should be locatable by simply replacing `/images/*.jpg` with `/labels/*.txt` in its pathname. An example image and label pair would be: 50 | ```bash 51 | dataset/images/train2017/000000109622.jpg # image 52 | dataset/labels/train2017/000000109622.txt # label 53 | ``` 54 | An example label file with 5 persons (all class `0`): 55 | Screen Shot 2020-04-01 at 11 44 26 AM 56 | 57 | 58 | ### 3. Organize Directories 59 | 60 | Organize your train and val images and labels according to the example below. Note `/coco128` should be **next to** the `/yolov5` directory. Make sure `coco128/labels` folder is next to `coco128/images` folder. 61 | 62 | Screen Shot 2020-04-01 at 11 44 26 AM 63 | 64 | ### 4. Select a Model 65 | 66 | Select a model from the `./models` folder. Here we select [yolov5s.yaml](https://github.com/ultralytics/yolov5/blob/master/models/yolov5s.yaml), the smallest and fastest model available. See our README [table](https://github.com/ultralytics/yolov5#pretrained-checkpoints) for a full comparison of all models. Once you have selected a model, if you are not training COCO, **update** the `nc: 80` parameter in your yaml file to match the number of classes in your dataset from step **1.** 67 | ```yaml 68 | # parameters 69 | nc: 80 # number of classes <------------------ UPDATE to match your dataset 70 | depth_multiple: 0.33 # model depth multiple 71 | width_multiple: 0.50 # layer channel multiple 72 | 73 | # anchors 74 | anchors: 75 | - [10,13, 16,30, 33,23] # P3/8 76 | - [30,61, 62,45, 59,119] # P4/16 77 | - [116,90, 156,198, 373,326] # P5/32 78 | 79 | # yolov5 backbone 80 | backbone: 81 | # [from, number, module, args] 82 | [[-1, 1, Focus, [64, 3]], # 1-P1/2 83 | [-1, 1, Conv, [128, 3, 2]], # 2-P2/4 84 | [-1, 3, Bottleneck, [128]], 85 | [-1, 1, Conv, [256, 3, 2]], # 4-P3/8 86 | [-1, 9, BottleneckCSP, [256, False]], 87 | [-1, 1, Conv, [512, 3, 2]], # 6-P4/16 88 | [-1, 9, BottleneckCSP, [512, False]], 89 | [-1, 1, Conv, [1024, 3, 2]], # 8-P5/32 90 | [-1, 1, SPP, [1024, [5, 9, 13]]], 91 | [-1, 12, BottleneckCSP, [1024, False]], # 10 92 | ] 93 | 94 | # yolov5 head 95 | head: 96 | [[-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 12 (P5/32-large) 97 | 98 | [-2, 1, nn.Upsample, [None, 2, 'nearest']], 99 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 100 | [-1, 1, Conv, [512, 1, 1]], 101 | [-1, 3, BottleneckCSP, [512, False]], 102 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 16 (P4/16-medium) 103 | 104 | [-2, 1, nn.Upsample, [None, 2, 'nearest']], 105 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 106 | [-1, 1, Conv, [256, 1, 1]], 107 | [-1, 3, BottleneckCSP, [256, False]], 108 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]], # 21 (P3/8-small) 109 | 110 | [[], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 111 | ] 112 | ``` 113 | 114 | ### 5. Train 115 | 116 | Run the training command below to train `coco128.yaml` for 5 epochs. You can train yolov5s from scratch by passing `--cfg yolov5s.yaml --weights ''`, or train from a pretrained checkpoint by passing a matching weights file: `--cfg yolov5s.yaml --weights yolov5s.pt`. 117 | ```bash 118 | # Train yolov5s on coco128 for 5 epochs 119 | $ python train.py --img 640 --batch 16 --epochs 5 --data ./data/coco128.yaml --cfg ./models/yolov5s.yaml --weights '' 120 | ``` 121 | 122 | For training command outputs and further details please see the training section of Google Colab Notebook. Open In Colab 123 | 124 | ### 6. Visualize 125 | 126 | After training starts, view `train*.jpg` images to see training images, labels and augmentation effects. Note a mosaic dataloader is used for training (shown below), a new dataloading concept developed by Ultralytics and first featured in [YOLOv4](https://arxiv.org/abs/2004.10934). If your labels are not correct in these images then you have incorrectly labelled your data, and should revisit **2. Create Labels**. 127 | ![download](./pic/83667642-90fcb200-a583-11ea-8fa3-338bbf7da194.jpeg) 128 | 129 | After the first epoch is complete, view `test_batch0_gt.jpg` to see test batch 0 ground truth labels: 130 | ![download (1)](./pic/83667626-8c37fe00-a583-11ea-997b-0923fe59b29b.jpeg) 131 | 132 | And view `test_batch0_pred.jpg` to see test batch 0 predictions: 133 | ![download (2)](./pic/83667635-90641b80-a583-11ea-8075-606316cebb9c.jpeg) 134 | 135 | Training losses and performance metrics are saved to Tensorboard and also to a `results.txt` logfile. `results.txt` is plotted as `results.png` after training completes. Partially completed `results.txt` files can be plotted with `from utils.utils import plot_results; plot_results()`. Here we show yolov5s trained on coco128 to 100 epochs, starting from scratch (orange), and starting from pretrained `yolov5s.pt` weights (blue): 136 | 137 | ![download](./pic/83667810-d7eaa780-a583-11ea-8de8-5cca0673d076.png) 138 | 139 | 140 | ## Reproduce Our Environment 141 | 142 | To access an up-to-date working environment (with all dependencies including CUDA/CUDNN, Python and PyTorch preinstalled), consider a: 143 | 144 | - **GCP** Deep Learning VM with $300 free credit offer. See our [GCP Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/GCP-Quickstart) 145 | - **Google Colab Notebook** with 12 hours of free GPU time. Open In Colab 146 | - **Docker Image** https://hub.docker.com/r/ultralytics/yolov5. See [Docker Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/Docker-Quickstart) -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # pip install -U -r requirements.txt 2 | numpy==1.17 3 | opencv-python 4 | torch >= 1.5 5 | matplotlib 6 | pycocotools 7 | tqdm 8 | pillow 9 | tensorboard 10 | pyyaml 11 | 12 | 13 | # Nvidia Apex (optional) for mixed precision training -------------------------- 14 | # 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 15 | 16 | # Conda commands (in place of pip) --------------------------------------------- 17 | # conda update -yn base -c defaults conda 18 | # conda install -yc anaconda numpy opencv matplotlib tqdm pillow ipython 19 | # conda install -yc conda-forge scikit-image pycocotools tensorboard 20 | # conda install -yc spyder-ide spyder-line-profiler 21 | # conda install -yc pytorch pytorch torchvision 22 | # conda install -yc conda-forge protobuf numpy && pip install onnx # https://github.com/onnx/onnx#linux-and-macos 23 | -------------------------------------------------------------------------------- /runs/readme: -------------------------------------------------------------------------------- 1 | 此处存放tensorboard日志文件 -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import json 3 | 4 | import yaml 5 | from torch.utils.data import DataLoader 6 | 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 | model=None, 21 | dataloader=None, 22 | fast=False, 23 | verbose=False): # 0 fast, 1 accurate 24 | # Initialize/load model and set device 25 | if model is None: 26 | device = torch_utils.select_device(opt.device, batch_size=batch_size) 27 | 28 | # Remove previous 29 | for f in glob.glob('test_batch*.jpg'): 30 | os.remove(f) 31 | 32 | # Load model 33 | google_utils.attempt_download(weights) 34 | model = torch.load(weights, map_location=device)['model'] 35 | torch_utils.model_info(model) 36 | # model.fuse() 37 | model.to(device) 38 | 39 | if device.type != 'cpu' and torch.cuda.device_count() > 1: 40 | model = nn.DataParallel(model) 41 | 42 | training = False 43 | else: # called by train.py 44 | device = next(model.parameters()).device # get model device 45 | training = True 46 | 47 | # Configure run 48 | with open(data) as f: 49 | data = yaml.load(f, Loader=yaml.FullLoader) # model dict 50 | nc = 1 if single_cls else int(data['nc']) # number of classes 51 | iouv = torch.linspace(0.5, 0.95, 10).to(device) # iou vector for mAP@0.5:0.95 52 | # iouv = iouv[0].view(1) # comment for mAP@0.5:0.95 53 | niou = iouv.numel() 54 | 55 | # Dataloader 56 | if dataloader is None: 57 | fast |= conf_thres > 0.001 # enable fast mode 58 | path = data['test'] if opt.task == 'test' else data['val'] # path to val/test images 59 | dataset = LoadImagesAndLabels(path, 60 | imgsz, 61 | batch_size, 62 | rect=True, # rectangular inference 63 | single_cls=opt.single_cls, # single class mode 64 | pad=0.0 if fast else 0.5) # padding 65 | batch_size = min(batch_size, len(dataset)) 66 | nw = min([os.cpu_count(), batch_size if batch_size > 1 else 0, 8]) # number of workers 67 | dataloader = DataLoader(dataset, 68 | batch_size=batch_size, 69 | num_workers=nw, 70 | pin_memory=True, 71 | collate_fn=dataset.collate_fn) 72 | 73 | seen = 0 74 | model.eval() 75 | _ = model(torch.zeros((1, 3, imgsz, imgsz), device=device)) if device.type != 'cpu' else None # run once 76 | names = model.names if hasattr(model, 'names') else model.module.names 77 | coco91class = coco80_to_coco91_class() 78 | s = ('%20s' + '%12s' * 6) % ('Class', 'Images', 'Targets', 'P', 'R', 'mAP@.5', 'mAP@.5:.95') 79 | p, r, f1, mp, mr, map50, map, t0, t1 = 0., 0., 0., 0., 0., 0., 0., 0., 0. 80 | loss = torch.zeros(3, device=device) 81 | jdict, stats, ap, ap_class = [], [], [], [] 82 | for batch_i, (imgs, targets, paths, shapes) in enumerate(tqdm(dataloader, desc=s)): 83 | imgs = imgs.to(device).float() / 255.0 # uint8 to float32, 0 - 255 to 0.0 - 1.0 84 | targets = targets.to(device) 85 | nb, _, height, width = imgs.shape # batch size, channels, height, width 86 | whwh = torch.Tensor([width, height, width, height]).to(device) 87 | 88 | # Disable gradients 89 | with torch.no_grad(): 90 | # Run model 91 | t = torch_utils.time_synchronized() 92 | inf_out, train_out = model(imgs, augment=augment) # inference and training outputs 93 | t0 += torch_utils.time_synchronized() - t 94 | 95 | # Compute loss 96 | if training: # if model has loss hyperparameters 97 | loss += compute_loss(train_out, targets, model)[1][:3] # GIoU, obj, cls 98 | 99 | # Run NMS 100 | t = torch_utils.time_synchronized() 101 | output = non_max_suppression(inf_out, conf_thres=conf_thres, iou_thres=iou_thres, fast=fast) 102 | t1 += torch_utils.time_synchronized() - t 103 | 104 | # Statistics per image 105 | for si, pred in enumerate(output): 106 | labels = targets[targets[:, 0] == si, 1:] 107 | nl = len(labels) 108 | tcls = labels[:, 0].tolist() if nl else [] # target class 109 | seen += 1 110 | 111 | if pred is None: 112 | if nl: 113 | stats.append((torch.zeros(0, niou, dtype=torch.bool), torch.Tensor(), torch.Tensor(), tcls)) 114 | continue 115 | 116 | # Append to text file 117 | # with open('test.txt', 'a') as file: 118 | # [file.write('%11.5g' * 7 % tuple(x) + '\n') for x in pred] 119 | 120 | # Clip boxes to image bounds 121 | clip_coords(pred, (height, width)) 122 | 123 | # Append to pycocotools JSON dictionary 124 | if save_json: 125 | # [{"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236}, ... 126 | image_id = int(Path(paths[si]).stem.split('_')[-1]) 127 | box = pred[:, :4].clone() # xyxy 128 | scale_coords(imgs[si].shape[1:], box, shapes[si][0], shapes[si][1]) # to original shape 129 | box = xyxy2xywh(box) # xywh 130 | box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner 131 | for p, b in zip(pred.tolist(), box.tolist()): 132 | jdict.append({'image_id': image_id, 133 | 'category_id': coco91class[int(p[5])], 134 | 'bbox': [round(x, 3) for x in b], 135 | 'score': round(p[4], 5)}) 136 | 137 | # Assign all predictions as incorrect 138 | correct = torch.zeros(pred.shape[0], niou, dtype=torch.bool, device=device) 139 | if nl: 140 | detected = [] # target indices 141 | tcls_tensor = labels[:, 0] 142 | 143 | # target boxes 144 | tbox = xywh2xyxy(labels[:, 1:5]) * whwh 145 | 146 | # Per target class 147 | for cls in torch.unique(tcls_tensor): 148 | ti = (cls == tcls_tensor).nonzero().view(-1) # prediction indices 149 | pi = (cls == pred[:, 5]).nonzero().view(-1) # target indices 150 | 151 | # Search for detections 152 | if pi.shape[0]: 153 | # Prediction to target ious 154 | ious, i = box_iou(pred[pi, :4], tbox[ti]).max(1) # best ious, indices 155 | 156 | # Append detections 157 | for j in (ious > iouv[0]).nonzero(): 158 | d = ti[i[j]] # detected target 159 | if d not in detected: 160 | detected.append(d) 161 | correct[pi[j]] = ious[j] > iouv # iou_thres is 1xn 162 | if len(detected) == nl: # all targets already located in image 163 | break 164 | 165 | # Append statistics (correct, conf, pcls, tcls) 166 | stats.append((correct.cpu(), pred[:, 4].cpu(), pred[:, 5].cpu(), tcls)) 167 | 168 | # Plot images 169 | if batch_i < 1: 170 | f = 'test_batch%g_gt.jpg' % batch_i # filename 171 | plot_images(imgs, targets, paths, f, names) # ground truth 172 | f = 'test_batch%g_pred.jpg' % batch_i 173 | plot_images(imgs, output_to_target(output, width, height), paths, f, names) # predictions 174 | 175 | # Compute statistics 176 | stats = [np.concatenate(x, 0) for x in zip(*stats)] # to numpy 177 | if len(stats): 178 | p, r, ap, f1, ap_class = ap_per_class(*stats) 179 | p, r, ap50, ap = p[:, 0], r[:, 0], ap[:, 0], ap.mean(1) # [P, R, AP@0.5, AP@0.5:0.95] 180 | mp, mr, map50, map = p.mean(), r.mean(), ap50.mean(), ap.mean() 181 | nt = np.bincount(stats[3].astype(np.int64), minlength=nc) # number of targets per class 182 | else: 183 | nt = torch.zeros(1) 184 | 185 | # Print results 186 | pf = '%20s' + '%12.3g' * 6 # print format 187 | print(pf % ('all', seen, nt.sum(), mp, mr, map50, map)) 188 | 189 | # Print results per class 190 | if verbose and nc > 1 and len(stats): 191 | for i, c in enumerate(ap_class): 192 | print(pf % (names[c], seen, nt[c], p[i], r[i], ap50[i], ap[i])) 193 | 194 | # Print speeds 195 | t = tuple(x / seen * 1E3 for x in (t0, t1, t0 + t1)) + (imgsz, imgsz, batch_size) # tuple 196 | if not training: 197 | print('Speed: %.1f/%.1f/%.1f ms inference/NMS/total per %gx%g image at batch-size %g' % t) 198 | 199 | # Save JSON 200 | if save_json and map50 and len(jdict): 201 | imgIds = [int(Path(x).stem.split('_')[-1]) for x in dataloader.dataset.img_files] 202 | f = 'detections_val2017_%s_results.json' % \ 203 | (weights.split(os.sep)[-1].replace('.pt', '') if weights else '') # filename 204 | print('\nCOCO mAP with pycocotools... saving %s...' % f) 205 | with open(f, 'w') as file: 206 | json.dump(jdict, file) 207 | 208 | try: 209 | from pycocotools.coco import COCO 210 | from pycocotools.cocoeval import COCOeval 211 | 212 | # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb 213 | cocoGt = COCO(glob.glob('../coco/annotations/instances_val*.json')[0]) # initialize COCO ground truth api 214 | cocoDt = cocoGt.loadRes(f) # initialize COCO pred api 215 | 216 | cocoEval = COCOeval(cocoGt, cocoDt, 'bbox') 217 | cocoEval.params.imgIds = imgIds # [:32] # only evaluate these images 218 | cocoEval.evaluate() 219 | cocoEval.accumulate() 220 | cocoEval.summarize() 221 | map, map50 = cocoEval.stats[:2] # update to pycocotools results (mAP@0.5:0.95, mAP@0.5) 222 | except: 223 | print('WARNING: pycocotools must be installed with numpy==1.17 to run correctly. ' 224 | 'See https://github.com/cocodataset/cocoapi/issues/356') 225 | 226 | # Return results 227 | maps = np.zeros(nc) + map 228 | for i, c in enumerate(ap_class): 229 | maps[c] = ap[i] 230 | return (mp, mr, map50, map, *(loss.cpu() / len(dataloader)).tolist()), maps, t 231 | 232 | 233 | if __name__ == '__main__': 234 | parser = argparse.ArgumentParser(prog='test.py') 235 | parser.add_argument('--weights', type=str, default='weights/yolov5s.pt', help='model.pt path') 236 | parser.add_argument('--data', type=str, default='data/coco.yaml', help='*.data path') 237 | parser.add_argument('--batch-size', type=int, default=32, help='size of each image batch') 238 | parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)') 239 | parser.add_argument('--conf-thres', type=float, default=0.001, help='object confidence threshold') 240 | parser.add_argument('--iou-thres', type=float, default=0.65, help='IOU threshold for NMS') 241 | parser.add_argument('--save-json', action='store_true', help='save a cocoapi-compatible JSON results file') 242 | parser.add_argument('--task', default='val', help="'val', 'test', 'study'") 243 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') 244 | parser.add_argument('--single-cls', action='store_true', help='treat as single-class dataset') 245 | parser.add_argument('--augment', action='store_true', help='augmented inference') 246 | parser.add_argument('--verbose', action='store_true', help='report mAP by class') 247 | opt = parser.parse_args() 248 | opt.save_json = opt.save_json or opt.data.endswith('coco.yaml') 249 | opt.data = glob.glob('./**/' + opt.data, recursive=True)[0] # find file 250 | print(opt) 251 | 252 | # task = 'val', 'test', 'study' 253 | if opt.task in ['val', 'test']: # (default) run normally 254 | test(opt.data, 255 | opt.weights, 256 | opt.batch_size, 257 | opt.img_size, 258 | opt.conf_thres, 259 | opt.iou_thres, 260 | opt.save_json, 261 | opt.single_cls, 262 | opt.augment) 263 | 264 | elif opt.task == 'study': # run over a range of settings and save/plot 265 | for weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']: 266 | f = 'study_%s_%s.txt' % (Path(opt.data).stem, Path(weights).stem) # filename to save to 267 | x = list(range(288, 896, 64)) # x axis 268 | y = [] # y axis 269 | for i in x: # img-size 270 | print('\nRunning %s point %s...' % (f, i)) 271 | r, _, t = test(opt.data, weights, opt.batch_size, i, opt.conf_thres, opt.iou_thres, opt.save_json) 272 | y.append(r + t) # results and times 273 | np.savetxt(f, y, fmt='%10.4g') # save 274 | os.system('zip -r study.zip study_*.txt') 275 | # plot_study_txt(f, x) # plot 276 | -------------------------------------------------------------------------------- /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 yaml 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.datasets import * 13 | from utils.utils import * 14 | 15 | mixed_precision = True 16 | try: # Mixed precision training https://github.com/NVIDIA/apex 17 | from apex import amp 18 | except: 19 | print('Apex recommended for faster mixed precision training: https://github.com/NVIDIA/apex') 20 | mixed_precision = False # not installed 21 | 22 | wdir = 'weights' + os.sep # weights dir 23 | last = wdir + 'last.pt' 24 | best = wdir + 'best.pt' 25 | results_file = 'results.txt' 26 | 27 | # Hyperparameters 28 | hyp = {'lr0': 0.01, # initial learning rate (SGD=1E-2, Adam=1E-3) 29 | 'momentum': 0.937, # SGD momentum 30 | 'weight_decay': 5e-4, # optimizer weight decay 31 | 'giou': 0.05, # giou loss gain 32 | 'cls': 0.58, # cls loss gain 33 | 'cls_pw': 1.0, # cls BCELoss positive_weight 34 | 'obj': 1.0, # obj loss gain (*=img_size/320 if img_size != 320) 35 | 'obj_pw': 1.0, # obj BCELoss positive_weight 36 | 'iou_t': 0.20, # iou training threshold 37 | 'anchor_t': 4.0, # anchor-multiple threshold 38 | 'fl_gamma': 0.0, # focal loss gamma (efficientDet default is gamma=1.5) 39 | 'hsv_h': 0.014, # image HSV-Hue augmentation (fraction) 40 | 'hsv_s': 0.68, # image HSV-Saturation augmentation (fraction) 41 | 'hsv_v': 0.36, # image HSV-Value augmentation (fraction) 42 | 'degrees': 0.0, # image rotation (+/- deg) 43 | 'translate': 0.0, # image translation (+/- fraction) 44 | 'scale': 0.5, # image scale (+/- gain) 45 | 'shear': 0.0} # image shear (+/- deg) 46 | print(hyp) 47 | 48 | # Overwrite hyp with hyp*.txt (optional) 49 | f = glob.glob('hyp*.txt') 50 | if f: 51 | print('Using %s' % f[0]) 52 | for k, v in zip(hyp.keys(), np.loadtxt(f[0])): 53 | hyp[k] = v 54 | 55 | # Print focal loss if gamma > 0 56 | if hyp['fl_gamma']: 57 | print('Using FocalLoss(gamma=%g)' % hyp['fl_gamma']) 58 | 59 | 60 | def train(hyp): 61 | epochs = opt.epochs # 300 62 | batch_size = opt.batch_size # 64 63 | weights = opt.weights # initial training weights 64 | 65 | # Configure 66 | init_seeds(1) 67 | with open(opt.data) as f: 68 | data_dict = yaml.load(f, Loader=yaml.FullLoader) # model dict 69 | train_path = data_dict['train'] 70 | test_path = data_dict['val'] 71 | nc = 1 if opt.single_cls else int(data_dict['nc']) # number of classes 72 | 73 | # Remove previous results 74 | for f in glob.glob('*_batch*.jpg') + glob.glob(results_file): 75 | os.remove(f) 76 | 77 | # Create model 78 | model = Model(opt.cfg).to(device) 79 | assert model.md['nc'] == nc, '%s nc=%g classes but %s nc=%g classes' % (opt.data, nc, opt.cfg, model.md['nc']) 80 | 81 | # Image sizes 82 | gs = int(max(model.stride)) # grid size (max stride) 83 | if any(x % gs != 0 for x in opt.img_size): 84 | print('WARNING: --img-size %g,%g must be multiple of %s max stride %g' % (*opt.img_size, opt.cfg, gs)) 85 | imgsz, imgsz_test = [make_divisible(x, gs) for x in opt.img_size] # image sizes (train, test) 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'] = \ 117 | {k: v for k, v in ckpt['model'].state_dict().items() if model.state_dict()[k].numel() == v.numel()} 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 | 156 | # Dataset 157 | dataset = LoadImagesAndLabels(train_path, imgsz, batch_size, 158 | augment=True, 159 | hyp=hyp, # augmentation hyperparameters 160 | rect=opt.rect, # rectangular training 161 | cache_images=opt.cache_images, 162 | single_cls=opt.single_cls) 163 | mlc = np.concatenate(dataset.labels, 0)[:, 0].max() # max label class 164 | assert mlc < nc, 'Label class %g exceeds nc=%g in %s. Correct your labels or your model.' % (mlc, nc, opt.cfg) 165 | 166 | # Dataloader 167 | batch_size = min(batch_size, len(dataset)) 168 | nw = min([os.cpu_count(), batch_size if batch_size > 1 else 0, 8]) # number of workers 169 | dataloader = torch.utils.data.DataLoader(dataset, 170 | batch_size=batch_size, 171 | num_workers=nw, 172 | shuffle=not opt.rect, # Shuffle=True unless rectangular training is used 173 | pin_memory=True, 174 | collate_fn=dataset.collate_fn) 175 | 176 | # Testloader 177 | testloader = torch.utils.data.DataLoader(LoadImagesAndLabels(test_path, imgsz_test, batch_size, 178 | hyp=hyp, 179 | rect=True, 180 | cache_images=opt.cache_images, 181 | single_cls=opt.single_cls), 182 | batch_size=batch_size, 183 | num_workers=nw, 184 | pin_memory=True, 185 | collate_fn=dataset.collate_fn) 186 | 187 | # Model parameters 188 | hyp['cls'] *= nc / 80. # scale coco-tuned hyp['cls'] to current dataset 189 | model.nc = nc # attach number of classes to model 190 | model.hyp = hyp # attach hyperparameters to model 191 | model.gr = 1.0 # giou loss ratio (obj_loss = 1.0 or giou) 192 | model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) # attach class weights 193 | model.names = data_dict['names'] 194 | 195 | # class frequency 196 | labels = np.concatenate(dataset.labels, 0) 197 | c = torch.tensor(labels[:, 0]) # classes 198 | # cf = torch.bincount(c.long(), minlength=nc) + 1. 199 | # model._initialize_biases(cf.to(device)) 200 | # plot_labels(labels) #<----------------------------close by xujing 201 | tb_writer.add_histogram('classes', c, 0) 202 | 203 | # Exponential moving average 204 | ema = torch_utils.ModelEMA(model) 205 | 206 | # Start training 207 | t0 = time.time() 208 | nb = len(dataloader) # number of batches 209 | n_burn = max(3 * nb, 1e3) # burn-in iterations, max(3 epochs, 1k iterations) 210 | maps = np.zeros(nc) # mAP per class 211 | results = (0, 0, 0, 0, 0, 0, 0) # 'P', 'R', 'mAP', 'F1', 'val GIoU', 'val Objectness', 'val Classification' 212 | print('Image sizes %g train, %g test' % (imgsz, imgsz_test)) 213 | print('Using %g dataloader workers' % nw) 214 | print('Starting training for %g epochs...' % epochs) 215 | # torch.autograd.set_detect_anomaly(True) 216 | for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------ 217 | model.train() 218 | 219 | # Update image weights (optional) 220 | if dataset.image_weights: 221 | w = model.class_weights.cpu().numpy() * (1 - maps) ** 2 # class weights 222 | image_weights = labels_to_image_weights(dataset.labels, nc=nc, class_weights=w) 223 | dataset.indices = random.choices(range(dataset.n), weights=image_weights, k=dataset.n) # rand weighted idx 224 | 225 | mloss = torch.zeros(4, device=device) # mean losses 226 | print(('\n' + '%10s' * 8) % ('Epoch', 'gpu_mem', 'GIoU', 'obj', 'cls', 'total', 'targets', 'img_size')) 227 | pbar = tqdm(enumerate(dataloader), total=nb) # progress bar 228 | for i, (imgs, targets, paths, _) in pbar: # batch ------------------------------------------------------------- 229 | ni = i + nb * epoch # number integrated batches (since train start) 230 | imgs = imgs.to(device).float() / 255.0 # uint8 to float32, 0 - 255 to 0.0 - 1.0 231 | 232 | # Burn-in 233 | if ni <= n_burn: 234 | xi = [0, n_burn] # x interp 235 | # model.gr = np.interp(ni, xi, [0.0, 1.0]) # giou loss ratio (obj_loss = 1.0 or giou) 236 | accumulate = max(1, np.interp(ni, xi, [1, nbs / batch_size]).round()) 237 | for j, x in enumerate(optimizer.param_groups): 238 | # bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0 239 | x['lr'] = np.interp(ni, xi, [0.1 if j == 2 else 0.0, x['initial_lr'] * lf(epoch)]) 240 | if 'momentum' in x: 241 | x['momentum'] = np.interp(ni, xi, [0.9, hyp['momentum']]) 242 | 243 | # Multi-scale 244 | if opt.multi_scale: 245 | sz = random.randrange(imgsz * 0.5, imgsz * 1.5 + gs) // gs * gs # size 246 | sf = sz / max(imgs.shape[2:]) # scale factor 247 | if sf != 1: 248 | ns = [math.ceil(x * sf / gs) * gs for x in imgs.shape[2:]] # new shape (stretched to gs-multiple) 249 | imgs = F.interpolate(imgs, size=ns, mode='bilinear', align_corners=False) 250 | 251 | # Forward 252 | pred = model(imgs) 253 | 254 | # Loss 255 | loss, loss_items = compute_loss(pred, targets.to(device), model) 256 | if not torch.isfinite(loss): 257 | print('WARNING: non-finite loss, ending training ', loss_items) 258 | return results 259 | 260 | # Backward 261 | if mixed_precision: 262 | with amp.scale_loss(loss, optimizer) as scaled_loss: 263 | scaled_loss.backward() 264 | else: 265 | loss.backward() 266 | 267 | # Optimize 268 | if ni % accumulate == 0: 269 | optimizer.step() 270 | optimizer.zero_grad() 271 | ema.update(model) 272 | 273 | # Print 274 | mloss = (mloss * i + loss_items) / (i + 1) # update mean losses 275 | mem = '%.3gG' % (torch.cuda.memory_cached() / 1E9 if torch.cuda.is_available() else 0) # (GB) 276 | s = ('%10s' * 2 + '%10.4g' * 6) % ( 277 | '%g/%g' % (epoch, epochs - 1), mem, *mloss, targets.shape[0], imgs.shape[-1]) 278 | pbar.set_description(s) 279 | 280 | # Plot 281 | if ni < 3: 282 | f = 'train_batch%g.jpg' % i # filename 283 | res = plot_images(images=imgs, targets=targets, paths=paths, fname=f) 284 | if tb_writer: 285 | tb_writer.add_image(f, res, dataformats='HWC', global_step=epoch) 286 | # tb_writer.add_graph(model, imgs) # add model to tensorboard 287 | 288 | # end batch ------------------------------------------------------------------------------------------------ 289 | 290 | # Scheduler 291 | scheduler.step() 292 | 293 | # mAP 294 | ema.update_attr(model) 295 | final_epoch = epoch + 1 == epochs 296 | if not opt.notest or final_epoch: # Calculate mAP 297 | results, maps, times = test.test(opt.data, 298 | batch_size=batch_size, 299 | imgsz=imgsz_test, 300 | save_json=final_epoch and opt.data.endswith(os.sep + 'coco.yaml'), 301 | model=ema.ema, 302 | single_cls=opt.single_cls, 303 | dataloader=testloader, 304 | fast=ni < n_burn) 305 | 306 | # Write 307 | with open(results_file, 'a') as f: 308 | f.write(s + '%10.4g' * 7 % results + '\n') # P, R, mAP, F1, test_losses=(GIoU, obj, cls) 309 | if len(opt.name) and opt.bucket: 310 | os.system('gsutil cp results.txt gs://%s/results/results%s.txt' % (opt.bucket, opt.name)) 311 | 312 | # Tensorboard 313 | if tb_writer: 314 | tags = ['train/giou_loss', 'train/obj_loss', 'train/cls_loss', 315 | 'metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/F1', 316 | 'val/giou_loss', 'val/obj_loss', 'val/cls_loss'] 317 | for x, tag in zip(list(mloss[:-1]) + list(results), tags): 318 | tb_writer.add_scalar(tag, x, epoch) 319 | 320 | # Update best mAP 321 | fi = fitness(np.array(results).reshape(1, -1)) # fitness_i = weighted combination of [P, R, mAP, F1] 322 | if fi > best_fitness: 323 | best_fitness = fi 324 | 325 | # Save model 326 | save = (not opt.nosave) or (final_epoch and not opt.evolve) 327 | if save: 328 | with open(results_file, 'r') as f: # create checkpoint 329 | ckpt = {'epoch': epoch, 330 | 'best_fitness': best_fitness, 331 | 'training_results': f.read(), 332 | 'model': ema.ema.module if hasattr(model, 'module') else ema.ema, 333 | 'optimizer': None if final_epoch else optimizer.state_dict()} 334 | 335 | # Save last, best and delete 336 | torch.save(ckpt, last) 337 | if (best_fitness == fi) and not final_epoch: 338 | torch.save(ckpt, best) 339 | del ckpt 340 | 341 | # end epoch ---------------------------------------------------------------------------------------------------- 342 | # end training 343 | 344 | n = opt.name 345 | if len(n): 346 | n = '_' + n if not n.isnumeric() else n 347 | fresults, flast, fbest = 'results%s.txt' % n, wdir + 'last%s.pt' % n, wdir + 'best%s.pt' % n 348 | for f1, f2 in zip([wdir + 'last.pt', wdir + 'best.pt', 'results.txt'], [flast, fbest, fresults]): 349 | if os.path.exists(f1): 350 | os.rename(f1, f2) # rename 351 | ispt = f2.endswith('.pt') # is *.pt 352 | strip_optimizer(f2) if ispt else None # strip optimizer 353 | os.system('gsutil cp %s gs://%s/weights' % (f2, opt.bucket)) if opt.bucket and ispt else None # upload 354 | 355 | if not opt.evolve: 356 | # plot_results() # save as results.png 357 | pass 358 | print('%g epochs completed in %.3f hours.\n' % (epoch - start_epoch + 1, (time.time() - t0) / 3600)) 359 | dist.destroy_process_group() if torch.cuda.device_count() > 1 else None 360 | torch.cuda.empty_cache() 361 | return results 362 | 363 | 364 | if __name__ == '__main__': 365 | parser = argparse.ArgumentParser() 366 | parser.add_argument('--epochs', type=int, default=300) 367 | parser.add_argument('--batch-size', type=int, default=16) 368 | parser.add_argument('--cfg', type=str, default='models/yolov5s.yaml', help='*.cfg path') 369 | parser.add_argument('--data', type=str, default='data/coco128.yaml', help='*.data path') 370 | parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='train,test sizes') 371 | parser.add_argument('--rect', action='store_true', help='rectangular training') 372 | parser.add_argument('--resume', action='store_true', help='resume training from last.pt') 373 | parser.add_argument('--nosave', action='store_true', help='only save final checkpoint') 374 | parser.add_argument('--notest', action='store_true', help='only test final epoch') 375 | parser.add_argument('--evolve', action='store_true', help='evolve hyperparameters') 376 | parser.add_argument('--bucket', type=str, default='', help='gsutil bucket') 377 | parser.add_argument('--cache-images', action='store_true', help='cache images for faster training') 378 | parser.add_argument('--weights', type=str, default='', help='initial weights path') 379 | parser.add_argument('--name', default='', help='renames results.txt to results_name.txt if supplied') 380 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') 381 | parser.add_argument('--adam', action='store_true', help='use adam optimizer') 382 | parser.add_argument('--multi-scale', action='store_true', help='vary img-size +/- 50%') 383 | parser.add_argument('--single-cls', action='store_true', help='train as single-class dataset') 384 | opt = parser.parse_args() 385 | opt.weights = last if opt.resume else opt.weights 386 | opt.cfg = glob.glob('./**/' + opt.cfg, recursive=True)[0] # find file 387 | opt.data = glob.glob('./**/' + opt.data, recursive=True)[0] # find file 388 | print(opt) 389 | opt.img_size.extend([opt.img_size[-1]] * (2 - len(opt.img_size))) # extend to 2 sizes (train, test) 390 | device = torch_utils.select_device(opt.device, apex=mixed_precision, batch_size=opt.batch_size) 391 | # check_git_status() 392 | if device.type == 'cpu': 393 | mixed_precision = False 394 | 395 | # Train 396 | if not opt.evolve: 397 | tb_writer = SummaryWriter(comment=opt.name) 398 | print('Start Tensorboard with "tensorboard --logdir=runs", view at http://localhost:6006/') 399 | train(hyp) 400 | 401 | # Evolve hyperparameters (optional) 402 | else: 403 | tb_writer = None 404 | opt.notest, opt.nosave = True, True # only test/save final epoch 405 | if opt.bucket: 406 | os.system('gsutil cp gs://%s/evolve.txt .' % opt.bucket) # download evolve.txt if exists 407 | 408 | for _ in range(10): # generations to evolve 409 | if os.path.exists('evolve.txt'): # if evolve.txt exists: select best hyps and mutate 410 | # Select parent(s) 411 | parent = 'single' # parent selection method: 'single' or 'weighted' 412 | x = np.loadtxt('evolve.txt', ndmin=2) 413 | n = min(5, len(x)) # number of previous results to consider 414 | x = x[np.argsort(-fitness(x))][:n] # top n mutations 415 | w = fitness(x) - fitness(x).min() # weights 416 | if parent == 'single' or len(x) == 1: 417 | # x = x[random.randint(0, n - 1)] # random selection 418 | x = x[random.choices(range(n), weights=w)[0]] # weighted selection 419 | elif parent == 'weighted': 420 | x = (x * w.reshape(n, 1)).sum(0) / w.sum() # weighted combination 421 | 422 | # Mutate 423 | mp, s = 0.9, 0.2 # mutation probability, sigma 424 | npr = np.random 425 | npr.seed(int(time.time())) 426 | g = np.array([1, 1, 1, 1, 1, 1, 1, 0, .1, 1, 0, 1, 1, 1, 1, 1, 1, 1]) # gains 427 | ng = len(g) 428 | v = np.ones(ng) 429 | while all(v == 1): # mutate until a change occurs (prevent duplicates) 430 | v = (g * (npr.random(ng) < mp) * npr.randn(ng) * npr.random() * s + 1).clip(0.3, 3.0) 431 | for i, k in enumerate(hyp.keys()): # plt.hist(v.ravel(), 300) 432 | hyp[k] = x[i + 7] * v[i] # mutate 433 | 434 | # Clip to limits 435 | keys = ['lr0', 'iou_t', 'momentum', 'weight_decay', 'hsv_s', 'hsv_v', 'translate', 'scale', 'fl_gamma'] 436 | 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)] 437 | for k, v in zip(keys, limits): 438 | hyp[k] = np.clip(hyp[k], v[0], v[1]) 439 | 440 | # Train mutation 441 | results = train(hyp.copy()) 442 | 443 | # Write mutation results 444 | print_mutation(hyp, results, opt.bucket) 445 | 446 | # Plot results 447 | # plot_evolution_results(hyp) 448 | -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DataXujing/YOLO-v5/ead1c141106f114d92dddafb6ac8c57d7e96afb4/utils/__init__.py -------------------------------------------------------------------------------- /utils/activations.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.functional as F 3 | import torch.nn as nn 4 | 5 | 6 | # Swish ------------------------------------------------------------------------ 7 | class SwishImplementation(torch.autograd.Function): 8 | @staticmethod 9 | def forward(ctx, x): 10 | ctx.save_for_backward(x) 11 | return x * torch.sigmoid(x) 12 | 13 | @staticmethod 14 | def backward(ctx, grad_output): 15 | x = ctx.saved_tensors[0] 16 | sx = torch.sigmoid(x) 17 | return grad_output * (sx * (1 + x * (1 - sx))) 18 | 19 | 20 | class MemoryEfficientSwish(nn.Module): 21 | @staticmethod 22 | def forward(x): 23 | return SwishImplementation.apply(x) 24 | 25 | 26 | class HardSwish(nn.Module): # https://arxiv.org/pdf/1905.02244.pdf 27 | @staticmethod 28 | def forward(x): 29 | return x * F.hardtanh(x + 3, 0., 6., True) / 6. 30 | 31 | 32 | class Swish(nn.Module): 33 | @staticmethod 34 | def forward(x): 35 | return x * torch.sigmoid(x) 36 | 37 | 38 | # Mish ------------------------------------------------------------------------ 39 | class MishImplementation(torch.autograd.Function): 40 | @staticmethod 41 | def forward(ctx, x): 42 | ctx.save_for_backward(x) 43 | return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x))) 44 | 45 | @staticmethod 46 | def backward(ctx, grad_output): 47 | x = ctx.saved_tensors[0] 48 | sx = torch.sigmoid(x) 49 | fx = F.softplus(x).tanh() 50 | return grad_output * (fx + x * sx * (1 - fx * fx)) 51 | 52 | 53 | class MemoryEfficientMish(nn.Module): 54 | @staticmethod 55 | def forward(x): 56 | return MishImplementation.apply(x) 57 | 58 | 59 | class Mish(nn.Module): # https://github.com/digantamisra98/Mish 60 | @staticmethod 61 | def forward(x): 62 | return x * F.softplus(x).tanh() 63 | -------------------------------------------------------------------------------- /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 | # Error check 29 | if not (r == 0 and os.path.exists(weights) and os.path.getsize(weights) > 1E6): # weights exist and > 1MB 30 | os.system('rm ' + weights) # remove partial downloads 31 | raise Exception(msg) 32 | 33 | 34 | def gdrive_download(id='1HaXkef9z6y5l4vUnCYgdmEAj61c6bfWO', name='coco.zip'): 35 | # https://gist.github.com/tanaikech/f0f2d122e05bf5f971611258c22c110f 36 | # Downloads a file from Google Drive, accepting presented query 37 | # from utils.google_utils import *; gdrive_download() 38 | t = time.time() 39 | 40 | print('Downloading https://drive.google.com/uc?export=download&id=%s as %s... ' % (id, name), end='') 41 | os.remove(name) if os.path.exists(name) else None # remove existing 42 | os.remove('cookie') if os.path.exists('cookie') else None 43 | 44 | # Attempt file download 45 | os.system("curl -c ./cookie -s -L \"https://drive.google.com/uc?export=download&id=%s\" > /dev/null" % id) 46 | if os.path.exists('cookie'): # large file 47 | s = "curl -Lb ./cookie \"https://drive.google.com/uc?export=download&confirm=`awk '/download/ {print $NF}' ./cookie`&id=%s\" -o %s" % ( 48 | id, name) 49 | else: # small file 50 | s = "curl -s -L -o %s 'https://drive.google.com/uc?export=download&id=%s'" % (name, id) 51 | r = os.system(s) # execute, capture return values 52 | os.remove('cookie') if os.path.exists('cookie') else None 53 | 54 | # Error check 55 | if r != 0: 56 | os.remove(name) if os.path.exists(name) else None # remove partial 57 | print('Download error ') # raise Exception('Download error') 58 | return r 59 | 60 | # Unzip if archive 61 | if name.endswith('.zip'): 62 | print('unzipping... ', end='') 63 | os.system('unzip -q %s' % name) # unzip 64 | os.remove(name) # remove zip to free space 65 | 66 | print('Done (%.1fs)' % (time.time() - t)) 67 | return r 68 | 69 | # def upload_blob(bucket_name, source_file_name, destination_blob_name): 70 | # # Uploads a file to a bucket 71 | # # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python 72 | # 73 | # storage_client = storage.Client() 74 | # bucket = storage_client.get_bucket(bucket_name) 75 | # blob = bucket.blob(destination_blob_name) 76 | # 77 | # blob.upload_from_filename(source_file_name) 78 | # 79 | # print('File {} uploaded to {}.'.format( 80 | # source_file_name, 81 | # destination_blob_name)) 82 | # 83 | # 84 | # def download_blob(bucket_name, source_blob_name, destination_file_name): 85 | # # Uploads a blob from a bucket 86 | # storage_client = storage.Client() 87 | # bucket = storage_client.get_bucket(bucket_name) 88 | # blob = bucket.blob(source_blob_name) 89 | # 90 | # blob.download_to_filename(destination_file_name) 91 | # 92 | # print('Blob {} downloaded to {}.'.format( 93 | # source_blob_name, 94 | # destination_file_name)) 95 | -------------------------------------------------------------------------------- /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 | 11 | 12 | def init_seeds(seed=0): 13 | torch.manual_seed(seed) 14 | 15 | # Speed-reproducibility tradeoff https://pytorch.org/docs/stable/notes/randomness.html 16 | if seed == 0: # slower, more reproducible 17 | cudnn.deterministic = True 18 | cudnn.benchmark = False 19 | else: # faster, less reproducible 20 | cudnn.deterministic = False 21 | cudnn.benchmark = True 22 | 23 | 24 | def select_device(device='', apex=False, batch_size=None): 25 | # device = 'cpu' or '0' or '0,1,2,3' 26 | cpu_request = device.lower() == 'cpu' 27 | if device and not cpu_request: # if device requested other than 'cpu' 28 | os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable 29 | assert torch.cuda.is_available(), 'CUDA unavailable, invalid device %s requested' % device # check availablity 30 | 31 | cuda = False if cpu_request else torch.cuda.is_available() 32 | if cuda: 33 | c = 1024 ** 2 # bytes to MB 34 | ng = torch.cuda.device_count() 35 | if ng > 1 and batch_size: # check that batch_size is compatible with device_count 36 | assert batch_size % ng == 0, 'batch-size %g not multiple of GPU count %g' % (batch_size, ng) 37 | x = [torch.cuda.get_device_properties(i) for i in range(ng)] 38 | s = 'Using CUDA ' + ('Apex ' if apex else '') # apex for mixed precision https://github.com/NVIDIA/apex 39 | for i in range(0, ng): 40 | if i == 1: 41 | s = ' ' * len(s) 42 | print("%sdevice%g _CudaDeviceProperties(name='%s', total_memory=%dMB)" % 43 | (s, i, x[i].name, x[i].total_memory / c)) 44 | else: 45 | print('Using CPU') 46 | 47 | print('') # skip a line 48 | return torch.device('cuda:0' if cuda else 'cpu') 49 | 50 | 51 | def time_synchronized(): 52 | torch.cuda.synchronize() if torch.cuda.is_available() else None 53 | return time.time() 54 | 55 | 56 | def initialize_weights(model): 57 | for m in model.modules(): 58 | t = type(m) 59 | if t is nn.Conv2d: 60 | pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') 61 | elif t is nn.BatchNorm2d: 62 | m.eps = 1e-4 63 | m.momentum = 0.03 64 | elif t in [nn.LeakyReLU, nn.ReLU, nn.ReLU6]: 65 | m.inplace = True 66 | 67 | 68 | def find_modules(model, mclass=nn.Conv2d): 69 | # finds layer indices matching module class 'mclass' 70 | return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)] 71 | 72 | 73 | def fuse_conv_and_bn(conv, bn): 74 | # https://tehnokv.com/posts/fusing-batchnorm-and-conv/ 75 | with torch.no_grad(): 76 | # init 77 | fusedconv = torch.nn.Conv2d(conv.in_channels, 78 | conv.out_channels, 79 | kernel_size=conv.kernel_size, 80 | stride=conv.stride, 81 | padding=conv.padding, 82 | bias=True) 83 | 84 | # prepare filters 85 | w_conv = conv.weight.clone().view(conv.out_channels, -1) 86 | w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var))) 87 | fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.size())) 88 | 89 | # prepare spatial bias 90 | if conv.bias is not None: 91 | b_conv = conv.bias 92 | else: 93 | b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) 94 | b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps)) 95 | fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn) 96 | 97 | return fusedconv 98 | 99 | 100 | def model_info(model, verbose=False): 101 | # Plots a line-by-line description of a PyTorch model 102 | n_p = sum(x.numel() for x in model.parameters()) # number parameters 103 | n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients 104 | if verbose: 105 | print('%5s %40s %9s %12s %20s %10s %10s' % ('layer', 'name', 'gradient', 'parameters', 'shape', 'mu', 'sigma')) 106 | for i, (name, p) in enumerate(model.named_parameters()): 107 | name = name.replace('module_list.', '') 108 | print('%5g %40s %9s %12g %20s %10.3g %10.3g' % 109 | (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std())) 110 | 111 | try: # FLOPS 112 | from thop import profile 113 | macs, _ = profile(model, inputs=(torch.zeros(1, 3, 480, 640),), verbose=False) 114 | fs = ', %.1f GFLOPS' % (macs / 1E9 * 2) 115 | except: 116 | fs = '' 117 | 118 | print('Model Summary: %g layers, %g parameters, %g gradients%s' % (len(list(model.parameters())), n_p, n_g, fs)) 119 | 120 | 121 | def load_classifier(name='resnet101', n=2): 122 | # Loads a pretrained model reshaped to n-class output 123 | import pretrainedmodels # https://github.com/Cadene/pretrained-models.pytorch#torchvision 124 | model = pretrainedmodels.__dict__[name](num_classes=1000, pretrained='imagenet') 125 | 126 | # Display model properties 127 | for x in ['model.input_size', 'model.input_space', 'model.input_range', 'model.mean', 'model.std']: 128 | print(x + ' =', eval(x)) 129 | 130 | # Reshape output to n classes 131 | filters = model.last_linear.weight.shape[1] 132 | model.last_linear.bias = torch.nn.Parameter(torch.zeros(n)) 133 | model.last_linear.weight = torch.nn.Parameter(torch.zeros(n, filters)) 134 | model.last_linear.out_features = n 135 | return model 136 | 137 | 138 | def scale_img(img, ratio=1.0, same_shape=False): # img(16,3,256,416), r=ratio 139 | # scales img(bs,3,y,x) by ratio 140 | h, w = img.shape[2:] 141 | s = (int(h * ratio), int(w * ratio)) # new size 142 | img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize 143 | if not same_shape: # pad/crop img 144 | gs = 32 # (pixels) grid size 145 | h, w = [math.ceil(x * ratio / gs) * gs for x in (h, w)] 146 | return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean 147 | 148 | 149 | class ModelEMA: 150 | """ Model Exponential Moving Average from https://github.com/rwightman/pytorch-image-models 151 | Keep a moving average of everything in the model state_dict (parameters and buffers). 152 | This is intended to allow functionality like 153 | https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage 154 | A smoothed version of the weights is necessary for some training schemes to perform well. 155 | E.g. Google's hyper-params for training MNASNet, MobileNet-V3, EfficientNet, etc that use 156 | RMSprop with a short 2.4-3 epoch decay period and slow LR decay rate of .96-.99 requires EMA 157 | smoothing of weights to match results. Pay attention to the decay constant you are using 158 | relative to your update count per epoch. 159 | To keep EMA from using GPU resources, set device='cpu'. This will save a bit of memory but 160 | disable validation of the EMA weights. Validation will have to be done manually in a separate 161 | process, or after the training stops converging. 162 | This class is sensitive where it is initialized in the sequence of model init, 163 | GPU assignment and distributed training wrappers. 164 | I've tested with the sequence in my own train.py for torch.DataParallel, apex.DDP, and single-GPU. 165 | """ 166 | 167 | def __init__(self, model, decay=0.9999, device=''): 168 | # make a copy of the model for accumulating moving average of weights 169 | self.ema = deepcopy(model) 170 | self.ema.eval() 171 | self.updates = 0 # number of EMA updates 172 | self.decay = lambda x: decay * (1 - math.exp(-x / 2000)) # decay exponential ramp (to help early epochs) 173 | self.device = device # perform ema on different device from model if set 174 | if device: 175 | self.ema.to(device=device) 176 | for p in self.ema.parameters(): 177 | p.requires_grad_(False) 178 | 179 | def update(self, model): 180 | self.updates += 1 181 | d = self.decay(self.updates) 182 | with torch.no_grad(): 183 | if type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel): 184 | msd, esd = model.module.state_dict(), self.ema.module.state_dict() 185 | else: 186 | msd, esd = model.state_dict(), self.ema.state_dict() 187 | 188 | for k, v in esd.items(): 189 | if v.dtype.is_floating_point: 190 | v *= d 191 | v += (1. - d) * msd[k].detach() 192 | 193 | def update_attr(self, model): 194 | # Assign attributes (which may change during training) 195 | for k in model.__dict__.keys(): 196 | if not k.startswith('_'): 197 | setattr(self.ema, k, getattr(model, k)) 198 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /weights/readme: -------------------------------------------------------------------------------- 1 | 此处存放与训练和训练的模型! -------------------------------------------------------------------------------- /yolov5_trt.py: -------------------------------------------------------------------------------- 1 | """ 2 | An example that uses TensorRT's Python api to make inferences. 3 | """ 4 | import ctypes 5 | import os 6 | import random 7 | import sys 8 | import threading 9 | import time 10 | 11 | import cv2 12 | import numpy as np 13 | import pycuda.autoinit 14 | import pycuda.driver as cuda 15 | import tensorrt as trt 16 | import torch 17 | import torchvision 18 | 19 | INPUT_W = 640 20 | INPUT_H = 640 21 | CONF_THRESH = 0.25 22 | IOU_THRESHOLD = 0.45 23 | 24 | PROB_THRESH = 0.65 25 | 26 | id2label = { 27 | 0:"normal", #A 28 | 1:"normal", #B 29 | 2:"normal", #C 30 | 3:"normal", #D 31 | 4:"normal", #E 32 | 5:"early_esophageal_cancer", #F 33 | 6:"early_gastric_cancer", #G 34 | 7:"normal", #N1 35 | 8:"normal", #N2 36 | 9:"normal", #N3 37 | 10:"normal", #N4 38 | 11:"normal", #N5 39 | 12:"normal", #N6 40 | 13:"normal", #N7 41 | 14:"normal", #N8 42 | 15:"normal", #N9 43 | 16:"normal", #N10 44 | } 45 | 46 | # 画框 47 | def plot_one_box(x, img, color=None, label=None, line_thickness=None): 48 | """ 49 | description: Plots one bounding box on image img, 50 | this function comes from YoLov5 project. 51 | param: 52 | x: a box likes [x1,y1,x2,y2] 53 | img: a opencv image object 54 | color: color to draw rectangle, such as (0,255,0) 55 | label: str 56 | line_thickness: int 57 | return: 58 | no return 59 | 60 | """ 61 | # if not os.path.exists("detect_res"): 62 | # os.makdedirs("detect_res") 63 | tl = ( 64 | line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1 65 | ) # line/font thickness 66 | color = color or [random.randint(0, 255) for _ in range(3)] 67 | c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3])) 68 | cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA) 69 | if label: 70 | tf = max(tl - 1, 1) # font thickness 71 | t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0] 72 | c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3 73 | cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA) # filled 74 | cv2.putText( 75 | img, 76 | label, 77 | (c1[0], c1[1] - 2), 78 | 0, 79 | tl / 3, 80 | [225, 255, 255], 81 | thickness=tf, 82 | lineType=cv2.LINE_AA, 83 | ) 84 | # cv2.imwrite(os.path.join(save_path,file_name),img) 85 | 86 | 87 | class YoLov5TRT(object): 88 | """ 89 | description: A YOLOv5 class that warps TensorRT ops, preprocess and postprocess ops. 90 | """ 91 | 92 | def __init__(self, engine_file_path): 93 | # Create a Context on this device, 94 | self.cfx = cuda.Device(0).make_context() 95 | stream = cuda.Stream() 96 | TRT_LOGGER = trt.Logger(trt.Logger.INFO) 97 | runtime = trt.Runtime(TRT_LOGGER) 98 | 99 | # <--------------------读取序列化引擎 100 | with open(engine_file_path, "rb") as f: 101 | engine = runtime.deserialize_cuda_engine(f.read()) 102 | context = engine.create_execution_context() 103 | 104 | host_inputs = [] 105 | cuda_inputs = [] 106 | host_outputs = [] 107 | cuda_outputs = [] 108 | bindings = [] 109 | 110 | for binding in engine: 111 | size = trt.volume(engine.get_binding_shape(binding)) * engine.max_batch_size 112 | dtype = trt.nptype(engine.get_binding_dtype(binding)) 113 | # Allocate host and device buffers 114 | host_mem = cuda.pagelocked_empty(size, dtype) 115 | cuda_mem = cuda.mem_alloc(host_mem.nbytes) 116 | # Append the device buffer to device bindings. 117 | bindings.append(int(cuda_mem)) 118 | # Append to the appropriate list. 119 | if engine.binding_is_input(binding): 120 | host_inputs.append(host_mem) 121 | cuda_inputs.append(cuda_mem) 122 | else: 123 | host_outputs.append(host_mem) 124 | cuda_outputs.append(cuda_mem) 125 | 126 | # Store 127 | self.stream = stream 128 | self.context = context 129 | self.engine = engine 130 | self.host_inputs = host_inputs 131 | self.cuda_inputs = cuda_inputs 132 | self.host_outputs = host_outputs 133 | self.cuda_outputs = cuda_outputs 134 | self.bindings = bindings 135 | 136 | def infer(self, input_image_path): 137 | threading.Thread.__init__(self) 138 | # Make self the active context, pushing it on top of the context stack. 139 | self.cfx.push() 140 | # Restore 141 | stream = self.stream 142 | context = self.context 143 | engine = self.engine 144 | host_inputs = self.host_inputs 145 | cuda_inputs = self.cuda_inputs 146 | host_outputs = self.host_outputs 147 | cuda_outputs = self.cuda_outputs 148 | bindings = self.bindings 149 | 150 | # # <-----------------模型的前处理,图像处理 151 | 152 | input_image, image_raw, origin_h, origin_w = self.preprocess_image_0( 153 | input_image_path 154 | ) 155 | # Copy input image to host buffer 156 | np.copyto(host_inputs[0], input_image.ravel()) 157 | # Transfer input data to the GPU. 158 | cuda.memcpy_htod_async(cuda_inputs[0], host_inputs[0], stream) 159 | # #<-----------基于序列化的引擎,开始推断 160 | start = time.time() 161 | context.execute_async(bindings=bindings, stream_handle=stream.handle) 162 | # Transfer predictions back from the GPU. 163 | cuda.memcpy_dtoh_async(host_outputs[0], cuda_outputs[0], stream) 164 | # Synchronize the stream 165 | stream.synchronize() 166 | # Remove any context from the top of the context stack, deactivating it. 167 | self.cfx.pop() 168 | # Here we use the first row of output in that batch_size = 1 169 | # <---------------得到推断结果 170 | output = host_outputs[0] 171 | end = time.time() 172 | print(output.shape) 173 | 174 | # <--------------后处理 175 | result_boxes, result_scores, result_classid = self.post_process( 176 | output, origin_h, origin_w 177 | ) 178 | 179 | print("waste_time: {}".format(end-start)) 180 | # Draw rectangles and labels on the original image 181 | 182 | file_name = input_image_path.split("/")[-1] 183 | for i in range(len(result_boxes)): 184 | box = result_boxes[i] 185 | if result_scores[i] <= PROB_THRESH: 186 | continue; 187 | if not int(result_classid[i]) in [5,6]: 188 | continue; 189 | plot_one_box( 190 | box, 191 | image_raw, 192 | label="{}:{:.2f}".format( 193 | id2label[int(result_classid[i])], result_scores[i] 194 | ), 195 | ) 196 | parent, filename = os.path.split(input_image_path) 197 | 198 | if not os.path.exists("detect_res"): 199 | os.makedirs("detect_res") 200 | save_name = os.path.join("detect_res", filename) 201 | #  Save image 202 | cv2.imwrite(save_name, image_raw) 203 | 204 | def destroy(self): 205 | # Remove any context from the top of the context stack, deactivating it. 206 | self.cfx.pop() 207 | 208 | def preprocess_image(self, input_image_path): 209 | """ 210 | description: Read an image from image path, convert it to RGB, 211 | resize and pad it to target size, normalize to [0,1], 212 | transform to NCHW format. 213 | param: 214 | input_image_path: str, image path 215 | return: 216 | image: the processed image 217 | image_raw: the original image 218 | h: original height 219 | w: original width 220 | """ 221 | image_raw = cv2.imread(input_image_path) # 1.opencv读入图片 222 | h, w, c = image_raw.shape 223 | 224 | # Calculate widht and height and paddings 225 | r_w = INPUT_W / w # INPUT_W=INPUT_H=640 # 4.计算宽高缩放的倍数 r_w,r_h 226 | r_h = INPUT_H / h 227 | if r_h > r_w: # 5.如果原图的高小于宽(长边),则长边缩放到640,短边按长边缩放比例缩放 228 | tw = INPUT_W 229 | th = int(r_w * h) 230 | 231 | dw = INPUT_W - tw 232 | dh = INPUT_H - th 233 | 234 | dw, dh = np.mod(dw,32),np.mod(dh,32) 235 | dw /= 2 # divide padding into 2 sides 236 | dh /= 2 237 | 238 | else: 239 | tw = int(r_h * w) 240 | th = INPUT_H 241 | 242 | dw = INPUT_W - tw 243 | dh = INPUT_H - th 244 | 245 | dw, dh = np.mod(dw,32),np.mod(dh,32) 246 | dw /= 2 # divide padding into 2 sides 247 | dh /= 2 248 | 249 | 250 | 251 | # Resize the image with long side while maintaining ratio 252 | image = cv2.resize(image_raw, (tw, th),interpolation=cv2.INTER_LINEAR) # 6.图像resize,按照cv2.INTER_LINEAR方法 253 | # Pad the short side with (128,128,128) 254 | 255 | top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1)) 256 | left, right = int(round(dw - 0.1)), int(round(dw + 0.1)) 257 | image = cv2.copyMakeBorder( 258 | # image, ty1, ty2, tx1, tx2, cv2.BORDER_CONSTANT, (128, 128, 128) 259 | image, top, bottom, left, right, cv2.BORDER_CONSTANT, (114, 114, 114) 260 | 261 | ) # image:图像, ty1, ty2.tx1,tx2: 相应方向上的边框宽度,添加的边界框像素值为常数,value填充的常数值 262 | 263 | image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # 3. BGR2RGB 264 | 265 | image = image.astype(np.float32) # 7.unit8-->float 266 | # Normalize to [0,1] 267 | image /= 255.0 # 8. 逐像素点除255.0 268 | # HWC to CHW format: 269 | image = np.transpose(image, [2, 0, 1]) # 9. HWC2CHW 270 | # CHW to NCHW format 271 | image = np.expand_dims(image, axis=0) # 10.CWH2NCHW 272 | # Convert the image to row-major order, also known as "C order": 273 | image = np.ascontiguousarray(image) # 11.ascontiguousarray函数将一个内存不连续存储的数组转换为内存连续存储的数组,使得运行速度更快 274 | return image, image_raw, h, w # 处理后的图像,原图, 原图的h,w 275 | 276 | def preprocess_image_0(self, input_image_path): 277 | """ 278 | description: Read an image from image path, convert it to RGB, 279 | resize and pad it to target size, normalize to [0,1], 280 | transform to NCHW format. 281 | param: 282 | input_image_path: str, image path 283 | return: 284 | image: the processed image 285 | image_raw: the original image 286 | h: original height 287 | w: original width 288 | """ 289 | image_raw = cv2.imread(input_image_path) # 1.opencv读入图片 290 | h, w, c = image_raw.shape # 2.记录图片大小 291 | image = cv2.cvtColor(image_raw, cv2.COLOR_BGR2RGB) # 3. BGR2RGB 292 | # Calculate widht and height and paddings 293 | r_w = INPUT_W / w # INPUT_W=INPUT_H=640 # 4.计算宽高缩放的倍数 r_w,r_h 294 | r_h = INPUT_H / h 295 | if r_h > r_w: # 5.如果原图的高小于宽(长边),则长边缩放到640,短边按长边缩放比例缩放 296 | tw = INPUT_W 297 | th = int(r_w * h) 298 | tx1 = tx2 = 0 299 | ty1 = int((INPUT_H - th) / 2) # ty1=(640-短边缩放的长度)/2 ,这部分是YOLOv5为加速推断而做的一个图像缩放算法 300 | ty2 = INPUT_H - th - ty1 # ty2=640-短边缩放的长度-ty1 301 | else: 302 | tw = int(r_h * w) 303 | th = INPUT_H 304 | tx1 = int((INPUT_W - tw) / 2) 305 | tx2 = INPUT_W - tw - tx1 306 | ty1 = ty2 = 0 307 | # Resize the image with long side while maintaining ratio 308 | image = cv2.resize(image, (tw, th),interpolation=cv2.INTER_LINEAR) # 6.图像resize,按照cv2.INTER_LINEAR方法 309 | # Pad the short side with (128,128,128) 310 | image = cv2.copyMakeBorder( 311 | # image, ty1, ty2, tx1, tx2, cv2.BORDER_CONSTANT, (128, 128, 128) 312 | image, ty1, ty2, tx1, tx2, cv2.BORDER_CONSTANT, (114, 114, 114) 313 | 314 | ) # image:图像, ty1, ty2.tx1,tx2: 相应方向上的边框宽度,添加的边界框像素值为常数,value填充的常数值 315 | image = image.astype(np.float32) # 7.unit8-->float 316 | # Normalize to [0,1] 317 | image /= 255.0 # 8. 逐像素点除255.0 318 | # HWC to CHW format: 319 | image = np.transpose(image, [2, 0, 1]) # 9. HWC2CHW 320 | # CHW to NCHW format 321 | image = np.expand_dims(image, axis=0) # 10.CWH2NCHW 322 | # Convert the image to row-major order, also known as "C order": 323 | image = np.ascontiguousarray(image) # 11.ascontiguousarray函数将一个内存不连续存储的数组转换为内存连续存储的数组,使得运行速度更快 324 | return image, image_raw, h, w # 处理后的图像,原图, 原图的h,w 325 | 326 | def xywh2xyxy(self, origin_h, origin_w, x): 327 | """ 328 | description: Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right 329 | param: 330 | origin_h: height of original image 331 | origin_w: width of original image 332 | x: A boxes tensor, each row is a box [center_x, center_y, w, h] 333 | return: 334 | y: A boxes tensor, each row is a box [x1, y1, x2, y2] 335 | """ 336 | y = torch.zeros_like(x) if isinstance(x, torch.Tensor) else np.zeros_like(x) 337 | r_w = INPUT_W / origin_w 338 | r_h = INPUT_H / origin_h 339 | if r_h > r_w: 340 | y[:, 0] = x[:, 0] - x[:, 2] / 2 #x1 341 | y[:, 2] = x[:, 0] + x[:, 2] / 2 #x2 342 | y[:, 1] = x[:, 1] - x[:, 3] / 2 - (INPUT_H - r_w * origin_h) / 2 # y1 343 | y[:, 3] = x[:, 1] + x[:, 3] / 2 - (INPUT_H - r_w * origin_h) / 2 # y2 344 | y /= r_w 345 | else: 346 | y[:, 0] = x[:, 0] - x[:, 2] / 2 - (INPUT_W - r_h * origin_w) / 2 347 | y[:, 2] = x[:, 0] + x[:, 2] / 2 - (INPUT_W - r_h * origin_w) / 2 348 | y[:, 1] = x[:, 1] - x[:, 3] / 2 349 | y[:, 3] = x[:, 1] + x[:, 3] / 2 350 | y /= r_h 351 | 352 | return y 353 | 354 | def post_process(self, output, origin_h, origin_w): 355 | """ 356 | description: postprocess the prediction 357 | param: 358 | output: A tensor likes [num_boxes,cx,cy,w,h,conf,cls_id, cx,cy,w,h,conf,cls_id, ...] 359 | origin_h: height of original image 360 | origin_w: width of original image 361 | return: 362 | result_boxes: finally boxes, a boxes tensor, each row is a box [x1, y1, x2, y2] 363 | result_scores: finally scores, a tensor, each element is the score correspoing to box 364 | result_classid: finally classid, a tensor, each element is the classid correspoing to box 365 | """ 366 | # Get the num of boxes detected 367 | num = int(output[0]) # detect的box的个数 368 | # Reshape to a two dimentional ndarray 369 | pred = np.reshape(output[1:], (-1, 6))[:num, :] #[[cx,cy,w,h,conf,cls_id],[cx,cy,w,h,conf,cls_id],...] 370 | # to a torch Tensor 371 | pred = torch.Tensor(pred).cuda() 372 | # Get the boxes 373 | boxes = pred[:, :4] # [[cx,cy,w,h],[cx,cy,w,h],...] 374 | # Get the scores 375 | scores = pred[:, 4] #[conf,conf,....] 376 | # Get the classid 377 | classid = pred[:, 5] # [cls_id,cls_id,...] 378 | # Choose those boxes that score > CONF_THRESH 379 | si = scores > CONF_THRESH 380 | boxes = boxes[si, :] 381 | scores = scores[si] 382 | classid = classid[si] 383 | # Trandform bbox from [center_x, center_y, w, h] to [x1, y1, x2, y2] 384 | boxes = self.xywh2xyxy(origin_h, origin_w, boxes) 385 | # Do nms 386 | indices = torchvision.ops.nms(boxes, scores, iou_threshold=IOU_THRESHOLD).cpu() # NMS 387 | result_boxes = boxes[indices, :].cpu() 388 | result_scores = scores[indices].cpu() 389 | result_classid = classid[indices].cpu() 390 | return result_boxes, result_scores, result_classid 391 | 392 | 393 | class myThread(threading.Thread): 394 | def __init__(self, func, args): 395 | threading.Thread.__init__(self) 396 | self.func = func 397 | self.args = args 398 | 399 | def run(self): 400 | self.func(*self.args) 401 | 402 | 403 | if __name__ == "__main__": 404 | 405 | # load custom plugins 406 | PLUGIN_LIBRARY = "build/libmyplugins.so" 407 | ctypes.CDLL(PLUGIN_LIBRARY) 408 | 409 | engine_file_path = "build/yolov5x.engine" 410 | 411 | # a YoLov5TRT instance 412 | yolov5_wrapper = YoLov5TRT(engine_file_path) 413 | 414 | # from https://github.com/ultralytics/yolov5/tree/master/inference/images 415 | 416 | files = os.listdir('test') 417 | input_image_paths = [os.path.join('test',file) for file in files] 418 | 419 | for input_image_path in input_image_paths: 420 | # create a new thread to do inference 421 | thread1 = myThread(yolov5_wrapper.infer, [input_image_path]) 422 | thread1.start() 423 | thread1.join() 424 | 425 | # destroy the instance 426 | yolov5_wrapper.destroy() 427 | --------------------------------------------------------------------------------