├── .github ├── ISSUE_TEMPLATE │ ├── 1_bug_report.md │ ├── 2_need_help.md │ └── 3_feature_request.md ├── dependabot.yml ├── pull_request_template.md └── workflows │ └── main.yml ├── .gitignore ├── LICENSE ├── README.md ├── assets ├── dog.png ├── giraffe.png ├── messi.png └── traffic.png ├── config ├── coco.data ├── create_custom_model.sh ├── custom.data ├── yolov3-tiny.cfg └── yolov3.cfg ├── data ├── coco.names ├── custom │ ├── classes.names │ ├── images │ │ └── train.jpg │ ├── labels │ │ └── train.txt │ ├── train.txt │ └── valid.txt ├── get_coco_dataset.sh └── samples │ ├── dog.jpg │ ├── eagle.jpg │ ├── field.jpg │ ├── giraffe.jpg │ ├── herd_of_horses.jpg │ ├── messi.jpg │ ├── person.jpg │ ├── room.jpg │ └── street.jpg ├── poetry.lock ├── pyproject.toml ├── pytorchyolo ├── __init__.py ├── detect.py ├── models.py ├── test.py ├── train.py └── utils │ ├── __init__.py │ ├── augmentations.py │ ├── datasets.py │ ├── logger.py │ ├── loss.py │ ├── parse_config.py │ ├── transforms.py │ └── utils.py └── weights └── download_weights.sh /.github/ISSUE_TEMPLATE/1_bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: "\U0001F41B Bug report" 3 | about: Report a bug, crash or some misbehavior 4 | title: '' 5 | labels: 'bug' 6 | assignees: '' 7 | --- 8 | 9 | 10 | ## Context 11 | 12 | - [ ] I have installed this repo manually and the issue occurred on this commit: 13 | 14 | - [ ] I have installed this repo via `PIP` and the issue occurred on version: 15 | - [ ] The issue occurred when using the following .cfg model: 16 | - [ ] `yolov3` 17 | - [ ] `yolov3-tiny` 18 | - [ ] `CUSTOM` 19 | 20 | ## Necessary Checks 21 | 22 | - [ ] The issue occurred on the newest version 23 | 24 | 25 | - [ ] I couldn't find a similar issue here on this project's github repo 26 | - [ ] If the issue is CUDA related (CUDA error), I have tested and provided the traceback also when CUDA is turned off 27 | - [ ] I have provided all tracebacks or printouts in ```Text Form``` 28 | - [ ] In case, the issue occurred on a custom .cfg model, I have provided the model down below 29 | 30 | ## Expected behavior 31 | 32 | 33 | ## Current behavior 34 | 35 | 36 | ## Steps to Reproduce 37 | 38 | 39 | 1. 40 | 2. 41 | 3. 42 | ... 43 | 44 | ## Possible Solution 45 | 46 | 47 | 48 | ### Custom `.cfg` 49 | 50 |
Custom .cfg 51 |

52 | 53 |

54 |
55 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/2_need_help.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: "⁉️ Need help?" 3 | about: "Get help with using or improving our software" 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | --- 8 | 9 | ## What I'm trying to do 10 | 11 | 12 | ## What I've tried 13 | 14 | 15 | ## Additional context 16 | 17 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/3_feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: "\U0001F680 Feature request" 3 | about: Suggest an idea for this project 4 | labels: 'enhancement' 5 | --- 6 | 7 | 12 | 13 | ## Is your feature request related to a problem? Please describe. 14 | 15 | 16 | ## Describe the solution you'd like 17 | 18 | 19 | ## Describe alternatives you've considered 20 | 21 | 22 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "pip" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "daily" 12 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | ## Proposed changes 2 | 3 | 4 | ## Related issues 5 | 6 | 7 | 8 | 9 | ## Necessary checks 10 | - [ ] Update poetry package version [semantically](https://semver.org/) 11 | - [ ] Write documentation 12 | - [ ] Create issues for future work 13 | - [ ] Test on your machine 14 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: [pull_request, workflow_dispatch] 4 | 5 | jobs: 6 | main: 7 | runs-on: ${{ matrix.os }} 8 | strategy: 9 | matrix: 10 | os: [ubuntu-22.04, ubuntu-20.04, windows-latest] 11 | steps: 12 | - uses: actions/checkout@v2 13 | 14 | - name: Set up Python 15 | uses: actions/setup-python@v1 16 | with: 17 | python-version: 3.8 18 | 19 | - name: Upgrade pip 20 | run: python3 -m pip install --upgrade pip 21 | 22 | - name: Install Poetry 23 | run: pip3 install poetry --user 24 | 25 | - name: Install Dependencies 26 | run: poetry install 27 | 28 | # Prints the help pages of all scripts to see if the imports etc. work 29 | - name: Test the help pages 30 | run: | 31 | poetry run yolo-train -h 32 | poetry run yolo-test -h 33 | poetry run yolo-detect -h 34 | 35 | - name: Demo Training 36 | run: poetry run yolo-train --data config/custom.data --model config/yolov3.cfg --epochs 30 37 | 38 | - name: Demo Evaluate 39 | run: poetry run yolo-test --data config/custom.data --model config/yolov3.cfg --weights checkpoints/yolov3_ckpt_29.pth 40 | 41 | - name: Demo Detect 42 | run: poetry run yolo-detect --batch_size 2 --weights checkpoints/yolov3_ckpt_29.pth 43 | 44 | linter: 45 | runs-on: ubuntu-latest 46 | steps: 47 | - uses: actions/checkout@v2 48 | 49 | - name: Flake8 50 | uses: TrueBrain/actions-flake8@master 51 | with: 52 | only_warn: 1 53 | max_line_length: 150 54 | path: pytorchyolo 55 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | .DS_Store 3 | build 4 | .git 5 | *.egg-info 6 | dist 7 | output/ 8 | data/* 9 | backup 10 | weights/*.weights 11 | weights/*.conv.* 12 | __pycache__ 13 | checkpoints/ 14 | 15 | .vscode/ 16 | logs/ 17 | 18 | .python-version 19 | -------------------------------------------------------------------------------- /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 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PyTorch YOLO 2 | A minimal PyTorch implementation of YOLOv3, with support for training, inference and evaluation. 3 | 4 | YOLOv4 and YOLOv7 weights are also compatible with this implementation. 5 | 6 | [![CI](https://github.com/eriklindernoren/PyTorch-YOLOv3/actions/workflows/main.yml/badge.svg)](https://github.com/eriklindernoren/PyTorch-YOLOv3/actions/workflows/main.yml) [![PyPI pyversions](https://img.shields.io/pypi/pyversions/pytorchyolo.svg)](https://pypi.python.org/pypi/pytorchyolo/) [![PyPI license](https://img.shields.io/pypi/l/pytorchyolo.svg)](LICENSE) 7 | 8 | ## Installation 9 | ### Installing from source 10 | 11 | For normal training and evaluation we recommend installing the package from source using a poetry virtual environment. 12 | 13 | ```bash 14 | git clone https://github.com/eriklindernoren/PyTorch-YOLOv3 15 | cd PyTorch-YOLOv3/ 16 | pip3 install poetry --user 17 | poetry install 18 | ``` 19 | 20 | You need to join the virtual environment by running `poetry shell` in this directory before running any of the following commands without the `poetry run` prefix. 21 | Also have a look at the other installing method, if you want to use the commands everywhere without opening a poetry-shell. 22 | 23 | #### Download pretrained weights 24 | 25 | ```bash 26 | ./weights/download_weights.sh 27 | ``` 28 | 29 | #### Download COCO 30 | 31 | ```bash 32 | ./data/get_coco_dataset.sh 33 | ``` 34 | 35 | ### Install via pip 36 | 37 | This installation method is recommended, if you want to use this package as a dependency in another python project. 38 | This method only includes the code, is less isolated and may conflict with other packages. 39 | Weights and the COCO dataset need to be downloaded as stated above. 40 | See __API__ for further information regarding the packages API. 41 | It also enables the CLI tools `yolo-detect`, `yolo-train`, and `yolo-test` everywhere without any additional commands. 42 | 43 | ```bash 44 | pip3 install pytorchyolo --user 45 | ``` 46 | 47 | ## Test 48 | Evaluates the model on COCO test dataset. 49 | To download this dataset as well as weights, see above. 50 | 51 | ```bash 52 | poetry run yolo-test --weights weights/yolov3.weights 53 | ``` 54 | 55 | | Model | mAP (min. 50 IoU) | 56 | | ----------------------- |:-----------------:| 57 | | YOLOv3 608 (paper) | 57.9 | 58 | | YOLOv3 608 (this impl.) | 57.3 | 59 | | YOLOv3 416 (paper) | 55.3 | 60 | | YOLOv3 416 (this impl.) | 55.5 | 61 | 62 | ## Inference 63 | Uses pretrained weights to make predictions on images. Below table displays the inference times when using as inputs images scaled to 256x256. The ResNet backbone measurements are taken from the YOLOv3 paper. The Darknet-53 measurement marked shows the inference time of this implementation on my 1080ti card. 64 | 65 | | Backbone | GPU | FPS | 66 | | ----------------------- |:--------:|:--------:| 67 | | ResNet-101 | Titan X | 53 | 68 | | ResNet-152 | Titan X | 37 | 69 | | Darknet-53 (paper) | Titan X | 76 | 70 | | Darknet-53 (this impl.) | 1080ti | 74 | 71 | 72 | ```bash 73 | poetry run yolo-detect --images data/samples/ 74 | ``` 75 | 76 |

77 |

78 |

79 |

80 | 81 | ## Train 82 | For argument descriptions have a look at `poetry run yolo-train --help` 83 | 84 | #### Example (COCO) 85 | To train on COCO using a Darknet-53 backend pretrained on ImageNet run: 86 | 87 | ```bash 88 | poetry run yolo-train --data config/coco.data --pretrained_weights weights/darknet53.conv.74 89 | ``` 90 | 91 | #### Tensorboard 92 | Track training progress in Tensorboard: 93 | * Initialize training 94 | * Run the command below 95 | * Go to http://localhost:6006/ 96 | 97 | ```bash 98 | poetry run tensorboard --logdir='logs' --port=6006 99 | ``` 100 | 101 | Storing the logs on a slow drive possibly leads to a significant training speed decrease. 102 | 103 | You can adjust the log directory using `--logdir ` when running `tensorboard` and `yolo-train`. 104 | 105 | ## Train on Custom Dataset 106 | 107 | #### Custom model 108 | Run the commands below to create a custom model definition, replacing `` with the number of classes in your dataset. 109 | 110 | ```bash 111 | cd config 112 | ./create_custom_model.sh # Will create custom model 'yolov3-custom.cfg' 113 | ``` 114 | 115 | #### Classes 116 | Add class names to `data/custom/classes.names`. This file should have one row per class name. 117 | 118 | #### Image Folder 119 | Move the images of your dataset to `data/custom/images/`. 120 | 121 | #### Annotation Folder 122 | Move your annotations to `data/custom/labels/`. The dataloader expects that the annotation file corresponding to the image `data/custom/images/train.jpg` has the path `data/custom/labels/train.txt`. Each row in the annotation file should define one bounding box, using the syntax `label_idx x_center y_center width height`. The coordinates should be scaled `[0, 1]`, and the `label_idx` should be zero-indexed and correspond to the row number of the class name in `data/custom/classes.names`. 123 | 124 | #### Define Train and Validation Sets 125 | In `data/custom/train.txt` and `data/custom/valid.txt`, add paths to images that will be used as train and validation data respectively. 126 | 127 | #### Train 128 | To train on the custom dataset run: 129 | 130 | ```bash 131 | poetry run yolo-train --model config/yolov3-custom.cfg --data config/custom.data 132 | ``` 133 | 134 | Add `--pretrained_weights weights/darknet53.conv.74` to train using a backend pretrained on ImageNet. 135 | 136 | 137 | ## API 138 | 139 | You are able to import the modules of this repo in your own project if you install the pip package `pytorchyolo`. 140 | 141 | An example prediction call from a simple OpenCV python script would look like this: 142 | 143 | ```python 144 | import cv2 145 | from pytorchyolo import detect, models 146 | 147 | # Load the YOLO model 148 | model = models.load_model( 149 | "/yolov3.cfg", 150 | "/yolov3.weights") 151 | 152 | # Load the image as a numpy array 153 | img = cv2.imread("") 154 | 155 | # Convert OpenCV bgr to rgb 156 | img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 157 | 158 | # Runs the YOLO model on the image 159 | boxes = detect.detect_image(model, img) 160 | 161 | print(boxes) 162 | # Output will be a numpy array in the following format: 163 | # [[x1, y1, x2, y2, confidence, class]] 164 | ``` 165 | 166 | For more advanced usage look at the method's doc strings. 167 | 168 | ## Credit 169 | 170 | ### YOLOv3: An Incremental Improvement 171 | _Joseph Redmon, Ali Farhadi_
172 | 173 | **Abstract**
174 | We present some updates to YOLO! We made a bunch 175 | of little design changes to make it better. We also trained 176 | this new network that’s pretty swell. It’s a little bigger than 177 | last time but more accurate. It’s still fast though, don’t 178 | worry. At 320 × 320 YOLOv3 runs in 22 ms at 28.2 mAP, 179 | as accurate as SSD but three times faster. When we look 180 | at the old .5 IOU mAP detection metric YOLOv3 is quite 181 | good. It achieves 57.9 AP50 in 51 ms on a Titan X, compared 182 | to 57.5 AP50 in 198 ms by RetinaNet, similar performance 183 | but 3.8× faster. As always, all the code is online at 184 | https://pjreddie.com/yolo/. 185 | 186 | [[Paper]](https://pjreddie.com/media/files/papers/YOLOv3.pdf) [[Project Webpage]](https://pjreddie.com/darknet/yolo/) [[Authors' Implementation]](https://github.com/pjreddie/darknet) 187 | 188 | ``` 189 | @article{yolov3, 190 | title={YOLOv3: An Incremental Improvement}, 191 | author={Redmon, Joseph and Farhadi, Ali}, 192 | journal = {arXiv}, 193 | year={2018} 194 | } 195 | ``` 196 | 197 | ## Other 198 | 199 | ### YOEO — You Only Encode Once 200 | 201 | [YOEO](https://github.com/bit-bots/YOEO) extends this repo with the ability to train an additional semantic segmentation decoder. The lightweight example model is mainly targeted towards embedded real-time applications. 202 | -------------------------------------------------------------------------------- /assets/dog.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eriklindernoren/PyTorch-YOLOv3/1d621c8489e22c76ceb93bb2397ac6c8dfb5ceb7/assets/dog.png -------------------------------------------------------------------------------- /assets/giraffe.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eriklindernoren/PyTorch-YOLOv3/1d621c8489e22c76ceb93bb2397ac6c8dfb5ceb7/assets/giraffe.png -------------------------------------------------------------------------------- /assets/messi.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eriklindernoren/PyTorch-YOLOv3/1d621c8489e22c76ceb93bb2397ac6c8dfb5ceb7/assets/messi.png -------------------------------------------------------------------------------- /assets/traffic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eriklindernoren/PyTorch-YOLOv3/1d621c8489e22c76ceb93bb2397ac6c8dfb5ceb7/assets/traffic.png -------------------------------------------------------------------------------- /config/coco.data: -------------------------------------------------------------------------------- 1 | classes= 80 2 | train=data/coco/trainvalno5k.txt 3 | valid=data/coco/5k.txt 4 | names=data/coco.names 5 | backup=backup/ 6 | eval=coco 7 | -------------------------------------------------------------------------------- /config/create_custom_model.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | NUM_CLASSES=$1 4 | 5 | echo " 6 | [net] 7 | # Testing 8 | #batch=1 9 | #subdivisions=1 10 | # Training 11 | batch=16 12 | subdivisions=1 13 | width=416 14 | height=416 15 | channels=3 16 | momentum=0.9 17 | decay=0.0005 18 | angle=0 19 | saturation = 1.5 20 | exposure = 1.5 21 | hue=.1 22 | 23 | learning_rate=0.001 24 | burn_in=1000 25 | max_batches = 500200 26 | policy=steps 27 | steps=400000,450000 28 | scales=.1,.1 29 | 30 | [convolutional] 31 | batch_normalize=1 32 | filters=32 33 | size=3 34 | stride=1 35 | pad=1 36 | activation=leaky 37 | 38 | # Downsample 39 | 40 | [convolutional] 41 | batch_normalize=1 42 | filters=64 43 | size=3 44 | stride=2 45 | pad=1 46 | activation=leaky 47 | 48 | [convolutional] 49 | batch_normalize=1 50 | filters=32 51 | size=1 52 | stride=1 53 | pad=1 54 | activation=leaky 55 | 56 | [convolutional] 57 | batch_normalize=1 58 | filters=64 59 | size=3 60 | stride=1 61 | pad=1 62 | activation=leaky 63 | 64 | [shortcut] 65 | from=-3 66 | activation=linear 67 | 68 | # Downsample 69 | 70 | [convolutional] 71 | batch_normalize=1 72 | filters=128 73 | size=3 74 | stride=2 75 | pad=1 76 | activation=leaky 77 | 78 | [convolutional] 79 | batch_normalize=1 80 | filters=64 81 | size=1 82 | stride=1 83 | pad=1 84 | activation=leaky 85 | 86 | [convolutional] 87 | batch_normalize=1 88 | filters=128 89 | size=3 90 | stride=1 91 | pad=1 92 | activation=leaky 93 | 94 | [shortcut] 95 | from=-3 96 | activation=linear 97 | 98 | [convolutional] 99 | batch_normalize=1 100 | filters=64 101 | size=1 102 | stride=1 103 | pad=1 104 | activation=leaky 105 | 106 | [convolutional] 107 | batch_normalize=1 108 | filters=128 109 | size=3 110 | stride=1 111 | pad=1 112 | activation=leaky 113 | 114 | [shortcut] 115 | from=-3 116 | activation=linear 117 | 118 | # Downsample 119 | 120 | [convolutional] 121 | batch_normalize=1 122 | filters=256 123 | size=3 124 | stride=2 125 | pad=1 126 | activation=leaky 127 | 128 | [convolutional] 129 | batch_normalize=1 130 | filters=128 131 | size=1 132 | stride=1 133 | pad=1 134 | activation=leaky 135 | 136 | [convolutional] 137 | batch_normalize=1 138 | filters=256 139 | size=3 140 | stride=1 141 | pad=1 142 | activation=leaky 143 | 144 | [shortcut] 145 | from=-3 146 | activation=linear 147 | 148 | [convolutional] 149 | batch_normalize=1 150 | filters=128 151 | size=1 152 | stride=1 153 | pad=1 154 | activation=leaky 155 | 156 | [convolutional] 157 | batch_normalize=1 158 | filters=256 159 | size=3 160 | stride=1 161 | pad=1 162 | activation=leaky 163 | 164 | [shortcut] 165 | from=-3 166 | activation=linear 167 | 168 | [convolutional] 169 | batch_normalize=1 170 | filters=128 171 | size=1 172 | stride=1 173 | pad=1 174 | activation=leaky 175 | 176 | [convolutional] 177 | batch_normalize=1 178 | filters=256 179 | size=3 180 | stride=1 181 | pad=1 182 | activation=leaky 183 | 184 | [shortcut] 185 | from=-3 186 | activation=linear 187 | 188 | [convolutional] 189 | batch_normalize=1 190 | filters=128 191 | size=1 192 | stride=1 193 | pad=1 194 | activation=leaky 195 | 196 | [convolutional] 197 | batch_normalize=1 198 | filters=256 199 | size=3 200 | stride=1 201 | pad=1 202 | activation=leaky 203 | 204 | [shortcut] 205 | from=-3 206 | activation=linear 207 | 208 | 209 | [convolutional] 210 | batch_normalize=1 211 | filters=128 212 | size=1 213 | stride=1 214 | pad=1 215 | activation=leaky 216 | 217 | [convolutional] 218 | batch_normalize=1 219 | filters=256 220 | size=3 221 | stride=1 222 | pad=1 223 | activation=leaky 224 | 225 | [shortcut] 226 | from=-3 227 | activation=linear 228 | 229 | [convolutional] 230 | batch_normalize=1 231 | filters=128 232 | size=1 233 | stride=1 234 | pad=1 235 | activation=leaky 236 | 237 | [convolutional] 238 | batch_normalize=1 239 | filters=256 240 | size=3 241 | stride=1 242 | pad=1 243 | activation=leaky 244 | 245 | [shortcut] 246 | from=-3 247 | activation=linear 248 | 249 | [convolutional] 250 | batch_normalize=1 251 | filters=128 252 | size=1 253 | stride=1 254 | pad=1 255 | activation=leaky 256 | 257 | [convolutional] 258 | batch_normalize=1 259 | filters=256 260 | size=3 261 | stride=1 262 | pad=1 263 | activation=leaky 264 | 265 | [shortcut] 266 | from=-3 267 | activation=linear 268 | 269 | [convolutional] 270 | batch_normalize=1 271 | filters=128 272 | size=1 273 | stride=1 274 | pad=1 275 | activation=leaky 276 | 277 | [convolutional] 278 | batch_normalize=1 279 | filters=256 280 | size=3 281 | stride=1 282 | pad=1 283 | activation=leaky 284 | 285 | [shortcut] 286 | from=-3 287 | activation=linear 288 | 289 | # Downsample 290 | 291 | [convolutional] 292 | batch_normalize=1 293 | filters=512 294 | size=3 295 | stride=2 296 | pad=1 297 | activation=leaky 298 | 299 | [convolutional] 300 | batch_normalize=1 301 | filters=256 302 | size=1 303 | stride=1 304 | pad=1 305 | activation=leaky 306 | 307 | [convolutional] 308 | batch_normalize=1 309 | filters=512 310 | size=3 311 | stride=1 312 | pad=1 313 | activation=leaky 314 | 315 | [shortcut] 316 | from=-3 317 | activation=linear 318 | 319 | 320 | [convolutional] 321 | batch_normalize=1 322 | filters=256 323 | size=1 324 | stride=1 325 | pad=1 326 | activation=leaky 327 | 328 | [convolutional] 329 | batch_normalize=1 330 | filters=512 331 | size=3 332 | stride=1 333 | pad=1 334 | activation=leaky 335 | 336 | [shortcut] 337 | from=-3 338 | activation=linear 339 | 340 | 341 | [convolutional] 342 | batch_normalize=1 343 | filters=256 344 | size=1 345 | stride=1 346 | pad=1 347 | activation=leaky 348 | 349 | [convolutional] 350 | batch_normalize=1 351 | filters=512 352 | size=3 353 | stride=1 354 | pad=1 355 | activation=leaky 356 | 357 | [shortcut] 358 | from=-3 359 | activation=linear 360 | 361 | 362 | [convolutional] 363 | batch_normalize=1 364 | filters=256 365 | size=1 366 | stride=1 367 | pad=1 368 | activation=leaky 369 | 370 | [convolutional] 371 | batch_normalize=1 372 | filters=512 373 | size=3 374 | stride=1 375 | pad=1 376 | activation=leaky 377 | 378 | [shortcut] 379 | from=-3 380 | activation=linear 381 | 382 | [convolutional] 383 | batch_normalize=1 384 | filters=256 385 | size=1 386 | stride=1 387 | pad=1 388 | activation=leaky 389 | 390 | [convolutional] 391 | batch_normalize=1 392 | filters=512 393 | size=3 394 | stride=1 395 | pad=1 396 | activation=leaky 397 | 398 | [shortcut] 399 | from=-3 400 | activation=linear 401 | 402 | 403 | [convolutional] 404 | batch_normalize=1 405 | filters=256 406 | size=1 407 | stride=1 408 | pad=1 409 | activation=leaky 410 | 411 | [convolutional] 412 | batch_normalize=1 413 | filters=512 414 | size=3 415 | stride=1 416 | pad=1 417 | activation=leaky 418 | 419 | [shortcut] 420 | from=-3 421 | activation=linear 422 | 423 | 424 | [convolutional] 425 | batch_normalize=1 426 | filters=256 427 | size=1 428 | stride=1 429 | pad=1 430 | activation=leaky 431 | 432 | [convolutional] 433 | batch_normalize=1 434 | filters=512 435 | size=3 436 | stride=1 437 | pad=1 438 | activation=leaky 439 | 440 | [shortcut] 441 | from=-3 442 | activation=linear 443 | 444 | [convolutional] 445 | batch_normalize=1 446 | filters=256 447 | size=1 448 | stride=1 449 | pad=1 450 | activation=leaky 451 | 452 | [convolutional] 453 | batch_normalize=1 454 | filters=512 455 | size=3 456 | stride=1 457 | pad=1 458 | activation=leaky 459 | 460 | [shortcut] 461 | from=-3 462 | activation=linear 463 | 464 | # Downsample 465 | 466 | [convolutional] 467 | batch_normalize=1 468 | filters=1024 469 | size=3 470 | stride=2 471 | pad=1 472 | activation=leaky 473 | 474 | [convolutional] 475 | batch_normalize=1 476 | filters=512 477 | size=1 478 | stride=1 479 | pad=1 480 | activation=leaky 481 | 482 | [convolutional] 483 | batch_normalize=1 484 | filters=1024 485 | size=3 486 | stride=1 487 | pad=1 488 | activation=leaky 489 | 490 | [shortcut] 491 | from=-3 492 | activation=linear 493 | 494 | [convolutional] 495 | batch_normalize=1 496 | filters=512 497 | size=1 498 | stride=1 499 | pad=1 500 | activation=leaky 501 | 502 | [convolutional] 503 | batch_normalize=1 504 | filters=1024 505 | size=3 506 | stride=1 507 | pad=1 508 | activation=leaky 509 | 510 | [shortcut] 511 | from=-3 512 | activation=linear 513 | 514 | [convolutional] 515 | batch_normalize=1 516 | filters=512 517 | size=1 518 | stride=1 519 | pad=1 520 | activation=leaky 521 | 522 | [convolutional] 523 | batch_normalize=1 524 | filters=1024 525 | size=3 526 | stride=1 527 | pad=1 528 | activation=leaky 529 | 530 | [shortcut] 531 | from=-3 532 | activation=linear 533 | 534 | [convolutional] 535 | batch_normalize=1 536 | filters=512 537 | size=1 538 | stride=1 539 | pad=1 540 | activation=leaky 541 | 542 | [convolutional] 543 | batch_normalize=1 544 | filters=1024 545 | size=3 546 | stride=1 547 | pad=1 548 | activation=leaky 549 | 550 | [shortcut] 551 | from=-3 552 | activation=linear 553 | 554 | ###################### 555 | 556 | [convolutional] 557 | batch_normalize=1 558 | filters=512 559 | size=1 560 | stride=1 561 | pad=1 562 | activation=leaky 563 | 564 | [convolutional] 565 | batch_normalize=1 566 | size=3 567 | stride=1 568 | pad=1 569 | filters=1024 570 | activation=leaky 571 | 572 | [convolutional] 573 | batch_normalize=1 574 | filters=512 575 | size=1 576 | stride=1 577 | pad=1 578 | activation=leaky 579 | 580 | [convolutional] 581 | batch_normalize=1 582 | size=3 583 | stride=1 584 | pad=1 585 | filters=1024 586 | activation=leaky 587 | 588 | [convolutional] 589 | batch_normalize=1 590 | filters=512 591 | size=1 592 | stride=1 593 | pad=1 594 | activation=leaky 595 | 596 | [convolutional] 597 | batch_normalize=1 598 | size=3 599 | stride=1 600 | pad=1 601 | filters=1024 602 | activation=leaky 603 | 604 | [convolutional] 605 | size=1 606 | stride=1 607 | pad=1 608 | filters=$(expr 3 \* $(expr $NUM_CLASSES \+ 5)) 609 | activation=linear 610 | 611 | 612 | [yolo] 613 | mask = 6,7,8 614 | anchors = 10,13, 16,30, 33,23, 30,61, 62,45, 59,119, 116,90, 156,198, 373,326 615 | classes=$NUM_CLASSES 616 | num=9 617 | jitter=.3 618 | ignore_thresh = .7 619 | truth_thresh = 1 620 | random=1 621 | 622 | 623 | [route] 624 | layers = -4 625 | 626 | [convolutional] 627 | batch_normalize=1 628 | filters=256 629 | size=1 630 | stride=1 631 | pad=1 632 | activation=leaky 633 | 634 | [upsample] 635 | stride=2 636 | 637 | [route] 638 | layers = -1, 61 639 | 640 | 641 | 642 | [convolutional] 643 | batch_normalize=1 644 | filters=256 645 | size=1 646 | stride=1 647 | pad=1 648 | activation=leaky 649 | 650 | [convolutional] 651 | batch_normalize=1 652 | size=3 653 | stride=1 654 | pad=1 655 | filters=512 656 | activation=leaky 657 | 658 | [convolutional] 659 | batch_normalize=1 660 | filters=256 661 | size=1 662 | stride=1 663 | pad=1 664 | activation=leaky 665 | 666 | [convolutional] 667 | batch_normalize=1 668 | size=3 669 | stride=1 670 | pad=1 671 | filters=512 672 | activation=leaky 673 | 674 | [convolutional] 675 | batch_normalize=1 676 | filters=256 677 | size=1 678 | stride=1 679 | pad=1 680 | activation=leaky 681 | 682 | [convolutional] 683 | batch_normalize=1 684 | size=3 685 | stride=1 686 | pad=1 687 | filters=512 688 | activation=leaky 689 | 690 | [convolutional] 691 | size=1 692 | stride=1 693 | pad=1 694 | filters=$(expr 3 \* $(expr $NUM_CLASSES \+ 5)) 695 | activation=linear 696 | 697 | 698 | [yolo] 699 | mask = 3,4,5 700 | anchors = 10,13, 16,30, 33,23, 30,61, 62,45, 59,119, 116,90, 156,198, 373,326 701 | classes=$NUM_CLASSES 702 | num=9 703 | jitter=.3 704 | ignore_thresh = .7 705 | truth_thresh = 1 706 | random=1 707 | 708 | 709 | 710 | [route] 711 | layers = -4 712 | 713 | [convolutional] 714 | batch_normalize=1 715 | filters=128 716 | size=1 717 | stride=1 718 | pad=1 719 | activation=leaky 720 | 721 | [upsample] 722 | stride=2 723 | 724 | [route] 725 | layers = -1, 36 726 | 727 | 728 | 729 | [convolutional] 730 | batch_normalize=1 731 | filters=128 732 | size=1 733 | stride=1 734 | pad=1 735 | activation=leaky 736 | 737 | [convolutional] 738 | batch_normalize=1 739 | size=3 740 | stride=1 741 | pad=1 742 | filters=256 743 | activation=leaky 744 | 745 | [convolutional] 746 | batch_normalize=1 747 | filters=128 748 | size=1 749 | stride=1 750 | pad=1 751 | activation=leaky 752 | 753 | [convolutional] 754 | batch_normalize=1 755 | size=3 756 | stride=1 757 | pad=1 758 | filters=256 759 | activation=leaky 760 | 761 | [convolutional] 762 | batch_normalize=1 763 | filters=128 764 | size=1 765 | stride=1 766 | pad=1 767 | activation=leaky 768 | 769 | [convolutional] 770 | batch_normalize=1 771 | size=3 772 | stride=1 773 | pad=1 774 | filters=256 775 | activation=leaky 776 | 777 | [convolutional] 778 | size=1 779 | stride=1 780 | pad=1 781 | filters=$(expr 3 \* $(expr $NUM_CLASSES \+ 5)) 782 | activation=linear 783 | 784 | 785 | [yolo] 786 | mask = 0,1,2 787 | anchors = 10,13, 16,30, 33,23, 30,61, 62,45, 59,119, 116,90, 156,198, 373,326 788 | classes=$NUM_CLASSES 789 | num=9 790 | jitter=.3 791 | ignore_thresh = .7 792 | truth_thresh = 1 793 | random=1 794 | " >> yolov3-custom.cfg 795 | -------------------------------------------------------------------------------- /config/custom.data: -------------------------------------------------------------------------------- 1 | classes= 1 2 | train=data/custom/train.txt 3 | valid=data/custom/valid.txt 4 | names=data/custom/classes.names 5 | -------------------------------------------------------------------------------- /config/yolov3-tiny.cfg: -------------------------------------------------------------------------------- 1 | [net] 2 | # Testing 3 | #batch=1 4 | #subdivisions=1 5 | # Training 6 | batch=64 7 | subdivisions=2 8 | width=416 9 | height=416 10 | channels=3 11 | momentum=0.9 12 | decay=0.0005 13 | angle=0 14 | saturation = 1.5 15 | exposure = 1.5 16 | hue=.1 17 | 18 | learning_rate=0.0001 19 | burn_in=1000 20 | max_batches = 500200 21 | policy=steps 22 | steps=400000,450000 23 | scales=.1,.1 24 | 25 | # 0 26 | [convolutional] 27 | batch_normalize=1 28 | filters=16 29 | size=3 30 | stride=1 31 | pad=1 32 | activation=leaky 33 | 34 | # 1 35 | [maxpool] 36 | size=2 37 | stride=2 38 | 39 | # 2 40 | [convolutional] 41 | batch_normalize=1 42 | filters=32 43 | size=3 44 | stride=1 45 | pad=1 46 | activation=leaky 47 | 48 | # 3 49 | [maxpool] 50 | size=2 51 | stride=2 52 | 53 | # 4 54 | [convolutional] 55 | batch_normalize=1 56 | filters=64 57 | size=3 58 | stride=1 59 | pad=1 60 | activation=leaky 61 | 62 | # 5 63 | [maxpool] 64 | size=2 65 | stride=2 66 | 67 | # 6 68 | [convolutional] 69 | batch_normalize=1 70 | filters=128 71 | size=3 72 | stride=1 73 | pad=1 74 | activation=leaky 75 | 76 | # 7 77 | [maxpool] 78 | size=2 79 | stride=2 80 | 81 | # 8 82 | [convolutional] 83 | batch_normalize=1 84 | filters=256 85 | size=3 86 | stride=1 87 | pad=1 88 | activation=leaky 89 | 90 | # 9 91 | [maxpool] 92 | size=2 93 | stride=2 94 | 95 | # 10 96 | [convolutional] 97 | batch_normalize=1 98 | filters=512 99 | size=3 100 | stride=1 101 | pad=1 102 | activation=leaky 103 | 104 | # 11 105 | [maxpool] 106 | size=2 107 | stride=1 108 | 109 | # 12 110 | [convolutional] 111 | batch_normalize=1 112 | filters=1024 113 | size=3 114 | stride=1 115 | pad=1 116 | activation=leaky 117 | 118 | ########### 119 | 120 | # 13 121 | [convolutional] 122 | batch_normalize=1 123 | filters=256 124 | size=1 125 | stride=1 126 | pad=1 127 | activation=leaky 128 | 129 | # 14 130 | [convolutional] 131 | batch_normalize=1 132 | filters=512 133 | size=3 134 | stride=1 135 | pad=1 136 | activation=leaky 137 | 138 | # 15 139 | [convolutional] 140 | size=1 141 | stride=1 142 | pad=1 143 | filters=255 144 | activation=linear 145 | 146 | 147 | 148 | # 16 149 | [yolo] 150 | mask = 3,4,5 151 | anchors = 10,14, 23,27, 37,58, 81,82, 135,169, 344,319 152 | classes=80 153 | num=6 154 | jitter=.3 155 | ignore_thresh = .7 156 | truth_thresh = 1 157 | random=1 158 | 159 | # 17 160 | [route] 161 | layers = -4 162 | 163 | # 18 164 | [convolutional] 165 | batch_normalize=1 166 | filters=128 167 | size=1 168 | stride=1 169 | pad=1 170 | activation=leaky 171 | 172 | # 19 173 | [upsample] 174 | stride=2 175 | 176 | # 20 177 | [route] 178 | layers = -1, 8 179 | 180 | # 21 181 | [convolutional] 182 | batch_normalize=1 183 | filters=256 184 | size=3 185 | stride=1 186 | pad=1 187 | activation=leaky 188 | 189 | # 22 190 | [convolutional] 191 | size=1 192 | stride=1 193 | pad=1 194 | filters=255 195 | activation=linear 196 | 197 | # 23 198 | [yolo] 199 | mask = 1,2,3 200 | anchors = 10,14, 23,27, 37,58, 81,82, 135,169, 344,319 201 | classes=80 202 | num=6 203 | jitter=.3 204 | ignore_thresh = .7 205 | truth_thresh = 1 206 | random=1 207 | -------------------------------------------------------------------------------- /config/yolov3.cfg: -------------------------------------------------------------------------------- 1 | [net] 2 | # Testing 3 | #batch=1 4 | #subdivisions=1 5 | # Training 6 | batch=16 7 | subdivisions=1 8 | width=416 9 | height=416 10 | channels=3 11 | momentum=0.9 12 | decay=0.0005 13 | angle=0 14 | saturation = 1.5 15 | exposure = 1.5 16 | hue=.1 17 | 18 | learning_rate=0.0001 19 | burn_in=1000 20 | max_batches = 500200 21 | policy=steps 22 | steps=400000,450000 23 | scales=.1,.1 24 | 25 | [convolutional] 26 | batch_normalize=1 27 | filters=32 28 | size=3 29 | stride=1 30 | pad=1 31 | activation=leaky 32 | 33 | # Downsample 34 | 35 | [convolutional] 36 | batch_normalize=1 37 | filters=64 38 | size=3 39 | stride=2 40 | pad=1 41 | activation=leaky 42 | 43 | [convolutional] 44 | batch_normalize=1 45 | filters=32 46 | size=1 47 | stride=1 48 | pad=1 49 | activation=leaky 50 | 51 | [convolutional] 52 | batch_normalize=1 53 | filters=64 54 | size=3 55 | stride=1 56 | pad=1 57 | activation=leaky 58 | 59 | [shortcut] 60 | from=-3 61 | activation=linear 62 | 63 | # Downsample 64 | 65 | [convolutional] 66 | batch_normalize=1 67 | filters=128 68 | size=3 69 | stride=2 70 | pad=1 71 | activation=leaky 72 | 73 | [convolutional] 74 | batch_normalize=1 75 | filters=64 76 | size=1 77 | stride=1 78 | pad=1 79 | activation=leaky 80 | 81 | [convolutional] 82 | batch_normalize=1 83 | filters=128 84 | size=3 85 | stride=1 86 | pad=1 87 | activation=leaky 88 | 89 | [shortcut] 90 | from=-3 91 | activation=linear 92 | 93 | [convolutional] 94 | batch_normalize=1 95 | filters=64 96 | size=1 97 | stride=1 98 | pad=1 99 | activation=leaky 100 | 101 | [convolutional] 102 | batch_normalize=1 103 | filters=128 104 | size=3 105 | stride=1 106 | pad=1 107 | activation=leaky 108 | 109 | [shortcut] 110 | from=-3 111 | activation=linear 112 | 113 | # Downsample 114 | 115 | [convolutional] 116 | batch_normalize=1 117 | filters=256 118 | size=3 119 | stride=2 120 | pad=1 121 | activation=leaky 122 | 123 | [convolutional] 124 | batch_normalize=1 125 | filters=128 126 | size=1 127 | stride=1 128 | pad=1 129 | activation=leaky 130 | 131 | [convolutional] 132 | batch_normalize=1 133 | filters=256 134 | size=3 135 | stride=1 136 | pad=1 137 | activation=leaky 138 | 139 | [shortcut] 140 | from=-3 141 | activation=linear 142 | 143 | [convolutional] 144 | batch_normalize=1 145 | filters=128 146 | size=1 147 | stride=1 148 | pad=1 149 | activation=leaky 150 | 151 | [convolutional] 152 | batch_normalize=1 153 | filters=256 154 | size=3 155 | stride=1 156 | pad=1 157 | activation=leaky 158 | 159 | [shortcut] 160 | from=-3 161 | activation=linear 162 | 163 | [convolutional] 164 | batch_normalize=1 165 | filters=128 166 | size=1 167 | stride=1 168 | pad=1 169 | activation=leaky 170 | 171 | [convolutional] 172 | batch_normalize=1 173 | filters=256 174 | size=3 175 | stride=1 176 | pad=1 177 | activation=leaky 178 | 179 | [shortcut] 180 | from=-3 181 | activation=linear 182 | 183 | [convolutional] 184 | batch_normalize=1 185 | filters=128 186 | size=1 187 | stride=1 188 | pad=1 189 | activation=leaky 190 | 191 | [convolutional] 192 | batch_normalize=1 193 | filters=256 194 | size=3 195 | stride=1 196 | pad=1 197 | activation=leaky 198 | 199 | [shortcut] 200 | from=-3 201 | activation=linear 202 | 203 | 204 | [convolutional] 205 | batch_normalize=1 206 | filters=128 207 | size=1 208 | stride=1 209 | pad=1 210 | activation=leaky 211 | 212 | [convolutional] 213 | batch_normalize=1 214 | filters=256 215 | size=3 216 | stride=1 217 | pad=1 218 | activation=leaky 219 | 220 | [shortcut] 221 | from=-3 222 | activation=linear 223 | 224 | [convolutional] 225 | batch_normalize=1 226 | filters=128 227 | size=1 228 | stride=1 229 | pad=1 230 | activation=leaky 231 | 232 | [convolutional] 233 | batch_normalize=1 234 | filters=256 235 | size=3 236 | stride=1 237 | pad=1 238 | activation=leaky 239 | 240 | [shortcut] 241 | from=-3 242 | activation=linear 243 | 244 | [convolutional] 245 | batch_normalize=1 246 | filters=128 247 | size=1 248 | stride=1 249 | pad=1 250 | activation=leaky 251 | 252 | [convolutional] 253 | batch_normalize=1 254 | filters=256 255 | size=3 256 | stride=1 257 | pad=1 258 | activation=leaky 259 | 260 | [shortcut] 261 | from=-3 262 | activation=linear 263 | 264 | [convolutional] 265 | batch_normalize=1 266 | filters=128 267 | size=1 268 | stride=1 269 | pad=1 270 | activation=leaky 271 | 272 | [convolutional] 273 | batch_normalize=1 274 | filters=256 275 | size=3 276 | stride=1 277 | pad=1 278 | activation=leaky 279 | 280 | [shortcut] 281 | from=-3 282 | activation=linear 283 | 284 | # Downsample 285 | 286 | [convolutional] 287 | batch_normalize=1 288 | filters=512 289 | size=3 290 | stride=2 291 | pad=1 292 | activation=leaky 293 | 294 | [convolutional] 295 | batch_normalize=1 296 | filters=256 297 | size=1 298 | stride=1 299 | pad=1 300 | activation=leaky 301 | 302 | [convolutional] 303 | batch_normalize=1 304 | filters=512 305 | size=3 306 | stride=1 307 | pad=1 308 | activation=leaky 309 | 310 | [shortcut] 311 | from=-3 312 | activation=linear 313 | 314 | 315 | [convolutional] 316 | batch_normalize=1 317 | filters=256 318 | size=1 319 | stride=1 320 | pad=1 321 | activation=leaky 322 | 323 | [convolutional] 324 | batch_normalize=1 325 | filters=512 326 | size=3 327 | stride=1 328 | pad=1 329 | activation=leaky 330 | 331 | [shortcut] 332 | from=-3 333 | activation=linear 334 | 335 | 336 | [convolutional] 337 | batch_normalize=1 338 | filters=256 339 | size=1 340 | stride=1 341 | pad=1 342 | activation=leaky 343 | 344 | [convolutional] 345 | batch_normalize=1 346 | filters=512 347 | size=3 348 | stride=1 349 | pad=1 350 | activation=leaky 351 | 352 | [shortcut] 353 | from=-3 354 | activation=linear 355 | 356 | 357 | [convolutional] 358 | batch_normalize=1 359 | filters=256 360 | size=1 361 | stride=1 362 | pad=1 363 | activation=leaky 364 | 365 | [convolutional] 366 | batch_normalize=1 367 | filters=512 368 | size=3 369 | stride=1 370 | pad=1 371 | activation=leaky 372 | 373 | [shortcut] 374 | from=-3 375 | activation=linear 376 | 377 | [convolutional] 378 | batch_normalize=1 379 | filters=256 380 | size=1 381 | stride=1 382 | pad=1 383 | activation=leaky 384 | 385 | [convolutional] 386 | batch_normalize=1 387 | filters=512 388 | size=3 389 | stride=1 390 | pad=1 391 | activation=leaky 392 | 393 | [shortcut] 394 | from=-3 395 | activation=linear 396 | 397 | 398 | [convolutional] 399 | batch_normalize=1 400 | filters=256 401 | size=1 402 | stride=1 403 | pad=1 404 | activation=leaky 405 | 406 | [convolutional] 407 | batch_normalize=1 408 | filters=512 409 | size=3 410 | stride=1 411 | pad=1 412 | activation=leaky 413 | 414 | [shortcut] 415 | from=-3 416 | activation=linear 417 | 418 | 419 | [convolutional] 420 | batch_normalize=1 421 | filters=256 422 | size=1 423 | stride=1 424 | pad=1 425 | activation=leaky 426 | 427 | [convolutional] 428 | batch_normalize=1 429 | filters=512 430 | size=3 431 | stride=1 432 | pad=1 433 | activation=leaky 434 | 435 | [shortcut] 436 | from=-3 437 | activation=linear 438 | 439 | [convolutional] 440 | batch_normalize=1 441 | filters=256 442 | size=1 443 | stride=1 444 | pad=1 445 | activation=leaky 446 | 447 | [convolutional] 448 | batch_normalize=1 449 | filters=512 450 | size=3 451 | stride=1 452 | pad=1 453 | activation=leaky 454 | 455 | [shortcut] 456 | from=-3 457 | activation=linear 458 | 459 | # Downsample 460 | 461 | [convolutional] 462 | batch_normalize=1 463 | filters=1024 464 | size=3 465 | stride=2 466 | pad=1 467 | activation=leaky 468 | 469 | [convolutional] 470 | batch_normalize=1 471 | filters=512 472 | size=1 473 | stride=1 474 | pad=1 475 | activation=leaky 476 | 477 | [convolutional] 478 | batch_normalize=1 479 | filters=1024 480 | size=3 481 | stride=1 482 | pad=1 483 | activation=leaky 484 | 485 | [shortcut] 486 | from=-3 487 | activation=linear 488 | 489 | [convolutional] 490 | batch_normalize=1 491 | filters=512 492 | size=1 493 | stride=1 494 | pad=1 495 | activation=leaky 496 | 497 | [convolutional] 498 | batch_normalize=1 499 | filters=1024 500 | size=3 501 | stride=1 502 | pad=1 503 | activation=leaky 504 | 505 | [shortcut] 506 | from=-3 507 | activation=linear 508 | 509 | [convolutional] 510 | batch_normalize=1 511 | filters=512 512 | size=1 513 | stride=1 514 | pad=1 515 | activation=leaky 516 | 517 | [convolutional] 518 | batch_normalize=1 519 | filters=1024 520 | size=3 521 | stride=1 522 | pad=1 523 | activation=leaky 524 | 525 | [shortcut] 526 | from=-3 527 | activation=linear 528 | 529 | [convolutional] 530 | batch_normalize=1 531 | filters=512 532 | size=1 533 | stride=1 534 | pad=1 535 | activation=leaky 536 | 537 | [convolutional] 538 | batch_normalize=1 539 | filters=1024 540 | size=3 541 | stride=1 542 | pad=1 543 | activation=leaky 544 | 545 | [shortcut] 546 | from=-3 547 | activation=linear 548 | 549 | ###################### 550 | 551 | [convolutional] 552 | batch_normalize=1 553 | filters=512 554 | size=1 555 | stride=1 556 | pad=1 557 | activation=leaky 558 | 559 | [convolutional] 560 | batch_normalize=1 561 | size=3 562 | stride=1 563 | pad=1 564 | filters=1024 565 | activation=leaky 566 | 567 | [convolutional] 568 | batch_normalize=1 569 | filters=512 570 | size=1 571 | stride=1 572 | pad=1 573 | activation=leaky 574 | 575 | [convolutional] 576 | batch_normalize=1 577 | size=3 578 | stride=1 579 | pad=1 580 | filters=1024 581 | activation=leaky 582 | 583 | [convolutional] 584 | batch_normalize=1 585 | filters=512 586 | size=1 587 | stride=1 588 | pad=1 589 | activation=leaky 590 | 591 | [convolutional] 592 | batch_normalize=1 593 | size=3 594 | stride=1 595 | pad=1 596 | filters=1024 597 | activation=leaky 598 | 599 | [convolutional] 600 | size=1 601 | stride=1 602 | pad=1 603 | filters=255 604 | activation=linear 605 | 606 | 607 | [yolo] 608 | mask = 6,7,8 609 | anchors = 10,13, 16,30, 33,23, 30,61, 62,45, 59,119, 116,90, 156,198, 373,326 610 | classes=80 611 | num=9 612 | jitter=.3 613 | ignore_thresh = .7 614 | truth_thresh = 1 615 | random=1 616 | 617 | 618 | [route] 619 | layers = -4 620 | 621 | [convolutional] 622 | batch_normalize=1 623 | filters=256 624 | size=1 625 | stride=1 626 | pad=1 627 | activation=leaky 628 | 629 | [upsample] 630 | stride=2 631 | 632 | [route] 633 | layers = -1, 61 634 | 635 | 636 | 637 | [convolutional] 638 | batch_normalize=1 639 | filters=256 640 | size=1 641 | stride=1 642 | pad=1 643 | activation=leaky 644 | 645 | [convolutional] 646 | batch_normalize=1 647 | size=3 648 | stride=1 649 | pad=1 650 | filters=512 651 | activation=leaky 652 | 653 | [convolutional] 654 | batch_normalize=1 655 | filters=256 656 | size=1 657 | stride=1 658 | pad=1 659 | activation=leaky 660 | 661 | [convolutional] 662 | batch_normalize=1 663 | size=3 664 | stride=1 665 | pad=1 666 | filters=512 667 | activation=leaky 668 | 669 | [convolutional] 670 | batch_normalize=1 671 | filters=256 672 | size=1 673 | stride=1 674 | pad=1 675 | activation=leaky 676 | 677 | [convolutional] 678 | batch_normalize=1 679 | size=3 680 | stride=1 681 | pad=1 682 | filters=512 683 | activation=leaky 684 | 685 | [convolutional] 686 | size=1 687 | stride=1 688 | pad=1 689 | filters=255 690 | activation=linear 691 | 692 | 693 | [yolo] 694 | mask = 3,4,5 695 | anchors = 10,13, 16,30, 33,23, 30,61, 62,45, 59,119, 116,90, 156,198, 373,326 696 | classes=80 697 | num=9 698 | jitter=.3 699 | ignore_thresh = .7 700 | truth_thresh = 1 701 | random=1 702 | 703 | 704 | 705 | [route] 706 | layers = -4 707 | 708 | [convolutional] 709 | batch_normalize=1 710 | filters=128 711 | size=1 712 | stride=1 713 | pad=1 714 | activation=leaky 715 | 716 | [upsample] 717 | stride=2 718 | 719 | [route] 720 | layers = -1, 36 721 | 722 | 723 | 724 | [convolutional] 725 | batch_normalize=1 726 | filters=128 727 | size=1 728 | stride=1 729 | pad=1 730 | activation=leaky 731 | 732 | [convolutional] 733 | batch_normalize=1 734 | size=3 735 | stride=1 736 | pad=1 737 | filters=256 738 | activation=leaky 739 | 740 | [convolutional] 741 | batch_normalize=1 742 | filters=128 743 | size=1 744 | stride=1 745 | pad=1 746 | activation=leaky 747 | 748 | [convolutional] 749 | batch_normalize=1 750 | size=3 751 | stride=1 752 | pad=1 753 | filters=256 754 | activation=leaky 755 | 756 | [convolutional] 757 | batch_normalize=1 758 | filters=128 759 | size=1 760 | stride=1 761 | pad=1 762 | activation=leaky 763 | 764 | [convolutional] 765 | batch_normalize=1 766 | size=3 767 | stride=1 768 | pad=1 769 | filters=256 770 | activation=leaky 771 | 772 | [convolutional] 773 | size=1 774 | stride=1 775 | pad=1 776 | filters=255 777 | activation=linear 778 | 779 | 780 | [yolo] 781 | mask = 0,1,2 782 | anchors = 10,13, 16,30, 33,23, 30,61, 62,45, 59,119, 116,90, 156,198, 373,326 783 | classes=80 784 | num=9 785 | jitter=.3 786 | ignore_thresh = .7 787 | truth_thresh = 1 788 | random=1 789 | -------------------------------------------------------------------------------- /data/coco.names: -------------------------------------------------------------------------------- 1 | person 2 | bicycle 3 | car 4 | motorbike 5 | aeroplane 6 | bus 7 | train 8 | truck 9 | boat 10 | traffic light 11 | fire hydrant 12 | stop sign 13 | parking meter 14 | bench 15 | bird 16 | cat 17 | dog 18 | horse 19 | sheep 20 | cow 21 | elephant 22 | bear 23 | zebra 24 | giraffe 25 | backpack 26 | umbrella 27 | handbag 28 | tie 29 | suitcase 30 | frisbee 31 | skis 32 | snowboard 33 | sports ball 34 | kite 35 | baseball bat 36 | baseball glove 37 | skateboard 38 | surfboard 39 | tennis racket 40 | bottle 41 | wine glass 42 | cup 43 | fork 44 | knife 45 | spoon 46 | bowl 47 | banana 48 | apple 49 | sandwich 50 | orange 51 | broccoli 52 | carrot 53 | hot dog 54 | pizza 55 | donut 56 | cake 57 | chair 58 | sofa 59 | pottedplant 60 | bed 61 | diningtable 62 | toilet 63 | tvmonitor 64 | laptop 65 | mouse 66 | remote 67 | keyboard 68 | cell phone 69 | microwave 70 | oven 71 | toaster 72 | sink 73 | refrigerator 74 | book 75 | clock 76 | vase 77 | scissors 78 | teddy bear 79 | hair drier 80 | toothbrush 81 | -------------------------------------------------------------------------------- /data/custom/classes.names: -------------------------------------------------------------------------------- 1 | train 2 | -------------------------------------------------------------------------------- /data/custom/images/train.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eriklindernoren/PyTorch-YOLOv3/1d621c8489e22c76ceb93bb2397ac6c8dfb5ceb7/data/custom/images/train.jpg -------------------------------------------------------------------------------- /data/custom/labels/train.txt: -------------------------------------------------------------------------------- 1 | 0 0.515 0.5 0.21694873 0.18286777 2 | -------------------------------------------------------------------------------- /data/custom/train.txt: -------------------------------------------------------------------------------- 1 | data/custom/images/train.jpg 2 | -------------------------------------------------------------------------------- /data/custom/valid.txt: -------------------------------------------------------------------------------- 1 | data/custom/images/train.jpg 2 | -------------------------------------------------------------------------------- /data/get_coco_dataset.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # CREDIT: https://github.com/pjreddie/darknet/tree/master/scripts/get_coco_dataset.sh 4 | 5 | # Clone COCO API 6 | git clone https://github.com/pdollar/coco 7 | cd coco 8 | 9 | mkdir images 10 | cd images 11 | 12 | # Download Images 13 | wget -c "https://pjreddie.com/media/files/train2014.zip" --header "Referer: pjreddie.com" 14 | wget -c "https://pjreddie.com/media/files/val2014.zip" --header "Referer: pjreddie.com" 15 | 16 | # Unzip 17 | unzip -q train2014.zip 18 | unzip -q val2014.zip 19 | 20 | cd .. 21 | 22 | # Download COCO Metadata 23 | wget -c "https://pjreddie.com/media/files/instances_train-val2014.zip" --header "Referer: pjreddie.com" 24 | wget -c "https://pjreddie.com/media/files/coco/5k.part" --header "Referer: pjreddie.com" 25 | wget -c "https://pjreddie.com/media/files/coco/trainvalno5k.part" --header "Referer: pjreddie.com" 26 | wget -c "https://pjreddie.com/media/files/coco/labels.tgz" --header "Referer: pjreddie.com" 27 | tar xzf labels.tgz 28 | unzip -q instances_train-val2014.zip 29 | 30 | # Set Up Image Lists 31 | paste <(awk "{print \"$PWD\"}" <5k.part) 5k.part | tr -d '\t' > 5k.txt 32 | paste <(awk "{print \"$PWD\"}" trainvalno5k.txt 33 | -------------------------------------------------------------------------------- /data/samples/dog.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eriklindernoren/PyTorch-YOLOv3/1d621c8489e22c76ceb93bb2397ac6c8dfb5ceb7/data/samples/dog.jpg -------------------------------------------------------------------------------- /data/samples/eagle.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eriklindernoren/PyTorch-YOLOv3/1d621c8489e22c76ceb93bb2397ac6c8dfb5ceb7/data/samples/eagle.jpg -------------------------------------------------------------------------------- /data/samples/field.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eriklindernoren/PyTorch-YOLOv3/1d621c8489e22c76ceb93bb2397ac6c8dfb5ceb7/data/samples/field.jpg -------------------------------------------------------------------------------- /data/samples/giraffe.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eriklindernoren/PyTorch-YOLOv3/1d621c8489e22c76ceb93bb2397ac6c8dfb5ceb7/data/samples/giraffe.jpg -------------------------------------------------------------------------------- /data/samples/herd_of_horses.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eriklindernoren/PyTorch-YOLOv3/1d621c8489e22c76ceb93bb2397ac6c8dfb5ceb7/data/samples/herd_of_horses.jpg -------------------------------------------------------------------------------- /data/samples/messi.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eriklindernoren/PyTorch-YOLOv3/1d621c8489e22c76ceb93bb2397ac6c8dfb5ceb7/data/samples/messi.jpg -------------------------------------------------------------------------------- /data/samples/person.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eriklindernoren/PyTorch-YOLOv3/1d621c8489e22c76ceb93bb2397ac6c8dfb5ceb7/data/samples/person.jpg -------------------------------------------------------------------------------- /data/samples/room.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eriklindernoren/PyTorch-YOLOv3/1d621c8489e22c76ceb93bb2397ac6c8dfb5ceb7/data/samples/room.jpg -------------------------------------------------------------------------------- /data/samples/street.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eriklindernoren/PyTorch-YOLOv3/1d621c8489e22c76ceb93bb2397ac6c8dfb5ceb7/data/samples/street.jpg -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "PyTorchYolo" 3 | version = "1.8.0" 4 | readme = "README.md" 5 | repository = "https://github.com/eriklindernoren/PyTorch-YOLOv3" 6 | description = "Minimal PyTorch implementation of YOLO" 7 | authors = ["Florian Vahl ", "Erik Linder-Noren "] 8 | license = "GPL-3.0" 9 | 10 | [tool.poetry.dependencies] 11 | python = ">=3.8,<4.0" 12 | torch = ">=1.10.1, < 1.13.0" 13 | torchvision = ">=0.13.1" 14 | matplotlib = "^3.3.3" 15 | tensorboard = "^2.10.0" 16 | terminaltables = "^3.1.0" 17 | Pillow = "^9.1.0" 18 | tqdm = "^4.64.1" 19 | urllib3 = [ 20 | {version = "<=1.22", python = ">=3.8,<3.9"}, 21 | {version = "^1.23", python = ">=3.9"} 22 | ] # Temp pin because of crash issue 23 | scipy = [ 24 | {version = "<=1.6", python = ">=3.8,<3.9"}, 25 | {version = "^1.9", python = ">=3.9,<4.0"} 26 | ] 27 | imgaug = "^0.4.0" 28 | torchsummary = "^1.5.1" 29 | numpy = "^1.23.4" 30 | 31 | [tool.poetry.dev-dependencies] 32 | profilehooks = "^1.12.0" 33 | 34 | [build-system] 35 | requires = ["poetry-core>=1.0.0"] 36 | build-backend = "poetry.core.masonry.api" 37 | 38 | [tool.poetry.scripts] 39 | yolo-detect = "pytorchyolo.detect:run" 40 | yolo-train = "pytorchyolo.train:run" 41 | yolo-test = "pytorchyolo.test:run" 42 | -------------------------------------------------------------------------------- /pytorchyolo/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eriklindernoren/PyTorch-YOLOv3/1d621c8489e22c76ceb93bb2397ac6c8dfb5ceb7/pytorchyolo/__init__.py -------------------------------------------------------------------------------- /pytorchyolo/detect.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python3 2 | 3 | from __future__ import division 4 | 5 | import os 6 | import argparse 7 | import tqdm 8 | import random 9 | import numpy as np 10 | 11 | from PIL import Image 12 | 13 | import torch 14 | import torchvision.transforms as transforms 15 | from torch.utils.data import DataLoader 16 | from torch.autograd import Variable 17 | 18 | from pytorchyolo.models import load_model 19 | from pytorchyolo.utils.utils import load_classes, rescale_boxes, non_max_suppression, print_environment_info 20 | from pytorchyolo.utils.datasets import ImageFolder 21 | from pytorchyolo.utils.transforms import Resize, DEFAULT_TRANSFORMS 22 | 23 | import matplotlib.pyplot as plt 24 | import matplotlib.patches as patches 25 | from matplotlib.ticker import NullLocator 26 | 27 | 28 | def detect_directory(model_path, weights_path, img_path, classes, output_path, 29 | batch_size=8, img_size=416, n_cpu=8, conf_thres=0.5, nms_thres=0.5): 30 | """Detects objects on all images in specified directory and saves output images with drawn detections. 31 | 32 | :param model_path: Path to model definition file (.cfg) 33 | :type model_path: str 34 | :param weights_path: Path to weights or checkpoint file (.weights or .pth) 35 | :type weights_path: str 36 | :param img_path: Path to directory with images to inference 37 | :type img_path: str 38 | :param classes: List of class names 39 | :type classes: [str] 40 | :param output_path: Path to output directory 41 | :type output_path: str 42 | :param batch_size: Size of each image batch, defaults to 8 43 | :type batch_size: int, optional 44 | :param img_size: Size of each image dimension for yolo, defaults to 416 45 | :type img_size: int, optional 46 | :param n_cpu: Number of cpu threads to use during batch generation, defaults to 8 47 | :type n_cpu: int, optional 48 | :param conf_thres: Object confidence threshold, defaults to 0.5 49 | :type conf_thres: float, optional 50 | :param nms_thres: IOU threshold for non-maximum suppression, defaults to 0.5 51 | :type nms_thres: float, optional 52 | """ 53 | dataloader = _create_data_loader(img_path, batch_size, img_size, n_cpu) 54 | model = load_model(model_path, weights_path) 55 | img_detections, imgs = detect( 56 | model, 57 | dataloader, 58 | output_path, 59 | conf_thres, 60 | nms_thres) 61 | _draw_and_save_output_images( 62 | img_detections, imgs, img_size, output_path, classes) 63 | 64 | print(f"---- Detections were saved to: '{output_path}' ----") 65 | 66 | 67 | def detect_image(model, image, img_size=416, conf_thres=0.5, nms_thres=0.5): 68 | """Inferences one image with model. 69 | 70 | :param model: Model for inference 71 | :type model: models.Darknet 72 | :param image: Image to inference 73 | :type image: nd.array 74 | :param img_size: Size of each image dimension for yolo, defaults to 416 75 | :type img_size: int, optional 76 | :param conf_thres: Object confidence threshold, defaults to 0.5 77 | :type conf_thres: float, optional 78 | :param nms_thres: IOU threshold for non-maximum suppression, defaults to 0.5 79 | :type nms_thres: float, optional 80 | :return: Detections on image with each detection in the format: [x1, y1, x2, y2, confidence, class] 81 | :rtype: nd.array 82 | """ 83 | model.eval() # Set model to evaluation mode 84 | 85 | # Configure input 86 | input_img = transforms.Compose([ 87 | DEFAULT_TRANSFORMS, 88 | Resize(img_size)])( 89 | (image, np.zeros((1, 5))))[0].unsqueeze(0) 90 | 91 | if torch.cuda.is_available(): 92 | input_img = input_img.to("cuda") 93 | 94 | # Get detections 95 | with torch.no_grad(): 96 | detections = model(input_img) 97 | detections = non_max_suppression(detections, conf_thres, nms_thres) 98 | detections = rescale_boxes(detections[0], img_size, image.shape[:2]) 99 | return detections.numpy() 100 | 101 | 102 | def detect(model, dataloader, output_path, conf_thres, nms_thres): 103 | """Inferences images with model. 104 | 105 | :param model: Model for inference 106 | :type model: models.Darknet 107 | :param dataloader: Dataloader provides the batches of images to inference 108 | :type dataloader: DataLoader 109 | :param output_path: Path to output directory 110 | :type output_path: str 111 | :param conf_thres: Object confidence threshold, defaults to 0.5 112 | :type conf_thres: float, optional 113 | :param nms_thres: IOU threshold for non-maximum suppression, defaults to 0.5 114 | :type nms_thres: float, optional 115 | :return: List of detections. The coordinates are given for the padded image that is provided by the dataloader. 116 | Use `utils.rescale_boxes` to transform them into the desired input image coordinate system before its transformed by the dataloader), 117 | List of input image paths 118 | :rtype: [Tensor], [str] 119 | """ 120 | # Create output directory, if missing 121 | os.makedirs(output_path, exist_ok=True) 122 | 123 | model.eval() # Set model to evaluation mode 124 | 125 | Tensor = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor 126 | 127 | img_detections = [] # Stores detections for each image index 128 | imgs = [] # Stores image paths 129 | 130 | for (img_paths, input_imgs) in tqdm.tqdm(dataloader, desc="Detecting"): 131 | # Configure input 132 | input_imgs = Variable(input_imgs.type(Tensor)) 133 | 134 | # Get detections 135 | with torch.no_grad(): 136 | detections = model(input_imgs) 137 | detections = non_max_suppression(detections, conf_thres, nms_thres) 138 | 139 | # Store image and detections 140 | img_detections.extend(detections) 141 | imgs.extend(img_paths) 142 | return img_detections, imgs 143 | 144 | 145 | def _draw_and_save_output_images(img_detections, imgs, img_size, output_path, classes): 146 | """Draws detections in output images and stores them. 147 | 148 | :param img_detections: List of detections 149 | :type img_detections: [Tensor] 150 | :param imgs: List of paths to image files 151 | :type imgs: [str] 152 | :param img_size: Size of each image dimension for yolo 153 | :type img_size: int 154 | :param output_path: Path of output directory 155 | :type output_path: str 156 | :param classes: List of class names 157 | :type classes: [str] 158 | """ 159 | 160 | # Iterate through images and save plot of detections 161 | for (image_path, detections) in zip(imgs, img_detections): 162 | print(f"Image {image_path}:") 163 | _draw_and_save_output_image( 164 | image_path, detections, img_size, output_path, classes) 165 | 166 | 167 | def _draw_and_save_output_image(image_path, detections, img_size, output_path, classes): 168 | """Draws detections in output image and stores this. 169 | 170 | :param image_path: Path to input image 171 | :type image_path: str 172 | :param detections: List of detections on image 173 | :type detections: [Tensor] 174 | :param img_size: Size of each image dimension for yolo 175 | :type img_size: int 176 | :param output_path: Path of output directory 177 | :type output_path: str 178 | :param classes: List of class names 179 | :type classes: [str] 180 | """ 181 | # Create plot 182 | img = np.array(Image.open(image_path)) 183 | plt.figure() 184 | fig, ax = plt.subplots(1) 185 | ax.imshow(img) 186 | # Rescale boxes to original image 187 | detections = rescale_boxes(detections, img_size, img.shape[:2]) 188 | unique_labels = detections[:, -1].cpu().unique() 189 | n_cls_preds = len(unique_labels) 190 | # Bounding-box colors 191 | cmap = plt.get_cmap("tab20b") 192 | colors = [cmap(i) for i in np.linspace(0, 1, n_cls_preds)] 193 | bbox_colors = random.sample(colors, n_cls_preds) 194 | for x1, y1, x2, y2, conf, cls_pred in detections: 195 | 196 | print(f"\t+ Label: {classes[int(cls_pred)]} | Confidence: {conf.item():0.4f}") 197 | 198 | box_w = x2 - x1 199 | box_h = y2 - y1 200 | 201 | color = bbox_colors[int(np.where(unique_labels == int(cls_pred))[0])] 202 | # Create a Rectangle patch 203 | bbox = patches.Rectangle((x1, y1), box_w, box_h, linewidth=2, edgecolor=color, facecolor="none") 204 | # Add the bbox to the plot 205 | ax.add_patch(bbox) 206 | # Add label 207 | plt.text( 208 | x1, 209 | y1, 210 | s=f"{classes[int(cls_pred)]}: {conf:.2f}", 211 | color="white", 212 | verticalalignment="top", 213 | bbox={"color": color, "pad": 0}) 214 | 215 | # Save generated image with detections 216 | plt.axis("off") 217 | plt.gca().xaxis.set_major_locator(NullLocator()) 218 | plt.gca().yaxis.set_major_locator(NullLocator()) 219 | filename = os.path.basename(image_path).split(".")[0] 220 | output_path = os.path.join(output_path, f"{filename}.png") 221 | plt.savefig(output_path, bbox_inches="tight", pad_inches=0.0) 222 | plt.close() 223 | 224 | 225 | def _create_data_loader(img_path, batch_size, img_size, n_cpu): 226 | """Creates a DataLoader for inferencing. 227 | 228 | :param img_path: Path to file containing all paths to validation images. 229 | :type img_path: str 230 | :param batch_size: Size of each image batch 231 | :type batch_size: int 232 | :param img_size: Size of each image dimension for yolo 233 | :type img_size: int 234 | :param n_cpu: Number of cpu threads to use during batch generation 235 | :type n_cpu: int 236 | :return: Returns DataLoader 237 | :rtype: DataLoader 238 | """ 239 | dataset = ImageFolder( 240 | img_path, 241 | transform=transforms.Compose([DEFAULT_TRANSFORMS, Resize(img_size)])) 242 | dataloader = DataLoader( 243 | dataset, 244 | batch_size=batch_size, 245 | shuffle=False, 246 | num_workers=n_cpu, 247 | pin_memory=True) 248 | return dataloader 249 | 250 | 251 | def run(): 252 | print_environment_info() 253 | parser = argparse.ArgumentParser(description="Detect objects on images.") 254 | parser.add_argument("-m", "--model", type=str, default="config/yolov3.cfg", help="Path to model definition file (.cfg)") 255 | parser.add_argument("-w", "--weights", type=str, default="weights/yolov3.weights", help="Path to weights or checkpoint file (.weights or .pth)") 256 | parser.add_argument("-i", "--images", type=str, default="data/samples", help="Path to directory with images to inference") 257 | parser.add_argument("-c", "--classes", type=str, default="data/coco.names", help="Path to classes label file (.names)") 258 | parser.add_argument("-o", "--output", type=str, default="output", help="Path to output directory") 259 | parser.add_argument("-b", "--batch_size", type=int, default=1, help="Size of each image batch") 260 | parser.add_argument("--img_size", type=int, default=416, help="Size of each image dimension for yolo") 261 | parser.add_argument("--n_cpu", type=int, default=8, help="Number of cpu threads to use during batch generation") 262 | parser.add_argument("--conf_thres", type=float, default=0.5, help="Object confidence threshold") 263 | parser.add_argument("--nms_thres", type=float, default=0.4, help="IOU threshold for non-maximum suppression") 264 | args = parser.parse_args() 265 | print(f"Command line arguments: {args}") 266 | 267 | # Extract class names from file 268 | classes = load_classes(args.classes) # List of class names 269 | 270 | detect_directory( 271 | args.model, 272 | args.weights, 273 | args.images, 274 | classes, 275 | args.output, 276 | batch_size=args.batch_size, 277 | img_size=args.img_size, 278 | n_cpu=args.n_cpu, 279 | conf_thres=args.conf_thres, 280 | nms_thres=args.nms_thres) 281 | 282 | 283 | if __name__ == '__main__': 284 | run() 285 | -------------------------------------------------------------------------------- /pytorchyolo/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | 3 | import os 4 | from itertools import chain 5 | from typing import List, Tuple 6 | 7 | import numpy as np 8 | import torch 9 | import torch.nn as nn 10 | import torch.nn.functional as F 11 | 12 | from pytorchyolo.utils.parse_config import parse_model_config 13 | from pytorchyolo.utils.utils import weights_init_normal 14 | 15 | 16 | def create_modules(module_defs: List[dict]) -> Tuple[dict, nn.ModuleList]: 17 | """ 18 | Constructs module list of layer blocks from module configuration in module_defs 19 | 20 | :param module_defs: List of dictionaries with module definitions 21 | :return: Hyperparameters and pytorch module list 22 | """ 23 | hyperparams = module_defs.pop(0) 24 | hyperparams.update({ 25 | 'batch': int(hyperparams['batch']), 26 | 'subdivisions': int(hyperparams['subdivisions']), 27 | 'width': int(hyperparams['width']), 28 | 'height': int(hyperparams['height']), 29 | 'channels': int(hyperparams['channels']), 30 | 'optimizer': hyperparams.get('optimizer'), 31 | 'momentum': float(hyperparams['momentum']), 32 | 'decay': float(hyperparams['decay']), 33 | 'learning_rate': float(hyperparams['learning_rate']), 34 | 'burn_in': int(hyperparams['burn_in']), 35 | 'max_batches': int(hyperparams['max_batches']), 36 | 'policy': hyperparams['policy'], 37 | 'lr_steps': list(zip(map(int, hyperparams["steps"].split(",")), 38 | map(float, hyperparams["scales"].split(",")))) 39 | }) 40 | assert hyperparams["height"] == hyperparams["width"], \ 41 | "Height and width should be equal! Non square images are padded with zeros." 42 | output_filters = [hyperparams["channels"]] 43 | module_list = nn.ModuleList() 44 | for module_i, module_def in enumerate(module_defs): 45 | modules = nn.Sequential() 46 | 47 | if module_def["type"] == "convolutional": 48 | bn = int(module_def["batch_normalize"]) 49 | filters = int(module_def["filters"]) 50 | kernel_size = int(module_def["size"]) 51 | pad = (kernel_size - 1) // 2 52 | modules.add_module( 53 | f"conv_{module_i}", 54 | nn.Conv2d( 55 | in_channels=output_filters[-1], 56 | out_channels=filters, 57 | kernel_size=kernel_size, 58 | stride=int(module_def["stride"]), 59 | padding=pad, 60 | bias=not bn, 61 | ), 62 | ) 63 | if bn: 64 | modules.add_module(f"batch_norm_{module_i}", 65 | nn.BatchNorm2d(filters, momentum=0.1, eps=1e-5)) 66 | if module_def["activation"] == "leaky": 67 | modules.add_module(f"leaky_{module_i}", nn.LeakyReLU(0.1)) 68 | elif module_def["activation"] == "mish": 69 | modules.add_module(f"mish_{module_i}", nn.Mish()) 70 | elif module_def["activation"] == "logistic": 71 | modules.add_module(f"sigmoid_{module_i}", nn.Sigmoid()) 72 | elif module_def["activation"] == "swish": 73 | modules.add_module(f"swish_{module_i}", nn.SiLU()) 74 | 75 | elif module_def["type"] == "maxpool": 76 | kernel_size = int(module_def["size"]) 77 | stride = int(module_def["stride"]) 78 | if kernel_size == 2 and stride == 1: 79 | modules.add_module(f"_debug_padding_{module_i}", nn.ZeroPad2d((0, 1, 0, 1))) 80 | maxpool = nn.MaxPool2d(kernel_size=kernel_size, stride=stride, 81 | padding=int((kernel_size - 1) // 2)) 82 | modules.add_module(f"maxpool_{module_i}", maxpool) 83 | 84 | elif module_def["type"] == "upsample": 85 | upsample = Upsample(scale_factor=int(module_def["stride"]), mode="nearest") 86 | modules.add_module(f"upsample_{module_i}", upsample) 87 | 88 | elif module_def["type"] == "route": 89 | layers = [int(x) for x in module_def["layers"].split(",")] 90 | filters = sum([output_filters[1:][i] for i in layers]) // int(module_def.get("groups", 1)) 91 | modules.add_module(f"route_{module_i}", nn.Sequential()) 92 | 93 | elif module_def["type"] == "shortcut": 94 | filters = output_filters[1:][int(module_def["from"])] 95 | modules.add_module(f"shortcut_{module_i}", nn.Sequential()) 96 | 97 | elif module_def["type"] == "yolo": 98 | anchor_idxs = [int(x) for x in module_def["mask"].split(",")] 99 | # Extract anchors 100 | anchors = [int(x) for x in module_def["anchors"].split(",")] 101 | anchors = [(anchors[i], anchors[i + 1]) for i in range(0, len(anchors), 2)] 102 | anchors = [anchors[i] for i in anchor_idxs] 103 | num_classes = int(module_def["classes"]) 104 | new_coords = bool(module_def.get("new_coords", False)) 105 | # Define detection layer 106 | yolo_layer = YOLOLayer(anchors, num_classes, new_coords) 107 | modules.add_module(f"yolo_{module_i}", yolo_layer) 108 | # Register module list and number of output filters 109 | module_list.append(modules) 110 | output_filters.append(filters) 111 | 112 | return hyperparams, module_list 113 | 114 | 115 | class Upsample(nn.Module): 116 | """ nn.Upsample is deprecated """ 117 | 118 | def __init__(self, scale_factor, mode: str = "nearest"): 119 | super(Upsample, self).__init__() 120 | self.scale_factor = scale_factor 121 | self.mode = mode 122 | 123 | def forward(self, x): 124 | x = F.interpolate(x, scale_factor=self.scale_factor, mode=self.mode) 125 | return x 126 | 127 | 128 | class YOLOLayer(nn.Module): 129 | """Detection layer""" 130 | 131 | def __init__(self, anchors: List[Tuple[int, int]], num_classes: int, new_coords: bool): 132 | """ 133 | Create a YOLO layer 134 | 135 | :param anchors: List of anchors 136 | :param num_classes: Number of classes 137 | :param new_coords: Whether to use the new coordinate format from YOLO V7 138 | """ 139 | super(YOLOLayer, self).__init__() 140 | self.num_anchors = len(anchors) 141 | self.num_classes = num_classes 142 | self.new_coords = new_coords 143 | self.mse_loss = nn.MSELoss() 144 | self.bce_loss = nn.BCELoss() 145 | self.no = num_classes + 5 # number of outputs per anchor 146 | self.grid = torch.zeros(1) # TODO 147 | 148 | anchors = torch.tensor(list(chain(*anchors))).float().view(-1, 2) 149 | self.register_buffer('anchors', anchors) 150 | self.register_buffer( 151 | 'anchor_grid', anchors.clone().view(1, -1, 1, 1, 2)) 152 | self.stride = None 153 | 154 | def forward(self, x: torch.Tensor, img_size: int) -> torch.Tensor: 155 | """ 156 | Forward pass of the YOLO layer 157 | 158 | :param x: Input tensor 159 | :param img_size: Size of the input image 160 | """ 161 | stride = img_size // x.size(2) 162 | self.stride = stride 163 | bs, _, ny, nx = x.shape # x(bs,255,20,20) to x(bs,3,20,20,85) 164 | x = x.view(bs, self.num_anchors, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous() 165 | 166 | if not self.training: # inference 167 | if self.grid.shape[2:4] != x.shape[2:4]: 168 | self.grid = self._make_grid(nx, ny).to(x.device) 169 | 170 | if self.new_coords: 171 | x[..., 0:2] = (x[..., 0:2] + self.grid) * stride # xy 172 | x[..., 2:4] = x[..., 2:4] ** 2 * (4 * self.anchor_grid) # wh 173 | else: 174 | x[..., 0:2] = (x[..., 0:2].sigmoid() + self.grid) * stride # xy 175 | x[..., 2:4] = torch.exp(x[..., 2:4]) * self.anchor_grid # wh 176 | x[..., 4:] = x[..., 4:].sigmoid() # conf, cls 177 | x = x.view(bs, -1, self.no) 178 | 179 | return x 180 | 181 | @staticmethod 182 | def _make_grid(nx: int = 20, ny: int = 20) -> torch.Tensor: 183 | """ 184 | Create a grid of (x, y) coordinates 185 | 186 | :param nx: Number of x coordinates 187 | :param ny: Number of y coordinates 188 | """ 189 | yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)], indexing='ij') 190 | return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float() 191 | 192 | 193 | class Darknet(nn.Module): 194 | """YOLOv3 object detection model""" 195 | 196 | def __init__(self, config_path): 197 | super(Darknet, self).__init__() 198 | self.module_defs = parse_model_config(config_path) 199 | self.hyperparams, self.module_list = create_modules(self.module_defs) 200 | self.yolo_layers = [layer[0] 201 | for layer in self.module_list if isinstance(layer[0], YOLOLayer)] 202 | self.seen = 0 203 | self.header_info = np.array([0, 0, 0, self.seen, 0], dtype=np.int32) 204 | 205 | def forward(self, x): 206 | img_size = x.size(2) 207 | layer_outputs, yolo_outputs = [], [] 208 | for i, (module_def, module) in enumerate(zip(self.module_defs, self.module_list)): 209 | if module_def["type"] in ["convolutional", "upsample", "maxpool"]: 210 | x = module(x) 211 | elif module_def["type"] == "route": 212 | combined_outputs = torch.cat([layer_outputs[int(layer_i)] for layer_i in module_def["layers"].split(",")], 1) 213 | group_size = combined_outputs.shape[1] // int(module_def.get("groups", 1)) 214 | group_id = int(module_def.get("group_id", 0)) 215 | x = combined_outputs[:, group_size * group_id : group_size * (group_id + 1)] # Slice groupings used by yolo v4 216 | elif module_def["type"] == "shortcut": 217 | layer_i = int(module_def["from"]) 218 | x = layer_outputs[-1] + layer_outputs[layer_i] 219 | elif module_def["type"] == "yolo": 220 | x = module[0](x, img_size) 221 | yolo_outputs.append(x) 222 | layer_outputs.append(x) 223 | return yolo_outputs if self.training else torch.cat(yolo_outputs, 1) 224 | 225 | def load_darknet_weights(self, weights_path): 226 | """Parses and loads the weights stored in 'weights_path'""" 227 | 228 | # Open the weights file 229 | with open(weights_path, "rb") as f: 230 | # First five are header values 231 | header = np.fromfile(f, dtype=np.int32, count=5) 232 | self.header_info = header # Needed to write header when saving weights 233 | self.seen = header[3] # number of images seen during training 234 | weights = np.fromfile(f, dtype=np.float32) # The rest are weights 235 | 236 | # Establish cutoff for loading backbone weights 237 | cutoff = None 238 | # If the weights file has a cutoff, we can find out about it by looking at the filename 239 | # examples: darknet53.conv.74 -> cutoff is 74 240 | filename = os.path.basename(weights_path) 241 | if ".conv." in filename: 242 | try: 243 | cutoff = int(filename.split(".")[-1]) # use last part of filename 244 | except ValueError: 245 | pass 246 | 247 | ptr = 0 248 | for i, (module_def, module) in enumerate(zip(self.module_defs, self.module_list)): 249 | if i == cutoff: 250 | break 251 | if module_def["type"] == "convolutional": 252 | conv_layer = module[0] 253 | if module_def["batch_normalize"]: 254 | # Load BN bias, weights, running mean and running variance 255 | bn_layer = module[1] 256 | num_b = bn_layer.bias.numel() # Number of biases 257 | # Bias 258 | bn_b = torch.from_numpy( 259 | weights[ptr: ptr + num_b]).view_as(bn_layer.bias) 260 | bn_layer.bias.data.copy_(bn_b) 261 | ptr += num_b 262 | # Weight 263 | bn_w = torch.from_numpy( 264 | weights[ptr: ptr + num_b]).view_as(bn_layer.weight) 265 | bn_layer.weight.data.copy_(bn_w) 266 | ptr += num_b 267 | # Running Mean 268 | bn_rm = torch.from_numpy( 269 | weights[ptr: ptr + num_b]).view_as(bn_layer.running_mean) 270 | bn_layer.running_mean.data.copy_(bn_rm) 271 | ptr += num_b 272 | # Running Var 273 | bn_rv = torch.from_numpy( 274 | weights[ptr: ptr + num_b]).view_as(bn_layer.running_var) 275 | bn_layer.running_var.data.copy_(bn_rv) 276 | ptr += num_b 277 | else: 278 | # Load conv. bias 279 | num_b = conv_layer.bias.numel() 280 | conv_b = torch.from_numpy( 281 | weights[ptr: ptr + num_b]).view_as(conv_layer.bias) 282 | conv_layer.bias.data.copy_(conv_b) 283 | ptr += num_b 284 | # Load conv. weights 285 | num_w = conv_layer.weight.numel() 286 | conv_w = torch.from_numpy( 287 | weights[ptr: ptr + num_w]).view_as(conv_layer.weight) 288 | conv_layer.weight.data.copy_(conv_w) 289 | ptr += num_w 290 | 291 | def save_darknet_weights(self, path, cutoff=-1): 292 | """ 293 | @:param path - path of the new weights file 294 | @:param cutoff - save layers between 0 and cutoff (cutoff = -1 -> all are saved) 295 | """ 296 | fp = open(path, "wb") 297 | self.header_info[3] = self.seen 298 | self.header_info.tofile(fp) 299 | 300 | # Iterate through layers 301 | for i, (module_def, module) in enumerate(zip(self.module_defs[:cutoff], self.module_list[:cutoff])): 302 | if module_def["type"] == "convolutional": 303 | conv_layer = module[0] 304 | # If batch norm, load bn first 305 | if module_def["batch_normalize"]: 306 | bn_layer = module[1] 307 | bn_layer.bias.data.cpu().numpy().tofile(fp) 308 | bn_layer.weight.data.cpu().numpy().tofile(fp) 309 | bn_layer.running_mean.data.cpu().numpy().tofile(fp) 310 | bn_layer.running_var.data.cpu().numpy().tofile(fp) 311 | # Load conv bias 312 | else: 313 | conv_layer.bias.data.cpu().numpy().tofile(fp) 314 | # Load conv weights 315 | conv_layer.weight.data.cpu().numpy().tofile(fp) 316 | 317 | fp.close() 318 | 319 | 320 | def load_model(model_path, weights_path=None): 321 | """Loads the yolo model from file. 322 | 323 | :param model_path: Path to model definition file (.cfg) 324 | :type model_path: str 325 | :param weights_path: Path to weights or checkpoint file (.weights or .pth) 326 | :type weights_path: str 327 | :return: Returns model 328 | :rtype: Darknet 329 | """ 330 | device = torch.device("cuda" if torch.cuda.is_available() 331 | else "cpu") # Select device for inference 332 | model = Darknet(model_path).to(device) 333 | 334 | model.apply(weights_init_normal) 335 | 336 | # If pretrained weights are specified, start from checkpoint or weight file 337 | if weights_path: 338 | if weights_path.endswith(".pth"): 339 | # Load checkpoint weights 340 | model.load_state_dict(torch.load(weights_path, map_location=device)) 341 | else: 342 | # Load darknet weights 343 | model.load_darknet_weights(weights_path) 344 | return model 345 | -------------------------------------------------------------------------------- /pytorchyolo/test.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python3 2 | 3 | from __future__ import division 4 | 5 | import argparse 6 | import tqdm 7 | import numpy as np 8 | 9 | from terminaltables import AsciiTable 10 | 11 | import torch 12 | from torch.utils.data import DataLoader 13 | from torch.autograd import Variable 14 | 15 | from pytorchyolo.models import load_model 16 | from pytorchyolo.utils.utils import load_classes, ap_per_class, get_batch_statistics, non_max_suppression, to_cpu, xywh2xyxy, print_environment_info 17 | from pytorchyolo.utils.datasets import ListDataset 18 | from pytorchyolo.utils.transforms import DEFAULT_TRANSFORMS 19 | from pytorchyolo.utils.parse_config import parse_data_config 20 | 21 | 22 | def evaluate_model_file(model_path, weights_path, img_path, class_names, batch_size=8, img_size=416, 23 | n_cpu=8, iou_thres=0.5, conf_thres=0.5, nms_thres=0.5, verbose=True): 24 | """Evaluate model on validation dataset. 25 | 26 | :param model_path: Path to model definition file (.cfg) 27 | :type model_path: str 28 | :param weights_path: Path to weights or checkpoint file (.weights or .pth) 29 | :type weights_path: str 30 | :param img_path: Path to file containing all paths to validation images. 31 | :type img_path: str 32 | :param class_names: List of class names 33 | :type class_names: [str] 34 | :param batch_size: Size of each image batch, defaults to 8 35 | :type batch_size: int, optional 36 | :param img_size: Size of each image dimension for yolo, defaults to 416 37 | :type img_size: int, optional 38 | :param n_cpu: Number of cpu threads to use during batch generation, defaults to 8 39 | :type n_cpu: int, optional 40 | :param iou_thres: IOU threshold required to qualify as detected, defaults to 0.5 41 | :type iou_thres: float, optional 42 | :param conf_thres: Object confidence threshold, defaults to 0.5 43 | :type conf_thres: float, optional 44 | :param nms_thres: IOU threshold for non-maximum suppression, defaults to 0.5 45 | :type nms_thres: float, optional 46 | :param verbose: If True, prints stats of model, defaults to True 47 | :type verbose: bool, optional 48 | :return: Returns precision, recall, AP, f1, ap_class 49 | """ 50 | dataloader = _create_validation_data_loader( 51 | img_path, batch_size, img_size, n_cpu) 52 | model = load_model(model_path, weights_path) 53 | metrics_output = _evaluate( 54 | model, 55 | dataloader, 56 | class_names, 57 | img_size, 58 | iou_thres, 59 | conf_thres, 60 | nms_thres, 61 | verbose) 62 | return metrics_output 63 | 64 | 65 | def print_eval_stats(metrics_output, class_names, verbose): 66 | if metrics_output is not None: 67 | precision, recall, AP, f1, ap_class = metrics_output 68 | if verbose: 69 | # Prints class AP and mean AP 70 | ap_table = [["Index", "Class", "AP"]] 71 | for i, c in enumerate(ap_class): 72 | ap_table += [[c, class_names[c], "%.5f" % AP[i]]] 73 | print(AsciiTable(ap_table).table) 74 | print(f"---- mAP {AP.mean():.5f} ----") 75 | else: 76 | print("---- mAP not measured (no detections found by model) ----") 77 | 78 | 79 | def _evaluate(model, dataloader, class_names, img_size, iou_thres, conf_thres, nms_thres, verbose): 80 | """Evaluate model on validation dataset. 81 | 82 | :param model: Model to evaluate 83 | :type model: models.Darknet 84 | :param dataloader: Dataloader provides the batches of images with targets 85 | :type dataloader: DataLoader 86 | :param class_names: List of class names 87 | :type class_names: [str] 88 | :param img_size: Size of each image dimension for yolo 89 | :type img_size: int 90 | :param iou_thres: IOU threshold required to qualify as detected 91 | :type iou_thres: float 92 | :param conf_thres: Object confidence threshold 93 | :type conf_thres: float 94 | :param nms_thres: IOU threshold for non-maximum suppression 95 | :type nms_thres: float 96 | :param verbose: If True, prints stats of model 97 | :type verbose: bool 98 | :return: Returns precision, recall, AP, f1, ap_class 99 | """ 100 | model.eval() # Set model to evaluation mode 101 | 102 | Tensor = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor 103 | 104 | labels = [] 105 | sample_metrics = [] # List of tuples (TP, confs, pred) 106 | for _, imgs, targets in tqdm.tqdm(dataloader, desc="Validating"): 107 | # Extract labels 108 | labels += targets[:, 1].tolist() 109 | # Rescale target 110 | targets[:, 2:] = xywh2xyxy(targets[:, 2:]) 111 | targets[:, 2:] *= img_size 112 | 113 | imgs = Variable(imgs.type(Tensor), requires_grad=False) 114 | 115 | with torch.no_grad(): 116 | outputs = model(imgs) 117 | outputs = non_max_suppression(outputs, conf_thres=conf_thres, iou_thres=nms_thres) 118 | 119 | sample_metrics += get_batch_statistics(outputs, targets, iou_threshold=iou_thres) 120 | 121 | if len(sample_metrics) == 0: # No detections over whole validation set. 122 | print("---- No detections over whole validation set ----") 123 | return None 124 | 125 | # Concatenate sample statistics 126 | true_positives, pred_scores, pred_labels = [ 127 | np.concatenate(x, 0) for x in list(zip(*sample_metrics))] 128 | metrics_output = ap_per_class( 129 | true_positives, pred_scores, pred_labels, labels) 130 | 131 | print_eval_stats(metrics_output, class_names, verbose) 132 | 133 | return metrics_output 134 | 135 | 136 | def _create_validation_data_loader(img_path, batch_size, img_size, n_cpu): 137 | """ 138 | Creates a DataLoader for validation. 139 | 140 | :param img_path: Path to file containing all paths to validation images. 141 | :type img_path: str 142 | :param batch_size: Size of each image batch 143 | :type batch_size: int 144 | :param img_size: Size of each image dimension for yolo 145 | :type img_size: int 146 | :param n_cpu: Number of cpu threads to use during batch generation 147 | :type n_cpu: int 148 | :return: Returns DataLoader 149 | :rtype: DataLoader 150 | """ 151 | dataset = ListDataset(img_path, img_size=img_size, multiscale=False, transform=DEFAULT_TRANSFORMS) 152 | dataloader = DataLoader( 153 | dataset, 154 | batch_size=batch_size, 155 | shuffle=False, 156 | num_workers=n_cpu, 157 | pin_memory=True, 158 | collate_fn=dataset.collate_fn) 159 | return dataloader 160 | 161 | 162 | def run(): 163 | print_environment_info() 164 | parser = argparse.ArgumentParser(description="Evaluate validation data.") 165 | parser.add_argument("-m", "--model", type=str, default="config/yolov3.cfg", help="Path to model definition file (.cfg)") 166 | parser.add_argument("-w", "--weights", type=str, default="weights/yolov3.weights", help="Path to weights or checkpoint file (.weights or .pth)") 167 | parser.add_argument("-d", "--data", type=str, default="config/coco.data", help="Path to data config file (.data)") 168 | parser.add_argument("-b", "--batch_size", type=int, default=8, help="Size of each image batch") 169 | parser.add_argument("-v", "--verbose", action='store_true', help="Makes the validation more verbose") 170 | parser.add_argument("--img_size", type=int, default=416, help="Size of each image dimension for yolo") 171 | parser.add_argument("--n_cpu", type=int, default=8, help="Number of cpu threads to use during batch generation") 172 | parser.add_argument("--iou_thres", type=float, default=0.5, help="IOU threshold required to qualify as detected") 173 | parser.add_argument("--conf_thres", type=float, default=0.01, help="Object confidence threshold") 174 | parser.add_argument("--nms_thres", type=float, default=0.4, help="IOU threshold for non-maximum suppression") 175 | args = parser.parse_args() 176 | print(f"Command line arguments: {args}") 177 | 178 | # Load configuration from data file 179 | data_config = parse_data_config(args.data) 180 | # Path to file containing all images for validation 181 | valid_path = data_config["valid"] 182 | class_names = load_classes(data_config["names"]) # List of class names 183 | 184 | precision, recall, AP, f1, ap_class = evaluate_model_file( 185 | args.model, 186 | args.weights, 187 | valid_path, 188 | class_names, 189 | batch_size=args.batch_size, 190 | img_size=args.img_size, 191 | n_cpu=args.n_cpu, 192 | iou_thres=args.iou_thres, 193 | conf_thres=args.conf_thres, 194 | nms_thres=args.nms_thres, 195 | verbose=True) 196 | 197 | 198 | if __name__ == "__main__": 199 | run() 200 | -------------------------------------------------------------------------------- /pytorchyolo/train.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python3 2 | 3 | from __future__ import division 4 | 5 | import os 6 | import argparse 7 | import tqdm 8 | 9 | import torch 10 | from torch.utils.data import DataLoader 11 | import torch.optim as optim 12 | 13 | from pytorchyolo.models import load_model 14 | from pytorchyolo.utils.logger import Logger 15 | from pytorchyolo.utils.utils import to_cpu, load_classes, print_environment_info, provide_determinism, worker_seed_set 16 | from pytorchyolo.utils.datasets import ListDataset 17 | from pytorchyolo.utils.augmentations import AUGMENTATION_TRANSFORMS 18 | #from pytorchyolo.utils.transforms import DEFAULT_TRANSFORMS 19 | from pytorchyolo.utils.parse_config import parse_data_config 20 | from pytorchyolo.utils.loss import compute_loss 21 | from pytorchyolo.test import _evaluate, _create_validation_data_loader 22 | 23 | from terminaltables import AsciiTable 24 | 25 | from torchsummary import summary 26 | 27 | 28 | def _create_data_loader(img_path, batch_size, img_size, n_cpu, multiscale_training=False): 29 | """Creates a DataLoader for training. 30 | 31 | :param img_path: Path to file containing all paths to training images. 32 | :type img_path: str 33 | :param batch_size: Size of each image batch 34 | :type batch_size: int 35 | :param img_size: Size of each image dimension for yolo 36 | :type img_size: int 37 | :param n_cpu: Number of cpu threads to use during batch generation 38 | :type n_cpu: int 39 | :param multiscale_training: Scale images to different sizes randomly 40 | :type multiscale_training: bool 41 | :return: Returns DataLoader 42 | :rtype: DataLoader 43 | """ 44 | dataset = ListDataset( 45 | img_path, 46 | img_size=img_size, 47 | multiscale=multiscale_training, 48 | transform=AUGMENTATION_TRANSFORMS) 49 | dataloader = DataLoader( 50 | dataset, 51 | batch_size=batch_size, 52 | shuffle=True, 53 | num_workers=n_cpu, 54 | pin_memory=True, 55 | collate_fn=dataset.collate_fn, 56 | worker_init_fn=worker_seed_set) 57 | return dataloader 58 | 59 | 60 | def run(): 61 | print_environment_info() 62 | parser = argparse.ArgumentParser(description="Trains the YOLO model.") 63 | parser.add_argument("-m", "--model", type=str, default="config/yolov3.cfg", help="Path to model definition file (.cfg)") 64 | parser.add_argument("-d", "--data", type=str, default="config/coco.data", help="Path to data config file (.data)") 65 | parser.add_argument("-e", "--epochs", type=int, default=300, help="Number of epochs") 66 | parser.add_argument("-v", "--verbose", action='store_true', help="Makes the training more verbose") 67 | parser.add_argument("--n_cpu", type=int, default=8, help="Number of cpu threads to use during batch generation") 68 | parser.add_argument("--pretrained_weights", type=str, help="Path to checkpoint file (.weights or .pth). Starts training from checkpoint model") 69 | parser.add_argument("--checkpoint_interval", type=int, default=1, help="Interval of epochs between saving model weights") 70 | parser.add_argument("--evaluation_interval", type=int, default=1, help="Interval of epochs between evaluations on validation set") 71 | parser.add_argument("--multiscale_training", action="store_true", help="Allow multi-scale training") 72 | parser.add_argument("--iou_thres", type=float, default=0.5, help="Evaluation: IOU threshold required to qualify as detected") 73 | parser.add_argument("--conf_thres", type=float, default=0.1, help="Evaluation: Object confidence threshold") 74 | parser.add_argument("--nms_thres", type=float, default=0.5, help="Evaluation: IOU threshold for non-maximum suppression") 75 | parser.add_argument("--logdir", type=str, default="logs", help="Directory for training log files (e.g. for TensorBoard)") 76 | parser.add_argument("--seed", type=int, default=-1, help="Makes results reproducable. Set -1 to disable.") 77 | args = parser.parse_args() 78 | print(f"Command line arguments: {args}") 79 | 80 | if args.seed != -1: 81 | provide_determinism(args.seed) 82 | 83 | logger = Logger(args.logdir) # Tensorboard logger 84 | 85 | # Create output directories if missing 86 | os.makedirs("output", exist_ok=True) 87 | os.makedirs("checkpoints", exist_ok=True) 88 | 89 | # Get data configuration 90 | data_config = parse_data_config(args.data) 91 | train_path = data_config["train"] 92 | valid_path = data_config["valid"] 93 | class_names = load_classes(data_config["names"]) 94 | device = torch.device("cuda" if torch.cuda.is_available() else "cpu") 95 | 96 | # ############ 97 | # Create model 98 | # ############ 99 | 100 | model = load_model(args.model, args.pretrained_weights) 101 | 102 | # Print model 103 | if args.verbose: 104 | summary(model, input_size=(3, model.hyperparams['height'], model.hyperparams['height'])) 105 | 106 | mini_batch_size = model.hyperparams['batch'] // model.hyperparams['subdivisions'] 107 | 108 | # ################# 109 | # Create Dataloader 110 | # ################# 111 | 112 | # Load training dataloader 113 | dataloader = _create_data_loader( 114 | train_path, 115 | mini_batch_size, 116 | model.hyperparams['height'], 117 | args.n_cpu, 118 | args.multiscale_training) 119 | 120 | # Load validation dataloader 121 | validation_dataloader = _create_validation_data_loader( 122 | valid_path, 123 | mini_batch_size, 124 | model.hyperparams['height'], 125 | args.n_cpu) 126 | 127 | # ################ 128 | # Create optimizer 129 | # ################ 130 | 131 | params = [p for p in model.parameters() if p.requires_grad] 132 | 133 | if (model.hyperparams['optimizer'] in [None, "adam"]): 134 | optimizer = optim.Adam( 135 | params, 136 | lr=model.hyperparams['learning_rate'], 137 | weight_decay=model.hyperparams['decay'], 138 | ) 139 | elif (model.hyperparams['optimizer'] == "sgd"): 140 | optimizer = optim.SGD( 141 | params, 142 | lr=model.hyperparams['learning_rate'], 143 | weight_decay=model.hyperparams['decay'], 144 | momentum=model.hyperparams['momentum']) 145 | else: 146 | print("Unknown optimizer. Please choose between (adam, sgd).") 147 | 148 | # skip epoch zero, because then the calculations for when to evaluate/checkpoint makes more intuitive sense 149 | # e.g. when you stop after 30 epochs and evaluate every 10 epochs then the evaluations happen after: 10,20,30 150 | # instead of: 0, 10, 20 151 | for epoch in range(1, args.epochs+1): 152 | 153 | print("\n---- Training Model ----") 154 | 155 | model.train() # Set model to training mode 156 | 157 | for batch_i, (_, imgs, targets) in enumerate(tqdm.tqdm(dataloader, desc=f"Training Epoch {epoch}")): 158 | batches_done = len(dataloader) * epoch + batch_i 159 | 160 | imgs = imgs.to(device, non_blocking=True) 161 | targets = targets.to(device) 162 | 163 | outputs = model(imgs) 164 | 165 | loss, loss_components = compute_loss(outputs, targets, model) 166 | 167 | loss.backward() 168 | 169 | ############### 170 | # Run optimizer 171 | ############### 172 | 173 | if batches_done % model.hyperparams['subdivisions'] == 0: 174 | # Adapt learning rate 175 | # Get learning rate defined in cfg 176 | lr = model.hyperparams['learning_rate'] 177 | if batches_done < model.hyperparams['burn_in']: 178 | # Burn in 179 | lr *= (batches_done / model.hyperparams['burn_in']) 180 | else: 181 | # Set and parse the learning rate to the steps defined in the cfg 182 | for threshold, value in model.hyperparams['lr_steps']: 183 | if batches_done > threshold: 184 | lr *= value 185 | # Log the learning rate 186 | logger.scalar_summary("train/learning_rate", lr, batches_done) 187 | # Set learning rate 188 | for g in optimizer.param_groups: 189 | g['lr'] = lr 190 | 191 | # Run optimizer 192 | optimizer.step() 193 | # Reset gradients 194 | optimizer.zero_grad() 195 | 196 | # ############ 197 | # Log progress 198 | # ############ 199 | if args.verbose: 200 | print(AsciiTable( 201 | [ 202 | ["Type", "Value"], 203 | ["IoU loss", float(loss_components[0])], 204 | ["Object loss", float(loss_components[1])], 205 | ["Class loss", float(loss_components[2])], 206 | ["Loss", float(loss_components[3])], 207 | ["Batch loss", to_cpu(loss).item()], 208 | ]).table) 209 | 210 | # Tensorboard logging 211 | tensorboard_log = [ 212 | ("train/iou_loss", float(loss_components[0])), 213 | ("train/obj_loss", float(loss_components[1])), 214 | ("train/class_loss", float(loss_components[2])), 215 | ("train/loss", to_cpu(loss).item())] 216 | logger.list_of_scalars_summary(tensorboard_log, batches_done) 217 | 218 | model.seen += imgs.size(0) 219 | 220 | # ############# 221 | # Save progress 222 | # ############# 223 | 224 | # Save model to checkpoint file 225 | if epoch % args.checkpoint_interval == 0: 226 | checkpoint_path = f"checkpoints/yolov3_ckpt_{epoch}.pth" 227 | print(f"---- Saving checkpoint to: '{checkpoint_path}' ----") 228 | torch.save(model.state_dict(), checkpoint_path) 229 | 230 | # ######## 231 | # Evaluate 232 | # ######## 233 | 234 | if epoch % args.evaluation_interval == 0: 235 | print("\n---- Evaluating Model ----") 236 | # Evaluate the model on the validation set 237 | metrics_output = _evaluate( 238 | model, 239 | validation_dataloader, 240 | class_names, 241 | img_size=model.hyperparams['height'], 242 | iou_thres=args.iou_thres, 243 | conf_thres=args.conf_thres, 244 | nms_thres=args.nms_thres, 245 | verbose=args.verbose 246 | ) 247 | 248 | if metrics_output is not None: 249 | precision, recall, AP, f1, ap_class = metrics_output 250 | evaluation_metrics = [ 251 | ("validation/precision", precision.mean()), 252 | ("validation/recall", recall.mean()), 253 | ("validation/mAP", AP.mean()), 254 | ("validation/f1", f1.mean())] 255 | logger.list_of_scalars_summary(evaluation_metrics, epoch) 256 | 257 | 258 | if __name__ == "__main__": 259 | run() 260 | -------------------------------------------------------------------------------- /pytorchyolo/utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eriklindernoren/PyTorch-YOLOv3/1d621c8489e22c76ceb93bb2397ac6c8dfb5ceb7/pytorchyolo/utils/__init__.py -------------------------------------------------------------------------------- /pytorchyolo/utils/augmentations.py: -------------------------------------------------------------------------------- 1 | import imgaug.augmenters as iaa 2 | from torchvision import transforms 3 | from pytorchyolo.utils.transforms import ToTensor, PadSquare, RelativeLabels, AbsoluteLabels, ImgAug 4 | 5 | 6 | class DefaultAug(ImgAug): 7 | def __init__(self, ): 8 | self.augmentations = iaa.Sequential([ 9 | iaa.Sharpen((0.0, 0.1)), 10 | iaa.Affine(rotate=(-0, 0), translate_percent=(-0.1, 0.1), scale=(0.8, 1.5)), 11 | iaa.AddToBrightness((-60, 40)), 12 | iaa.AddToHue((-10, 10)), 13 | iaa.Fliplr(0.5), 14 | ]) 15 | 16 | 17 | class StrongAug(ImgAug): 18 | def __init__(self, ): 19 | self.augmentations = iaa.Sequential([ 20 | iaa.Dropout([0.0, 0.01]), 21 | iaa.Sharpen((0.0, 0.1)), 22 | iaa.Affine(rotate=(-10, 10), translate_percent=(-0.1, 0.1), scale=(0.8, 1.5)), 23 | iaa.AddToBrightness((-60, 40)), 24 | iaa.AddToHue((-20, 20)), 25 | iaa.Fliplr(0.5), 26 | ]) 27 | 28 | 29 | AUGMENTATION_TRANSFORMS = transforms.Compose([ 30 | AbsoluteLabels(), 31 | DefaultAug(), 32 | PadSquare(), 33 | RelativeLabels(), 34 | ToTensor(), 35 | ]) 36 | -------------------------------------------------------------------------------- /pytorchyolo/utils/datasets.py: -------------------------------------------------------------------------------- 1 | from torch.utils.data import Dataset 2 | import torch.nn.functional as F 3 | import torch 4 | import glob 5 | import random 6 | import os 7 | import warnings 8 | import numpy as np 9 | from PIL import Image 10 | from PIL import ImageFile 11 | 12 | ImageFile.LOAD_TRUNCATED_IMAGES = True 13 | 14 | 15 | def pad_to_square(img, pad_value): 16 | c, h, w = img.shape 17 | dim_diff = np.abs(h - w) 18 | # (upper / left) padding and (lower / right) padding 19 | pad1, pad2 = dim_diff // 2, dim_diff - dim_diff // 2 20 | # Determine padding 21 | pad = (0, 0, pad1, pad2) if h <= w else (pad1, pad2, 0, 0) 22 | # Add padding 23 | img = F.pad(img, pad, "constant", value=pad_value) 24 | 25 | return img, pad 26 | 27 | 28 | def resize(image, size): 29 | image = F.interpolate(image.unsqueeze(0), size=size, mode="nearest").squeeze(0) 30 | return image 31 | 32 | 33 | class ImageFolder(Dataset): 34 | def __init__(self, folder_path, transform=None): 35 | self.files = sorted(glob.glob("%s/*.*" % folder_path)) 36 | self.transform = transform 37 | 38 | def __getitem__(self, index): 39 | 40 | img_path = self.files[index % len(self.files)] 41 | img = np.array( 42 | Image.open(img_path).convert('RGB'), 43 | dtype=np.uint8) 44 | 45 | # Label Placeholder 46 | boxes = np.zeros((1, 5)) 47 | 48 | # Apply transforms 49 | if self.transform: 50 | img, _ = self.transform((img, boxes)) 51 | 52 | return img_path, img 53 | 54 | def __len__(self): 55 | return len(self.files) 56 | 57 | 58 | class ListDataset(Dataset): 59 | def __init__(self, list_path, img_size=416, multiscale=True, transform=None): 60 | with open(list_path, "r") as file: 61 | self.img_files = file.readlines() 62 | 63 | self.label_files = [] 64 | for path in self.img_files: 65 | image_dir = os.path.dirname(path) 66 | label_dir = "labels".join(image_dir.rsplit("images", 1)) 67 | assert label_dir != image_dir, \ 68 | f"Image path must contain a folder named 'images'! \n'{image_dir}'" 69 | label_file = os.path.join(label_dir, os.path.basename(path)) 70 | label_file = os.path.splitext(label_file)[0] + '.txt' 71 | self.label_files.append(label_file) 72 | 73 | self.img_size = img_size 74 | self.max_objects = 100 75 | self.multiscale = multiscale 76 | self.min_size = self.img_size - 3 * 32 77 | self.max_size = self.img_size + 3 * 32 78 | self.batch_count = 0 79 | self.transform = transform 80 | 81 | def __getitem__(self, index): 82 | 83 | # --------- 84 | # Image 85 | # --------- 86 | try: 87 | 88 | img_path = self.img_files[index % len(self.img_files)].rstrip() 89 | 90 | img = np.array(Image.open(img_path).convert('RGB'), dtype=np.uint8) 91 | except Exception: 92 | print(f"Could not read image '{img_path}'.") 93 | return 94 | 95 | # --------- 96 | # Label 97 | # --------- 98 | try: 99 | label_path = self.label_files[index % len(self.img_files)].rstrip() 100 | 101 | # Ignore warning if file is empty 102 | with warnings.catch_warnings(): 103 | warnings.simplefilter("ignore") 104 | boxes = np.loadtxt(label_path).reshape(-1, 5) 105 | except Exception: 106 | print(f"Could not read label '{label_path}'.") 107 | return 108 | 109 | # ----------- 110 | # Transform 111 | # ----------- 112 | if self.transform: 113 | try: 114 | img, bb_targets = self.transform((img, boxes)) 115 | except Exception: 116 | print("Could not apply transform.") 117 | return 118 | 119 | return img_path, img, bb_targets 120 | 121 | def collate_fn(self, batch): 122 | self.batch_count += 1 123 | 124 | # Drop invalid images 125 | batch = [data for data in batch if data is not None] 126 | 127 | paths, imgs, bb_targets = list(zip(*batch)) 128 | 129 | # Selects new image size every tenth batch 130 | if self.multiscale and self.batch_count % 10 == 0: 131 | self.img_size = random.choice( 132 | range(self.min_size, self.max_size + 1, 32)) 133 | 134 | # Resize images to input shape 135 | imgs = torch.stack([resize(img, self.img_size) for img in imgs]) 136 | 137 | # Add sample index to targets 138 | for i, boxes in enumerate(bb_targets): 139 | boxes[:, 0] = i 140 | bb_targets = torch.cat(bb_targets, 0) 141 | 142 | return paths, imgs, bb_targets 143 | 144 | def __len__(self): 145 | return len(self.img_files) 146 | -------------------------------------------------------------------------------- /pytorchyolo/utils/logger.py: -------------------------------------------------------------------------------- 1 | import os 2 | import datetime 3 | from torch.utils.tensorboard import SummaryWriter 4 | 5 | 6 | class Logger(object): 7 | def __init__(self, log_dir, log_hist=True): 8 | """Create a summary writer logging to log_dir.""" 9 | if log_hist: # Check a new folder for each log should be dreated 10 | log_dir = os.path.join( 11 | log_dir, 12 | datetime.datetime.now().strftime("%Y_%m_%d__%H_%M_%S")) 13 | self.writer = SummaryWriter(log_dir) 14 | 15 | def scalar_summary(self, tag, value, step): 16 | """Log a scalar variable.""" 17 | self.writer.add_scalar(tag, value, step) 18 | 19 | def list_of_scalars_summary(self, tag_value_pairs, step): 20 | """Log scalar variables.""" 21 | for tag, value in tag_value_pairs: 22 | self.writer.add_scalar(tag, value, step) 23 | -------------------------------------------------------------------------------- /pytorchyolo/utils/loss.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | import torch 4 | import torch.nn as nn 5 | 6 | from .utils import to_cpu 7 | 8 | # This new loss function is based on https://github.com/ultralytics/yolov3/blob/master/utils/loss.py 9 | 10 | 11 | def bbox_iou(box1, box2, x1y1x2y2=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-9): 12 | # Returns the IoU of box1 to box2. box1 is 4, box2 is nx4 13 | box2 = box2.T 14 | 15 | # Get the coordinates of bounding boxes 16 | if x1y1x2y2: # x1, y1, x2, y2 = box1 17 | b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3] 18 | b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3] 19 | else: # transform from xywh to xyxy 20 | b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2 21 | b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2 22 | b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2 23 | b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2 24 | 25 | # Intersection area 26 | inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \ 27 | (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0) 28 | 29 | # Union Area 30 | w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps 31 | w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps 32 | union = w1 * h1 + w2 * h2 - inter + eps 33 | 34 | iou = inter / union 35 | if GIoU or DIoU or CIoU: 36 | # convex (smallest enclosing box) width 37 | cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) 38 | ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height 39 | if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1 40 | c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared 41 | rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + 42 | (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center distance squared 43 | if DIoU: 44 | return iou - rho2 / c2 # DIoU 45 | elif CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47 46 | v = (4 / math.pi ** 2) * \ 47 | torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2) 48 | with torch.no_grad(): 49 | alpha = v / ((1 + eps) - iou + v) 50 | return iou - (rho2 / c2 + v * alpha) # CIoU 51 | else: # GIoU https://arxiv.org/pdf/1902.09630.pdf 52 | c_area = cw * ch + eps # convex area 53 | return iou - (c_area - union) / c_area # GIoU 54 | else: 55 | return iou # IoU 56 | 57 | 58 | def compute_loss(predictions, targets, model): 59 | # Check which device was used 60 | device = targets.device 61 | 62 | # Add placeholder varables for the different losses 63 | lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device) 64 | 65 | # Build yolo targets 66 | tcls, tbox, indices, anchors = build_targets(predictions, targets, model) # targets 67 | 68 | # Define different loss functions classification 69 | BCEcls = nn.BCEWithLogitsLoss( 70 | pos_weight=torch.tensor([1.0], device=device)) 71 | BCEobj = nn.BCEWithLogitsLoss( 72 | pos_weight=torch.tensor([1.0], device=device)) 73 | 74 | # Calculate losses for each yolo layer 75 | for layer_index, layer_predictions in enumerate(predictions): 76 | # Get image ids, anchors, grid index i and j for each target in the current yolo layer 77 | b, anchor, grid_j, grid_i = indices[layer_index] 78 | # Build empty object target tensor with the same shape as the object prediction 79 | tobj = torch.zeros_like(layer_predictions[..., 0], device=device) # target obj 80 | # Get the number of targets for this layer. 81 | # Each target is a label box with some scaling and the association of an anchor box. 82 | # Label boxes may be associated to 0 or multiple anchors. So they are multiple times or not at all in the targets. 83 | num_targets = b.shape[0] 84 | # Check if there are targets for this batch 85 | if num_targets: 86 | # Load the corresponding values from the predictions for each of the targets 87 | ps = layer_predictions[b, anchor, grid_j, grid_i] 88 | 89 | # Regression of the box 90 | # Apply sigmoid to xy offset predictions in each cell that has a target 91 | pxy = ps[:, :2].sigmoid() 92 | # Apply exponent to wh predictions and multiply with the anchor box that matched best with the label for each cell that has a target 93 | pwh = torch.exp(ps[:, 2:4]) * anchors[layer_index] 94 | # Build box out of xy and wh 95 | pbox = torch.cat((pxy, pwh), 1) 96 | # Calculate CIoU or GIoU for each target with the predicted box for its cell + anchor 97 | iou = bbox_iou(pbox.T, tbox[layer_index], x1y1x2y2=False, CIoU=True) 98 | # We want to minimize our loss so we and the best possible IoU is 1 so we take 1 - IoU and reduce it with a mean 99 | lbox += (1.0 - iou).mean() # iou loss 100 | 101 | # Classification of the objectness 102 | # Fill our empty object target tensor with the IoU we just calculated for each target at the targets position 103 | tobj[b, anchor, grid_j, grid_i] = iou.detach().clamp(0).type(tobj.dtype) # Use cells with iou > 0 as object targets 104 | 105 | # Classification of the class 106 | # Check if we need to do a classification (number of classes > 1) 107 | if ps.size(1) - 5 > 1: 108 | # Hot one class encoding 109 | t = torch.zeros_like(ps[:, 5:], device=device) # targets 110 | t[range(num_targets), tcls[layer_index]] = 1 111 | # Use the tensor to calculate the BCE loss 112 | lcls += BCEcls(ps[:, 5:], t) # BCE 113 | 114 | # Classification of the objectness the sequel 115 | # Calculate the BCE loss between the on the fly generated target and the network prediction 116 | lobj += BCEobj(layer_predictions[..., 4], tobj) # obj loss 117 | 118 | lbox *= 0.05 119 | lobj *= 1.0 120 | lcls *= 0.5 121 | 122 | # Merge losses 123 | loss = lbox + lobj + lcls 124 | 125 | return loss, to_cpu(torch.cat((lbox, lobj, lcls, loss))) 126 | 127 | 128 | def build_targets(p, targets, model): 129 | # Build targets for compute_loss(), input targets(image,class,x,y,w,h) 130 | na, nt = 3, targets.shape[0] # number of anchors, targets #TODO 131 | tcls, tbox, indices, anch = [], [], [], [] 132 | gain = torch.ones(7, device=targets.device) # normalized to gridspace gain 133 | # Make a tensor that iterates 0-2 for 3 anchors and repeat that as many times as we have target boxes 134 | ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) 135 | # Copy target boxes anchor size times and append an anchor index to each copy the anchor index is also expressed by the new first dimension 136 | targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) 137 | 138 | for i, yolo_layer in enumerate(model.yolo_layers): 139 | # Scale anchors by the yolo grid cell size so that an anchor with the size of the cell would result in 1 140 | anchors = yolo_layer.anchors / yolo_layer.stride 141 | # Add the number of yolo cells in this layer the gain tensor 142 | # The gain tensor matches the collums of our targets (img id, class, x, y, w, h, anchor id) 143 | gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain 144 | # Scale targets by the number of yolo layer cells, they are now in the yolo cell coordinate system 145 | t = targets * gain 146 | # Check if we have targets 147 | if nt: 148 | # Calculate ration between anchor and target box for both width and height 149 | r = t[:, :, 4:6] / anchors[:, None] 150 | # Select the ratios that have the highest divergence in any axis and check if the ratio is less than 4 151 | j = torch.max(r, 1. / r).max(2)[0] < 4 # compare #TODO 152 | # Only use targets that have the correct ratios for their anchors 153 | # That means we only keep ones that have a matching anchor and we loose the anchor dimension 154 | # The anchor id is still saved in the 7th value of each target 155 | t = t[j] 156 | else: 157 | t = targets[0] 158 | 159 | # Extract image id in batch and class id 160 | b, c = t[:, :2].long().T 161 | # We isolate the target cell associations. 162 | # x, y, w, h are allready in the cell coordinate system meaning an x = 1.2 would be 1.2 times cellwidth 163 | gxy = t[:, 2:4] 164 | gwh = t[:, 4:6] # grid wh 165 | # Cast to int to get an cell index e.g. 1.2 gets associated to cell 1 166 | gij = gxy.long() 167 | # Isolate x and y index dimensions 168 | gi, gj = gij.T # grid xy indices 169 | 170 | # Convert anchor indexes to int 171 | a = t[:, 6].long() 172 | # Add target tensors for this yolo layer to the output lists 173 | # Add to index list and limit index range to prevent out of bounds 174 | indices.append((b, a, gj.clamp_(0, gain[3].long() - 1), gi.clamp_(0, gain[2].long() - 1))) 175 | # Add to target box list and convert box coordinates from global grid coordinates to local offsets in the grid cell 176 | tbox.append(torch.cat((gxy - gij, gwh), 1)) # box 177 | # Add correct anchor for each target to the list 178 | anch.append(anchors[a]) 179 | # Add class for each target to the list 180 | tcls.append(c) 181 | 182 | return tcls, tbox, indices, anch 183 | -------------------------------------------------------------------------------- /pytorchyolo/utils/parse_config.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def parse_model_config(path): 4 | """Parses the yolo-v3 layer configuration file and returns module definitions""" 5 | file = open(path, 'r') 6 | lines = file.read().split('\n') 7 | lines = [x for x in lines if x and not x.startswith('#')] 8 | lines = [x.rstrip().lstrip() for x in lines] # get rid of fringe whitespaces 9 | module_defs = [] 10 | for line in lines: 11 | if line.startswith('['): # This marks the start of a new block 12 | module_defs.append({}) 13 | module_defs[-1]['type'] = line[1:-1].rstrip() 14 | if module_defs[-1]['type'] == 'convolutional': 15 | module_defs[-1]['batch_normalize'] = 0 16 | else: 17 | key, value = line.split("=") 18 | value = value.strip() 19 | module_defs[-1][key.rstrip()] = value.strip() 20 | 21 | return module_defs 22 | 23 | 24 | def parse_data_config(path): 25 | """Parses the data configuration file""" 26 | options = dict() 27 | options['gpus'] = '0,1,2,3' 28 | options['num_workers'] = '10' 29 | with open(path, 'r') as fp: 30 | lines = fp.readlines() 31 | for line in lines: 32 | line = line.strip() 33 | if line == '' or line.startswith('#'): 34 | continue 35 | key, value = line.split('=') 36 | options[key.strip()] = value.strip() 37 | return options 38 | -------------------------------------------------------------------------------- /pytorchyolo/utils/transforms.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn.functional as F 3 | import numpy as np 4 | 5 | import imgaug.augmenters as iaa 6 | from imgaug.augmentables.bbs import BoundingBox, BoundingBoxesOnImage 7 | 8 | from .utils import xywh2xyxy_np 9 | import torchvision.transforms as transforms 10 | 11 | 12 | class ImgAug(object): 13 | def __init__(self, augmentations=[]): 14 | self.augmentations = augmentations 15 | 16 | def __call__(self, data): 17 | # Unpack data 18 | img, boxes = data 19 | 20 | # Convert xywh to xyxy 21 | boxes = np.array(boxes) 22 | boxes[:, 1:] = xywh2xyxy_np(boxes[:, 1:]) 23 | 24 | # Convert bounding boxes to imgaug 25 | bounding_boxes = BoundingBoxesOnImage( 26 | [BoundingBox(*box[1:], label=box[0]) for box in boxes], 27 | shape=img.shape) 28 | 29 | # Apply augmentations 30 | img, bounding_boxes = self.augmentations( 31 | image=img, 32 | bounding_boxes=bounding_boxes) 33 | 34 | # Clip out of image boxes 35 | bounding_boxes = bounding_boxes.clip_out_of_image() 36 | 37 | # Convert bounding boxes back to numpy 38 | boxes = np.zeros((len(bounding_boxes), 5)) 39 | for box_idx, box in enumerate(bounding_boxes): 40 | # Extract coordinates for unpadded + unscaled image 41 | x1 = box.x1 42 | y1 = box.y1 43 | x2 = box.x2 44 | y2 = box.y2 45 | 46 | # Returns (x, y, w, h) 47 | boxes[box_idx, 0] = box.label 48 | boxes[box_idx, 1] = ((x1 + x2) / 2) 49 | boxes[box_idx, 2] = ((y1 + y2) / 2) 50 | boxes[box_idx, 3] = (x2 - x1) 51 | boxes[box_idx, 4] = (y2 - y1) 52 | 53 | return img, boxes 54 | 55 | 56 | class RelativeLabels(object): 57 | def __init__(self, ): 58 | pass 59 | 60 | def __call__(self, data): 61 | img, boxes = data 62 | h, w, _ = img.shape 63 | boxes[:, [1, 3]] /= w 64 | boxes[:, [2, 4]] /= h 65 | return img, boxes 66 | 67 | 68 | class AbsoluteLabels(object): 69 | def __init__(self, ): 70 | pass 71 | 72 | def __call__(self, data): 73 | img, boxes = data 74 | h, w, _ = img.shape 75 | boxes[:, [1, 3]] *= w 76 | boxes[:, [2, 4]] *= h 77 | return img, boxes 78 | 79 | 80 | class PadSquare(ImgAug): 81 | def __init__(self, ): 82 | self.augmentations = iaa.Sequential([ 83 | iaa.PadToAspectRatio( 84 | 1.0, 85 | position="center-center").to_deterministic() 86 | ]) 87 | 88 | 89 | class ToTensor(object): 90 | def __init__(self, ): 91 | pass 92 | 93 | def __call__(self, data): 94 | img, boxes = data 95 | # Extract image as PyTorch tensor 96 | img = transforms.ToTensor()(img) 97 | 98 | bb_targets = torch.zeros((len(boxes), 6)) 99 | bb_targets[:, 1:] = transforms.ToTensor()(boxes) 100 | 101 | return img, bb_targets 102 | 103 | 104 | class Resize(object): 105 | def __init__(self, size): 106 | self.size = size 107 | 108 | def __call__(self, data): 109 | img, boxes = data 110 | img = F.interpolate(img.unsqueeze(0), size=self.size, mode="nearest").squeeze(0) 111 | return img, boxes 112 | 113 | 114 | DEFAULT_TRANSFORMS = transforms.Compose([ 115 | AbsoluteLabels(), 116 | PadSquare(), 117 | RelativeLabels(), 118 | ToTensor(), 119 | ]) 120 | -------------------------------------------------------------------------------- /pytorchyolo/utils/utils.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | 3 | import time 4 | import platform 5 | import tqdm 6 | import torch 7 | import torch.nn as nn 8 | import torchvision 9 | import numpy as np 10 | import subprocess 11 | import random 12 | import imgaug as ia 13 | 14 | 15 | def provide_determinism(seed=42): 16 | random.seed(seed) 17 | np.random.seed(seed) 18 | torch.manual_seed(seed) 19 | torch.cuda.manual_seed_all(seed) 20 | ia.seed(seed) 21 | 22 | torch.backends.cudnn.benchmark = False 23 | torch.backends.cudnn.deterministic = True 24 | 25 | 26 | def worker_seed_set(worker_id): 27 | # See for details of numpy: 28 | # https://github.com/pytorch/pytorch/issues/5059#issuecomment-817392562 29 | # See for details of random: 30 | # https://pytorch.org/docs/stable/notes/randomness.html#dataloader 31 | 32 | # NumPy 33 | uint64_seed = torch.initial_seed() 34 | ss = np.random.SeedSequence([uint64_seed]) 35 | np.random.seed(ss.generate_state(4)) 36 | 37 | # random 38 | worker_seed = torch.initial_seed() % 2**32 39 | random.seed(worker_seed) 40 | 41 | 42 | def to_cpu(tensor): 43 | return tensor.detach().cpu() 44 | 45 | 46 | def load_classes(path): 47 | """ 48 | Loads class labels at 'path' 49 | """ 50 | with open(path, "r") as fp: 51 | names = fp.read().splitlines() 52 | return names 53 | 54 | 55 | def weights_init_normal(m): 56 | classname = m.__class__.__name__ 57 | if classname.find("Conv") != -1: 58 | nn.init.normal_(m.weight.data, 0.0, 0.02) 59 | elif classname.find("BatchNorm2d") != -1: 60 | nn.init.normal_(m.weight.data, 1.0, 0.02) 61 | nn.init.constant_(m.bias.data, 0.0) 62 | 63 | 64 | def rescale_boxes(boxes, current_dim, original_shape): 65 | """ 66 | Rescales bounding boxes to the original shape 67 | """ 68 | orig_h, orig_w = original_shape 69 | 70 | # The amount of padding that was added 71 | pad_x = max(orig_h - orig_w, 0) * (current_dim / max(original_shape)) 72 | pad_y = max(orig_w - orig_h, 0) * (current_dim / max(original_shape)) 73 | 74 | # Image height and width after padding is removed 75 | unpad_h = current_dim - pad_y 76 | unpad_w = current_dim - pad_x 77 | 78 | # Rescale bounding boxes to dimension of original image 79 | boxes[:, 0] = ((boxes[:, 0] - pad_x // 2) / unpad_w) * orig_w 80 | boxes[:, 1] = ((boxes[:, 1] - pad_y // 2) / unpad_h) * orig_h 81 | boxes[:, 2] = ((boxes[:, 2] - pad_x // 2) / unpad_w) * orig_w 82 | boxes[:, 3] = ((boxes[:, 3] - pad_y // 2) / unpad_h) * orig_h 83 | return boxes 84 | 85 | 86 | def xywh2xyxy(x): 87 | y = x.new(x.shape) 88 | y[..., 0] = x[..., 0] - x[..., 2] / 2 89 | y[..., 1] = x[..., 1] - x[..., 3] / 2 90 | y[..., 2] = x[..., 0] + x[..., 2] / 2 91 | y[..., 3] = x[..., 1] + x[..., 3] / 2 92 | return y 93 | 94 | 95 | def xywh2xyxy_np(x): 96 | y = np.zeros_like(x) 97 | y[..., 0] = x[..., 0] - x[..., 2] / 2 98 | y[..., 1] = x[..., 1] - x[..., 3] / 2 99 | y[..., 2] = x[..., 0] + x[..., 2] / 2 100 | y[..., 3] = x[..., 1] + x[..., 3] / 2 101 | return y 102 | 103 | 104 | def ap_per_class(tp, conf, pred_cls, target_cls): 105 | """ Compute the average precision, given the recall and precision curves. 106 | Source: https://github.com/rafaelpadilla/Object-Detection-Metrics. 107 | # Arguments 108 | tp: True positives (list). 109 | conf: Objectness value from 0-1 (list). 110 | pred_cls: Predicted object classes (list). 111 | target_cls: True object classes (list). 112 | # Returns 113 | The average precision as computed in py-faster-rcnn. 114 | """ 115 | 116 | # Sort by objectness 117 | i = np.argsort(-conf) 118 | tp, conf, pred_cls = tp[i], conf[i], pred_cls[i] 119 | 120 | # Find unique classes 121 | unique_classes = np.unique(target_cls) 122 | 123 | # Create Precision-Recall curve and compute AP for each class 124 | ap, p, r = [], [], [] 125 | for c in tqdm.tqdm(unique_classes, desc="Computing AP"): 126 | i = pred_cls == c 127 | n_gt = (target_cls == c).sum() # Number of ground truth objects 128 | n_p = i.sum() # Number of predicted objects 129 | 130 | if n_p == 0 and n_gt == 0: 131 | continue 132 | elif n_p == 0 or n_gt == 0: 133 | ap.append(0) 134 | r.append(0) 135 | p.append(0) 136 | else: 137 | # Accumulate FPs and TPs 138 | fpc = (1 - tp[i]).cumsum() 139 | tpc = (tp[i]).cumsum() 140 | 141 | # Recall 142 | recall_curve = tpc / (n_gt + 1e-16) 143 | r.append(recall_curve[-1]) 144 | 145 | # Precision 146 | precision_curve = tpc / (tpc + fpc) 147 | p.append(precision_curve[-1]) 148 | 149 | # AP from recall-precision curve 150 | ap.append(compute_ap(recall_curve, precision_curve)) 151 | 152 | # Compute F1 score (harmonic mean of precision and recall) 153 | p, r, ap = np.array(p), np.array(r), np.array(ap) 154 | f1 = 2 * p * r / (p + r + 1e-16) 155 | 156 | return p, r, ap, f1, unique_classes.astype("int32") 157 | 158 | 159 | def compute_ap(recall, precision): 160 | """ Compute the average precision, given the recall and precision curves. 161 | Code originally from https://github.com/rbgirshick/py-faster-rcnn. 162 | 163 | # Arguments 164 | recall: The recall curve (list). 165 | precision: The precision curve (list). 166 | # Returns 167 | The average precision as computed in py-faster-rcnn. 168 | """ 169 | # correct AP calculation 170 | # first append sentinel values at the end 171 | mrec = np.concatenate(([0.0], recall, [1.0])) 172 | mpre = np.concatenate(([0.0], precision, [0.0])) 173 | 174 | # compute the precision envelope 175 | for i in range(mpre.size - 1, 0, -1): 176 | mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i]) 177 | 178 | # to calculate area under PR curve, look for points 179 | # where X axis (recall) changes value 180 | i = np.where(mrec[1:] != mrec[:-1])[0] 181 | 182 | # and sum (\Delta recall) * prec 183 | ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) 184 | return ap 185 | 186 | 187 | def get_batch_statistics(outputs, targets, iou_threshold): 188 | """ Compute true positives, predicted scores and predicted labels per sample """ 189 | batch_metrics = [] 190 | for sample_i in range(len(outputs)): 191 | 192 | if outputs[sample_i] is None: 193 | continue 194 | 195 | output = outputs[sample_i] 196 | pred_boxes = output[:, :4] 197 | pred_scores = output[:, 4] 198 | pred_labels = output[:, -1] 199 | 200 | true_positives = np.zeros(pred_boxes.shape[0]) 201 | 202 | annotations = targets[targets[:, 0] == sample_i][:, 1:] 203 | target_labels = annotations[:, 0] if len(annotations) else [] 204 | if len(annotations): 205 | detected_boxes = [] 206 | target_boxes = annotations[:, 1:] 207 | 208 | for pred_i, (pred_box, pred_label) in enumerate(zip(pred_boxes, pred_labels)): 209 | 210 | # If targets are found break 211 | if len(detected_boxes) == len(annotations): 212 | break 213 | 214 | # Ignore if label is not one of the target labels 215 | if pred_label not in target_labels: 216 | continue 217 | 218 | # Filter target_boxes by pred_label so that we only match against boxes of our own label 219 | filtered_target_position, filtered_targets = zip(*filter(lambda x: target_labels[x[0]] == pred_label, enumerate(target_boxes))) 220 | 221 | # Find the best matching target for our predicted box 222 | iou, box_filtered_index = bbox_iou(pred_box.unsqueeze(0), torch.stack(filtered_targets)).max(0) 223 | 224 | # Remap the index in the list of filtered targets for that label to the index in the list with all targets. 225 | box_index = filtered_target_position[box_filtered_index] 226 | 227 | # Check if the iou is above the min treshold and i 228 | if iou >= iou_threshold and box_index not in detected_boxes: 229 | true_positives[pred_i] = 1 230 | detected_boxes += [box_index] 231 | batch_metrics.append([true_positives, pred_scores, pred_labels]) 232 | return batch_metrics 233 | 234 | 235 | def bbox_wh_iou(wh1, wh2): 236 | wh2 = wh2.t() 237 | w1, h1 = wh1[0], wh1[1] 238 | w2, h2 = wh2[0], wh2[1] 239 | inter_area = torch.min(w1, w2) * torch.min(h1, h2) 240 | union_area = (w1 * h1 + 1e-16) + w2 * h2 - inter_area 241 | return inter_area / union_area 242 | 243 | 244 | def bbox_iou(box1, box2, x1y1x2y2=True): 245 | """ 246 | Returns the IoU of two bounding boxes 247 | """ 248 | if not x1y1x2y2: 249 | # Transform from center and width to exact coordinates 250 | b1_x1, b1_x2 = box1[:, 0] - box1[:, 2] / 2, box1[:, 0] + box1[:, 2] / 2 251 | b1_y1, b1_y2 = box1[:, 1] - box1[:, 3] / 2, box1[:, 1] + box1[:, 3] / 2 252 | b2_x1, b2_x2 = box2[:, 0] - box2[:, 2] / 2, box2[:, 0] + box2[:, 2] / 2 253 | b2_y1, b2_y2 = box2[:, 1] - box2[:, 3] / 2, box2[:, 1] + box2[:, 3] / 2 254 | else: 255 | # Get the coordinates of bounding boxes 256 | b1_x1, b1_y1, b1_x2, b1_y2 = \ 257 | box1[:, 0], box1[:, 1], box1[:, 2], box1[:, 3] 258 | b2_x1, b2_y1, b2_x2, b2_y2 = \ 259 | box2[:, 0], box2[:, 1], box2[:, 2], box2[:, 3] 260 | 261 | # get the corrdinates of the intersection rectangle 262 | inter_rect_x1 = torch.max(b1_x1, b2_x1) 263 | inter_rect_y1 = torch.max(b1_y1, b2_y1) 264 | inter_rect_x2 = torch.min(b1_x2, b2_x2) 265 | inter_rect_y2 = torch.min(b1_y2, b2_y2) 266 | # Intersection area 267 | inter_area = torch.clamp(inter_rect_x2 - inter_rect_x1 + 1, min=0) * torch.clamp( 268 | inter_rect_y2 - inter_rect_y1 + 1, min=0 269 | ) 270 | # Union Area 271 | b1_area = (b1_x2 - b1_x1 + 1) * (b1_y2 - b1_y1 + 1) 272 | b2_area = (b2_x2 - b2_x1 + 1) * (b2_y2 - b2_y1 + 1) 273 | 274 | iou = inter_area / (b1_area + b2_area - inter_area + 1e-16) 275 | 276 | return iou 277 | 278 | 279 | def box_iou(box1, box2): 280 | # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py 281 | """ 282 | Return intersection-over-union (Jaccard index) of boxes. 283 | Both sets of boxes are expected to be in (x1, y1, x2, y2) format. 284 | Arguments: 285 | box1 (Tensor[N, 4]) 286 | box2 (Tensor[M, 4]) 287 | Returns: 288 | iou (Tensor[N, M]): the NxM matrix containing the pairwise 289 | IoU values for every element in boxes1 and boxes2 290 | """ 291 | 292 | def box_area(box): 293 | # box = 4xn 294 | return (box[2] - box[0]) * (box[3] - box[1]) 295 | 296 | area1 = box_area(box1.T) 297 | area2 = box_area(box2.T) 298 | 299 | # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2) 300 | inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - 301 | torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2) 302 | # iou = inter / (area1 + area2 - inter) 303 | return inter / (area1[:, None] + area2 - inter) 304 | 305 | 306 | def non_max_suppression(prediction, conf_thres=0.25, iou_thres=0.45, classes=None): 307 | """Performs Non-Maximum Suppression (NMS) on inference results 308 | Returns: 309 | detections with shape: nx6 (x1, y1, x2, y2, conf, cls) 310 | """ 311 | 312 | nc = prediction.shape[2] - 5 # number of classes 313 | 314 | # Settings 315 | # (pixels) minimum and maximum box width and height 316 | max_wh = 4096 317 | max_det = 300 # maximum number of detections per image 318 | max_nms = 30000 # maximum number of boxes into torchvision.ops.nms() 319 | time_limit = 1.0 # seconds to quit after 320 | multi_label = nc > 1 # multiple labels per box (adds 0.5ms/img) 321 | 322 | t = time.time() 323 | output = [torch.zeros((0, 6), device="cpu")] * prediction.shape[0] 324 | 325 | for xi, x in enumerate(prediction): # image index, image inference 326 | # Apply constraints 327 | # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height 328 | x = x[x[..., 4] > conf_thres] # confidence 329 | 330 | # If none remain process next image 331 | if not x.shape[0]: 332 | continue 333 | 334 | # Compute conf 335 | x[:, 5:] *= x[:, 4:5] # conf = obj_conf * cls_conf 336 | 337 | # Box (center x, center y, width, height) to (x1, y1, x2, y2) 338 | box = xywh2xyxy(x[:, :4]) 339 | 340 | # Detections matrix nx6 (xyxy, conf, cls) 341 | if multi_label: 342 | i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T 343 | x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1) 344 | else: # best class only 345 | conf, j = x[:, 5:].max(1, keepdim=True) 346 | x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres] 347 | 348 | # Filter by class 349 | if classes is not None: 350 | x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)] 351 | 352 | # Check shape 353 | n = x.shape[0] # number of boxes 354 | if not n: # no boxes 355 | continue 356 | elif n > max_nms: # excess boxes 357 | # sort by confidence 358 | x = x[x[:, 4].argsort(descending=True)[:max_nms]] 359 | 360 | # Batched NMS 361 | c = x[:, 5:6] * max_wh # classes 362 | # boxes (offset by class), scores 363 | boxes, scores = x[:, :4] + c, x[:, 4] 364 | i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS 365 | if i.shape[0] > max_det: # limit detections 366 | i = i[:max_det] 367 | 368 | output[xi] = to_cpu(x[i]) 369 | 370 | if (time.time() - t) > time_limit: 371 | print(f'WARNING: NMS time limit {time_limit}s exceeded') 372 | break # time limit exceeded 373 | 374 | return output 375 | 376 | 377 | def print_environment_info(): 378 | """ 379 | Prints infos about the environment and the system. 380 | This should help when people make issues containg the printout. 381 | """ 382 | 383 | print("Environment information:") 384 | 385 | # Print OS information 386 | print(f"System: {platform.system()} {platform.release()}") 387 | 388 | # Print poetry package version 389 | try: 390 | print(f"Current Version: {subprocess.check_output(['poetry', 'version'], stderr=subprocess.DEVNULL).decode('ascii').strip()}") 391 | except (subprocess.CalledProcessError, FileNotFoundError): 392 | print("Not using the poetry package") 393 | 394 | # Print commit hash if possible 395 | try: 396 | print(f"Current Commit Hash: {subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'], stderr=subprocess.DEVNULL).decode('ascii').strip()}") 397 | except (subprocess.CalledProcessError, FileNotFoundError): 398 | print("No git or repo found") 399 | -------------------------------------------------------------------------------- /weights/download_weights.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Download weights for vanilla YOLOv3 3 | wget -c "https://pjreddie.com/media/files/yolov3.weights" --header "Referer: pjreddie.com" 4 | # # Download weights for tiny YOLOv3 5 | wget -c "https://pjreddie.com/media/files/yolov3-tiny.weights" --header "Referer: pjreddie.com" 6 | # Download weights for backbone network 7 | wget -c "https://pjreddie.com/media/files/darknet53.conv.74" --header "Referer: pjreddie.com" 8 | --------------------------------------------------------------------------------