├── .gitignore ├── LICENSE ├── README.md ├── mask_rcnn.py ├── results ├── network_structure.png ├── res1.png └── res2.png ├── test.py ├── train.py └── utils ├── coco_eval.py ├── coco_utils.py ├── dataset.py ├── engine.py ├── model.py ├── transforms.py └── utils.py /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__/ 2 | -------------------------------------------------------------------------------- /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 | # Mask-RCNN-pytorch 2 | Pytorch implementation of [Mask-RCNN](https://arxiv.org/abs/1703.06870) based on torchvision model with VOC dataset format. The model generates segmentation masks and their scores for each instance of an object in the image. This repository is based on [TorchVision Object Detection Finetuning Tutorial](https://pytorch.org/tutorials/intermediate/torchvision_tutorial.html). 3 | 4 | ![Network Structure](results/network_structure.png) 5 | 6 | ## Training 7 | 8 | label your data with [labelme](https://github.com/wkentaro/labelme) and Export VOC-format dataset from json files with [labelme2voc](https://github.com/wkentaro/labelme/tree/master/examples/instance_segmentation). 9 | 10 | Prepare your dataset in this format: 11 | ``` 12 | my_dataset 13 | ├── labels.txt 14 | │ 15 | ├── JPEGImages 16 | │ ├── image1.jpg 17 | │ └── image2.jpg 18 | │ 19 | ├── SegmentationObject 20 | │ ├── image1.png 21 | │ └── image2.png 22 | │ 23 | └── SegmentationClass 24 | ├── image1.png 25 | └── image2.png 26 | ``` 27 | Clone the repository and put ```my_dataset``` folder in ```Mask-RCNN-pytorch``` folder then use this line of code to train: 28 | ``` 29 | $ python3 train.py --data my_dataset --num_classes 11 --num_epochs 150 30 | ``` 31 | Enter ```num_classes``` including background. 32 | 33 | ## Testing 34 | Enter your class names using ```classes``` variable in ```mask_rcnn.py``` then use this line of code to test on your image: 35 | ``` 36 | $ python3 test.py --img test_img.jpg --model ./maskrcnn_saved_models/mask_rcnn_model.pt 37 | ``` 38 | Here are some output results: 39 | 40 | ![res1](results/res1.png) ![res2](results/res2.png) 41 | 42 | -------------------------------------------------------------------------------- /mask_rcnn.py: -------------------------------------------------------------------------------- 1 | ############################################### 2 | # pytorch Mask-RCNN based on torchvision model 3 | # Amirhossein Heydarian 4 | ############################################### 5 | 6 | import torch 7 | import torchvision 8 | from torchvision.models.detection.faster_rcnn import FastRCNNPredictor 9 | from torchvision.models.detection.mask_rcnn import MaskRCNNPredictor 10 | from torchvision.transforms import functional as F 11 | import cv2 12 | import numpy as np 13 | 14 | device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') 15 | font = cv2.FONT_HERSHEY_SIMPLEX 16 | fontScale = 2 17 | thickness = 3 18 | 19 | 20 | def get_instance_segmentation_model(num_classes): 21 | # load an instance segmentation model pre-trained on COCO 22 | model = torchvision.models.detection.maskrcnn_resnet50_fpn() 23 | 24 | # get the number of input features for the classifier 25 | in_features = model.roi_heads.box_predictor.cls_score.in_features 26 | # replace the pre-trained head with a new one 27 | model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes) 28 | 29 | # now get the number of input features for the mask classifier 30 | in_features_mask = model.roi_heads.mask_predictor.conv5_mask.in_channels 31 | hidden_layer = 256 32 | # and replace the mask predictor with a new one 33 | model.roi_heads.mask_predictor = MaskRCNNPredictor(in_features_mask, 34 | hidden_layer, 35 | num_classes) 36 | return model 37 | 38 | class segmentation_model(): 39 | def __init__(self, model_path, num_classes): 40 | self.model = get_instance_segmentation_model(num_classes).to(device) 41 | self.model.load_state_dict(torch.load(model_path)) 42 | self.model.eval() 43 | 44 | def detect_masks(self,image,rgb_image): 45 | if not(rgb_image): 46 | image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) 47 | img = F.to_tensor(image) 48 | with torch.no_grad(): 49 | prediction = self.model([img.to(device)]) 50 | return prediction[0] 51 | 52 | def plot_masks(image, prediction, classes, th=.2): 53 | masks = prediction['masks'][:, 0].cpu().detach().numpy()[np.where(prediction['scores'].cpu().detach().numpy()>th)] 54 | masks[masks=th] = 1.0 56 | labels = prediction['labels'].cpu().numpy()[np.where(prediction['scores'].cpu().detach().numpy()>th)] 57 | scores = np.round(prediction['scores'].cpu().detach().numpy()[np.where(prediction['scores'].cpu().detach().numpy()>th)],2) 58 | 59 | copy_image = image.copy() 60 | alpha = 0.5 61 | for i in range(masks.shape[0]): 62 | color = (np.random.randint(255),np.random.randint(255),np.random.randint(255)) 63 | for c in range(3): 64 | copy_image[:, :, c] = np.where(masks[i] == 1.0, copy_image[:, :, c] * (1 - alpha) + alpha*color[c], copy_image[:, :, c]) 65 | 66 | #adding classes 67 | args = np.where(masks[i]>0) 68 | ymin,ymax,xmin,xmax = args[0].min(),args[0].max(),args[1].min(),args[1].max() 69 | copy_image = cv2.putText(copy_image, '{} ({})'.format(classes[int(labels[i])],str(scores[i])), (xmin+10, ymin+10), font, fontScale, (0,0,0), thickness, cv2.LINE_AA) 70 | return copy_image -------------------------------------------------------------------------------- /results/network_structure.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/4-geeks/Mask-RCNN-pytorch/ab2b28036e18d017fb2b3ff33307db64e38e88b9/results/network_structure.png -------------------------------------------------------------------------------- /results/res1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/4-geeks/Mask-RCNN-pytorch/ab2b28036e18d017fb2b3ff33307db64e38e88b9/results/res1.png -------------------------------------------------------------------------------- /results/res2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/4-geeks/Mask-RCNN-pytorch/ab2b28036e18d017fb2b3ff33307db64e38e88b9/results/res2.png -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | import os 2 | import cv2 3 | import argparse 4 | import matplotlib.pyplot as plt 5 | from mask_rcnn import segmentation_model, plot_masks 6 | 7 | if __name__ == '__main__': 8 | parser = argparse.ArgumentParser() 9 | parser.add_argument('--img', type=str, default='test_image.jpg', help='path to your test image') 10 | parser.add_argument('--labels', type=str, default='./my_dataset/labels.txt', help='path to labels list text file (labels.txt)') 11 | parser.add_argument('--model', type=str, default='./maskrcnn_saved_models/mask_rcnn_model.pt', help='path to saved model') 12 | 13 | args = parser.parse_args() 14 | 15 | IMAGE_PATH = args.img 16 | MODEL_PATH = args.model 17 | LABEL_PATH = args.labels 18 | 19 | with open(LABEL_PATH,'r') as f: 20 | lines = [line.rstrip() for line in f] 21 | assert lines[0] == '__ignore__', """first line of labels file must be \ 22 | "__ignore__" (labelme labels.txt)""" 23 | lines.pop(0) # remove first elements [__ignore__] 24 | 25 | num_classes = len(lines) 26 | classes = dict(zip(range(num_classes),lines)) 27 | 28 | image = cv2.imread(IMAGE_PATH) 29 | model = segmentation_model(MODEL_PATH,num_classes) 30 | pred = model.detect_masks(image, rgb_image=False) # rgb_image=False if loading image with cv2.imread() 31 | 32 | plotted = plot_masks(image,pred,classes) 33 | 34 | os.makedirs('./results', exist_ok=True) 35 | cv2.imwrite('./results/res.jpg', plotted) 36 | 37 | plt.figure(figsize=(16,12)) 38 | plt.imshow(plotted) 39 | plt.show() -------------------------------------------------------------------------------- /train.py: -------------------------------------------------------------------------------- 1 | import os 2 | import torch 3 | import argparse 4 | 5 | import utils.utils 6 | from utils.engine import train_one_epoch, evaluate 7 | from utils.dataset import maskrcnn_Dataset, get_transform 8 | from utils.model import get_instance_segmentation_model 9 | 10 | 11 | if __name__ == '__main__': 12 | parser = argparse.ArgumentParser() 13 | parser.add_argument('--data', type=str, default='my_dataset', help='dataset path') 14 | parser.add_argument('--num_classes', type=int, default=11, help='number of classes (background as a class)') 15 | parser.add_argument('--num_epochs', type=int, default=150, help='number of epochs') 16 | parser.add_argument('--batchsize', type=int, default=4, help='batchsize') 17 | parser.add_argument('--workers', type=int, default=4, help='number of workers') 18 | 19 | device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') 20 | args = parser.parse_args() 21 | 22 | DATASET_PATH = args.data 23 | num_classes = args.num_classes 24 | num_epochs = args.num_epochs 25 | batchsize = args.batchsize 26 | workers = args.workers 27 | 28 | 29 | #DATASET 30 | # use our dataset and defined transformations 31 | dataset = maskrcnn_Dataset(DATASET_PATH, get_transform(train=True)) 32 | dataset_test = maskrcnn_Dataset(DATASET_PATH, get_transform(train=False)) 33 | 34 | # split the dataset in train and test set 35 | torch.manual_seed(1) 36 | indices = torch.randperm(len(dataset)).tolist() 37 | dataset = torch.utils.data.Subset(dataset, indices[:-int(0.3*len(dataset))]) 38 | dataset_test = torch.utils.data.Subset(dataset_test, indices[-int(0.3*len(dataset)):]) 39 | 40 | print('number of train data :', len(dataset)) 41 | print('number of test data :', len(dataset_test)) 42 | 43 | # define training and validation data loaders 44 | data_loader = torch.utils.data.DataLoader( 45 | dataset, batch_size=batchsize, shuffle=True, num_workers=workers, 46 | collate_fn=utils.utils.collate_fn) 47 | 48 | data_loader_test = torch.utils.data.DataLoader( 49 | dataset_test, batch_size=1, shuffle=False, num_workers=workers, 50 | collate_fn=utils.utils.collate_fn) 51 | 52 | 53 | # MASK-RCNN MODEL 54 | # get the model using our helper function 55 | model = get_instance_segmentation_model(num_classes).to(device) 56 | 57 | # construct an optimizer 58 | params = [p for p in model.parameters() if p.requires_grad] 59 | optimizer = torch.optim.SGD(params, lr=0.005, 60 | momentum=0.9, weight_decay=0.0005) 61 | 62 | # and a learning rate scheduler which decreases the learning rate by 63 | # 10x every 3 epochs 64 | lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, 65 | step_size=15, 66 | gamma=0.1) 67 | 68 | # TRAINING LOOP 69 | 70 | save_fr = 1 71 | print_freq = 25 # make sure that print_freq is smaller than len(dataset) & len(dataset_test) 72 | os.makedirs('./maskrcnn_saved_models', exist_ok=True) 73 | 74 | for epoch in range(num_epochs): 75 | # train for one epoch, printing every 10 iterations 76 | train_one_epoch(model, optimizer, data_loader, device, epoch, print_freq=print_freq) 77 | if epoch%save_fr == 0: 78 | torch.save(model.state_dict(), './maskrcnn_saved_models/mask_rcnn_model_epoch_{}.pt'.format(str(epoch))) 79 | # update the learning rate 80 | lr_scheduler.step() 81 | # evaluate on the test dataset 82 | evaluate(model, data_loader_test, device=device) -------------------------------------------------------------------------------- /utils/coco_eval.py: -------------------------------------------------------------------------------- 1 | import json 2 | import tempfile 3 | 4 | import numpy as np 5 | import copy 6 | import time 7 | import torch 8 | import torch._six 9 | 10 | from pycocotools.cocoeval import COCOeval 11 | from pycocotools.coco import COCO 12 | import pycocotools.mask as mask_util 13 | 14 | from collections import defaultdict 15 | 16 | import utils.utils as utils 17 | 18 | 19 | class CocoEvaluator(object): 20 | def __init__(self, coco_gt, iou_types): 21 | assert isinstance(iou_types, (list, tuple)) 22 | coco_gt = copy.deepcopy(coco_gt) 23 | self.coco_gt = coco_gt 24 | 25 | self.iou_types = iou_types 26 | self.coco_eval = {} 27 | for iou_type in iou_types: 28 | self.coco_eval[iou_type] = COCOeval(coco_gt, iouType=iou_type) 29 | 30 | self.img_ids = [] 31 | self.eval_imgs = {k: [] for k in iou_types} 32 | 33 | def update(self, predictions): 34 | img_ids = list(np.unique(list(predictions.keys()))) 35 | self.img_ids.extend(img_ids) 36 | 37 | for iou_type in self.iou_types: 38 | results = self.prepare(predictions, iou_type) 39 | coco_dt = loadRes(self.coco_gt, results) if results else COCO() 40 | coco_eval = self.coco_eval[iou_type] 41 | 42 | coco_eval.cocoDt = coco_dt 43 | coco_eval.params.imgIds = list(img_ids) 44 | img_ids, eval_imgs = evaluate(coco_eval) 45 | 46 | self.eval_imgs[iou_type].append(eval_imgs) 47 | 48 | def synchronize_between_processes(self): 49 | for iou_type in self.iou_types: 50 | self.eval_imgs[iou_type] = np.concatenate(self.eval_imgs[iou_type], 2) 51 | create_common_coco_eval(self.coco_eval[iou_type], self.img_ids, self.eval_imgs[iou_type]) 52 | 53 | def accumulate(self): 54 | for coco_eval in self.coco_eval.values(): 55 | coco_eval.accumulate() 56 | 57 | def summarize(self): 58 | for iou_type, coco_eval in self.coco_eval.items(): 59 | print("IoU metric: {}".format(iou_type)) 60 | coco_eval.summarize() 61 | 62 | def prepare(self, predictions, iou_type): 63 | if iou_type == "bbox": 64 | return self.prepare_for_coco_detection(predictions) 65 | elif iou_type == "segm": 66 | return self.prepare_for_coco_segmentation(predictions) 67 | elif iou_type == "keypoints": 68 | return self.prepare_for_coco_keypoint(predictions) 69 | else: 70 | raise ValueError("Unknown iou type {}".format(iou_type)) 71 | 72 | def prepare_for_coco_detection(self, predictions): 73 | coco_results = [] 74 | for original_id, prediction in predictions.items(): 75 | if len(prediction) == 0: 76 | continue 77 | 78 | boxes = prediction["boxes"] 79 | boxes = convert_to_xywh(boxes).tolist() 80 | scores = prediction["scores"].tolist() 81 | labels = prediction["labels"].tolist() 82 | 83 | coco_results.extend( 84 | [ 85 | { 86 | "image_id": original_id, 87 | "category_id": labels[k], 88 | "bbox": box, 89 | "score": scores[k], 90 | } 91 | for k, box in enumerate(boxes) 92 | ] 93 | ) 94 | return coco_results 95 | 96 | def prepare_for_coco_segmentation(self, predictions): 97 | coco_results = [] 98 | for original_id, prediction in predictions.items(): 99 | if len(prediction) == 0: 100 | continue 101 | 102 | scores = prediction["scores"] 103 | labels = prediction["labels"] 104 | masks = prediction["masks"] 105 | 106 | masks = masks > 0.5 107 | 108 | scores = prediction["scores"].tolist() 109 | labels = prediction["labels"].tolist() 110 | 111 | rles = [ 112 | mask_util.encode(np.array(mask[0, :, :, np.newaxis], order="F"))[0] 113 | for mask in masks 114 | ] 115 | for rle in rles: 116 | rle["counts"] = rle["counts"].decode("utf-8") 117 | 118 | coco_results.extend( 119 | [ 120 | { 121 | "image_id": original_id, 122 | "category_id": labels[k], 123 | "segmentation": rle, 124 | "score": scores[k], 125 | } 126 | for k, rle in enumerate(rles) 127 | ] 128 | ) 129 | return coco_results 130 | 131 | def prepare_for_coco_keypoint(self, predictions): 132 | coco_results = [] 133 | for original_id, prediction in predictions.items(): 134 | if len(prediction) == 0: 135 | continue 136 | 137 | boxes = prediction["boxes"] 138 | boxes = convert_to_xywh(boxes).tolist() 139 | scores = prediction["scores"].tolist() 140 | labels = prediction["labels"].tolist() 141 | keypoints = prediction["keypoints"] 142 | keypoints = keypoints.flatten(start_dim=1).tolist() 143 | 144 | coco_results.extend( 145 | [ 146 | { 147 | "image_id": original_id, 148 | "category_id": labels[k], 149 | 'keypoints': keypoint, 150 | "score": scores[k], 151 | } 152 | for k, keypoint in enumerate(keypoints) 153 | ] 154 | ) 155 | return coco_results 156 | 157 | 158 | def convert_to_xywh(boxes): 159 | xmin, ymin, xmax, ymax = boxes.unbind(1) 160 | return torch.stack((xmin, ymin, xmax - xmin, ymax - ymin), dim=1) 161 | 162 | 163 | def merge(img_ids, eval_imgs): 164 | all_img_ids = utils.all_gather(img_ids) 165 | all_eval_imgs = utils.all_gather(eval_imgs) 166 | 167 | merged_img_ids = [] 168 | for p in all_img_ids: 169 | merged_img_ids.extend(p) 170 | 171 | merged_eval_imgs = [] 172 | for p in all_eval_imgs: 173 | merged_eval_imgs.append(p) 174 | 175 | merged_img_ids = np.array(merged_img_ids) 176 | merged_eval_imgs = np.concatenate(merged_eval_imgs, 2) 177 | 178 | # keep only unique (and in sorted order) images 179 | merged_img_ids, idx = np.unique(merged_img_ids, return_index=True) 180 | merged_eval_imgs = merged_eval_imgs[..., idx] 181 | 182 | return merged_img_ids, merged_eval_imgs 183 | 184 | 185 | def create_common_coco_eval(coco_eval, img_ids, eval_imgs): 186 | img_ids, eval_imgs = merge(img_ids, eval_imgs) 187 | img_ids = list(img_ids) 188 | eval_imgs = list(eval_imgs.flatten()) 189 | 190 | coco_eval.evalImgs = eval_imgs 191 | coco_eval.params.imgIds = img_ids 192 | coco_eval._paramsEval = copy.deepcopy(coco_eval.params) 193 | 194 | 195 | ################################################################# 196 | # From pycocotools, just removed the prints and fixed 197 | # a Python3 bug about unicode not defined 198 | ################################################################# 199 | 200 | # Ideally, pycocotools wouldn't have hard-coded prints 201 | # so that we could avoid copy-pasting those two functions 202 | 203 | def createIndex(self): 204 | # create index 205 | # print('creating index...') 206 | anns, cats, imgs = {}, {}, {} 207 | imgToAnns, catToImgs = defaultdict(list), defaultdict(list) 208 | if 'annotations' in self.dataset: 209 | for ann in self.dataset['annotations']: 210 | imgToAnns[ann['image_id']].append(ann) 211 | anns[ann['id']] = ann 212 | 213 | if 'images' in self.dataset: 214 | for img in self.dataset['images']: 215 | imgs[img['id']] = img 216 | 217 | if 'categories' in self.dataset: 218 | for cat in self.dataset['categories']: 219 | cats[cat['id']] = cat 220 | 221 | if 'annotations' in self.dataset and 'categories' in self.dataset: 222 | for ann in self.dataset['annotations']: 223 | catToImgs[ann['category_id']].append(ann['image_id']) 224 | 225 | # print('index created!') 226 | 227 | # create class members 228 | self.anns = anns 229 | self.imgToAnns = imgToAnns 230 | self.catToImgs = catToImgs 231 | self.imgs = imgs 232 | self.cats = cats 233 | 234 | 235 | maskUtils = mask_util 236 | 237 | 238 | def loadRes(self, resFile): 239 | """ 240 | Load result file and return a result api object. 241 | :param resFile (str) : file name of result file 242 | :return: res (obj) : result api object 243 | """ 244 | res = COCO() 245 | res.dataset['images'] = [img for img in self.dataset['images']] 246 | 247 | # print('Loading and preparing results...') 248 | # tic = time.time() 249 | if isinstance(resFile, torch._six.string_classes): 250 | anns = json.load(open(resFile)) 251 | elif type(resFile) == np.ndarray: 252 | anns = self.loadNumpyAnnotations(resFile) 253 | else: 254 | anns = resFile 255 | assert type(anns) == list, 'results in not an array of objects' 256 | annsImgIds = [ann['image_id'] for ann in anns] 257 | assert set(annsImgIds) == (set(annsImgIds) & set(self.getImgIds())), \ 258 | 'Results do not correspond to current coco set' 259 | if 'caption' in anns[0]: 260 | imgIds = set([img['id'] for img in res.dataset['images']]) & set([ann['image_id'] for ann in anns]) 261 | res.dataset['images'] = [img for img in res.dataset['images'] if img['id'] in imgIds] 262 | for id, ann in enumerate(anns): 263 | ann['id'] = id + 1 264 | elif 'bbox' in anns[0] and not anns[0]['bbox'] == []: 265 | res.dataset['categories'] = copy.deepcopy(self.dataset['categories']) 266 | for id, ann in enumerate(anns): 267 | bb = ann['bbox'] 268 | x1, x2, y1, y2 = [bb[0], bb[0] + bb[2], bb[1], bb[1] + bb[3]] 269 | if 'segmentation' not in ann: 270 | ann['segmentation'] = [[x1, y1, x1, y2, x2, y2, x2, y1]] 271 | ann['area'] = bb[2] * bb[3] 272 | ann['id'] = id + 1 273 | ann['iscrowd'] = 0 274 | elif 'segmentation' in anns[0]: 275 | res.dataset['categories'] = copy.deepcopy(self.dataset['categories']) 276 | for id, ann in enumerate(anns): 277 | # now only support compressed RLE format as segmentation results 278 | ann['area'] = maskUtils.area(ann['segmentation']) 279 | if 'bbox' not in ann: 280 | ann['bbox'] = maskUtils.toBbox(ann['segmentation']) 281 | ann['id'] = id + 1 282 | ann['iscrowd'] = 0 283 | elif 'keypoints' in anns[0]: 284 | res.dataset['categories'] = copy.deepcopy(self.dataset['categories']) 285 | for id, ann in enumerate(anns): 286 | s = ann['keypoints'] 287 | x = s[0::3] 288 | y = s[1::3] 289 | x0, x1, y0, y1 = np.min(x), np.max(x), np.min(y), np.max(y) 290 | ann['area'] = (x1 - x0) * (y1 - y0) 291 | ann['id'] = id + 1 292 | ann['bbox'] = [x0, y0, x1 - x0, y1 - y0] 293 | # print('DONE (t={:0.2f}s)'.format(time.time()- tic)) 294 | 295 | res.dataset['annotations'] = anns 296 | createIndex(res) 297 | return res 298 | 299 | 300 | def evaluate(self): 301 | ''' 302 | Run per image evaluation on given images and store results (a list of dict) in self.evalImgs 303 | :return: None 304 | ''' 305 | # tic = time.time() 306 | # print('Running per image evaluation...') 307 | p = self.params 308 | # add backward compatibility if useSegm is specified in params 309 | if p.useSegm is not None: 310 | p.iouType = 'segm' if p.useSegm == 1 else 'bbox' 311 | print('useSegm (deprecated) is not None. Running {} evaluation'.format(p.iouType)) 312 | # print('Evaluate annotation type *{}*'.format(p.iouType)) 313 | p.imgIds = list(np.unique(p.imgIds)) 314 | if p.useCats: 315 | p.catIds = list(np.unique(p.catIds)) 316 | p.maxDets = sorted(p.maxDets) 317 | self.params = p 318 | 319 | self._prepare() 320 | # loop through images, area range, max detection number 321 | catIds = p.catIds if p.useCats else [-1] 322 | 323 | if p.iouType == 'segm' or p.iouType == 'bbox': 324 | computeIoU = self.computeIoU 325 | elif p.iouType == 'keypoints': 326 | computeIoU = self.computeOks 327 | self.ious = { 328 | (imgId, catId): computeIoU(imgId, catId) 329 | for imgId in p.imgIds 330 | for catId in catIds} 331 | 332 | evaluateImg = self.evaluateImg 333 | maxDet = p.maxDets[-1] 334 | evalImgs = [ 335 | evaluateImg(imgId, catId, areaRng, maxDet) 336 | for catId in catIds 337 | for areaRng in p.areaRng 338 | for imgId in p.imgIds 339 | ] 340 | # this is NOT in the pycocotools code, but could be done outside 341 | evalImgs = np.asarray(evalImgs).reshape(len(catIds), len(p.areaRng), len(p.imgIds)) 342 | self._paramsEval = copy.deepcopy(self.params) 343 | # toc = time.time() 344 | # print('DONE (t={:0.2f}s).'.format(toc-tic)) 345 | return p.imgIds, evalImgs 346 | 347 | ################################################################# 348 | # end of straight copy from pycocotools, just removing the prints 349 | ################################################################# 350 | -------------------------------------------------------------------------------- /utils/coco_utils.py: -------------------------------------------------------------------------------- 1 | import copy 2 | import os 3 | from PIL import Image 4 | 5 | import torch 6 | import torch.utils.data 7 | import torchvision 8 | 9 | from pycocotools import mask as coco_mask 10 | from pycocotools.coco import COCO 11 | 12 | import utils.transforms as T 13 | 14 | 15 | class FilterAndRemapCocoCategories(object): 16 | def __init__(self, categories, remap=True): 17 | self.categories = categories 18 | self.remap = remap 19 | 20 | def __call__(self, image, target): 21 | anno = target["annotations"] 22 | anno = [obj for obj in anno if obj["category_id"] in self.categories] 23 | if not self.remap: 24 | target["annotations"] = anno 25 | return image, target 26 | anno = copy.deepcopy(anno) 27 | for obj in anno: 28 | obj["category_id"] = self.categories.index(obj["category_id"]) 29 | target["annotations"] = anno 30 | return image, target 31 | 32 | 33 | def convert_coco_poly_to_mask(segmentations, height, width): 34 | masks = [] 35 | for polygons in segmentations: 36 | rles = coco_mask.frPyObjects(polygons, height, width) 37 | mask = coco_mask.decode(rles) 38 | if len(mask.shape) < 3: 39 | mask = mask[..., None] 40 | mask = torch.as_tensor(mask, dtype=torch.uint8) 41 | mask = mask.any(dim=2) 42 | masks.append(mask) 43 | if masks: 44 | masks = torch.stack(masks, dim=0) 45 | else: 46 | masks = torch.zeros((0, height, width), dtype=torch.uint8) 47 | return masks 48 | 49 | 50 | class ConvertCocoPolysToMask(object): 51 | def __call__(self, image, target): 52 | w, h = image.size 53 | 54 | image_id = target["image_id"] 55 | image_id = torch.tensor([image_id]) 56 | 57 | anno = target["annotations"] 58 | 59 | anno = [obj for obj in anno if obj['iscrowd'] == 0] 60 | 61 | boxes = [obj["bbox"] for obj in anno] 62 | # guard against no boxes via resizing 63 | boxes = torch.as_tensor(boxes, dtype=torch.float32).reshape(-1, 4) 64 | boxes[:, 2:] += boxes[:, :2] 65 | boxes[:, 0::2].clamp_(min=0, max=w) 66 | boxes[:, 1::2].clamp_(min=0, max=h) 67 | 68 | classes = [obj["category_id"] for obj in anno] 69 | classes = torch.tensor(classes, dtype=torch.int64) 70 | 71 | segmentations = [obj["segmentation"] for obj in anno] 72 | masks = convert_coco_poly_to_mask(segmentations, h, w) 73 | 74 | keypoints = None 75 | if anno and "keypoints" in anno[0]: 76 | keypoints = [obj["keypoints"] for obj in anno] 77 | keypoints = torch.as_tensor(keypoints, dtype=torch.float32) 78 | num_keypoints = keypoints.shape[0] 79 | if num_keypoints: 80 | keypoints = keypoints.view(num_keypoints, -1, 3) 81 | 82 | keep = (boxes[:, 3] > boxes[:, 1]) & (boxes[:, 2] > boxes[:, 0]) 83 | boxes = boxes[keep] 84 | classes = classes[keep] 85 | masks = masks[keep] 86 | if keypoints is not None: 87 | keypoints = keypoints[keep] 88 | 89 | target = {} 90 | target["boxes"] = boxes 91 | target["labels"] = classes 92 | target["masks"] = masks 93 | target["image_id"] = image_id 94 | if keypoints is not None: 95 | target["keypoints"] = keypoints 96 | 97 | # for conversion to coco api 98 | area = torch.tensor([obj["area"] for obj in anno]) 99 | iscrowd = torch.tensor([obj["iscrowd"] for obj in anno]) 100 | target["area"] = area 101 | target["iscrowd"] = iscrowd 102 | 103 | return image, target 104 | 105 | 106 | def _coco_remove_images_without_annotations(dataset, cat_list=None): 107 | def _has_only_empty_bbox(anno): 108 | return all(any(o <= 1 for o in obj["bbox"][2:]) for obj in anno) 109 | 110 | def _count_visible_keypoints(anno): 111 | return sum(sum(1 for v in ann["keypoints"][2::3] if v > 0) for ann in anno) 112 | 113 | min_keypoints_per_image = 10 114 | 115 | def _has_valid_annotation(anno): 116 | # if it's empty, there is no annotation 117 | if len(anno) == 0: 118 | return False 119 | # if all boxes have close to zero area, there is no annotation 120 | if _has_only_empty_bbox(anno): 121 | return False 122 | # keypoints task have a slight different critera for considering 123 | # if an annotation is valid 124 | if "keypoints" not in anno[0]: 125 | return True 126 | # for keypoint detection tasks, only consider valid images those 127 | # containing at least min_keypoints_per_image 128 | if _count_visible_keypoints(anno) >= min_keypoints_per_image: 129 | return True 130 | return False 131 | 132 | assert isinstance(dataset, torchvision.datasets.CocoDetection) 133 | ids = [] 134 | for ds_idx, img_id in enumerate(dataset.ids): 135 | ann_ids = dataset.coco.getAnnIds(imgIds=img_id, iscrowd=None) 136 | anno = dataset.coco.loadAnns(ann_ids) 137 | if cat_list: 138 | anno = [obj for obj in anno if obj["category_id"] in cat_list] 139 | if _has_valid_annotation(anno): 140 | ids.append(ds_idx) 141 | 142 | dataset = torch.utils.data.Subset(dataset, ids) 143 | return dataset 144 | 145 | 146 | def convert_to_coco_api(ds): 147 | coco_ds = COCO() 148 | ann_id = 0 149 | dataset = {'images': [], 'categories': [], 'annotations': []} 150 | categories = set() 151 | for img_idx in range(len(ds)): 152 | # find better way to get target 153 | # targets = ds.get_annotations(img_idx) 154 | img, targets = ds[img_idx] 155 | image_id = targets["image_id"].item() 156 | img_dict = {} 157 | img_dict['id'] = image_id 158 | img_dict['height'] = img.shape[-2] 159 | img_dict['width'] = img.shape[-1] 160 | dataset['images'].append(img_dict) 161 | bboxes = targets["boxes"] 162 | bboxes[:, 2:] -= bboxes[:, :2] 163 | bboxes = bboxes.tolist() 164 | labels = targets['labels'].tolist() 165 | areas = targets['area'].tolist() 166 | iscrowd = targets['iscrowd'].tolist() 167 | if 'masks' in targets: 168 | masks = targets['masks'] 169 | # make masks Fortran contiguous for coco_mask 170 | masks = masks.permute(0, 2, 1).contiguous().permute(0, 2, 1) 171 | if 'keypoints' in targets: 172 | keypoints = targets['keypoints'] 173 | keypoints = keypoints.reshape(keypoints.shape[0], -1).tolist() 174 | num_objs = len(bboxes) 175 | for i in range(num_objs): 176 | ann = {} 177 | ann['image_id'] = image_id 178 | ann['bbox'] = bboxes[i] 179 | ann['category_id'] = labels[i] 180 | categories.add(labels[i]) 181 | ann['area'] = areas[i] 182 | ann['iscrowd'] = iscrowd[i] 183 | ann['id'] = ann_id 184 | if 'masks' in targets: 185 | ann["segmentation"] = coco_mask.encode(masks[i].numpy()) 186 | if 'keypoints' in targets: 187 | ann['keypoints'] = keypoints[i] 188 | ann['num_keypoints'] = sum(k != 0 for k in keypoints[i][2::3]) 189 | dataset['annotations'].append(ann) 190 | ann_id += 1 191 | dataset['categories'] = [{'id': i} for i in sorted(categories)] 192 | coco_ds.dataset = dataset 193 | coco_ds.createIndex() 194 | return coco_ds 195 | 196 | 197 | def get_coco_api_from_dataset(dataset): 198 | for i in range(10): 199 | if isinstance(dataset, torchvision.datasets.CocoDetection): 200 | break 201 | if isinstance(dataset, torch.utils.data.Subset): 202 | dataset = dataset.dataset 203 | if isinstance(dataset, torchvision.datasets.CocoDetection): 204 | return dataset.coco 205 | return convert_to_coco_api(dataset) 206 | 207 | 208 | class CocoDetection(torchvision.datasets.CocoDetection): 209 | def __init__(self, img_folder, ann_file, transforms): 210 | super(CocoDetection, self).__init__(img_folder, ann_file) 211 | self._transforms = transforms 212 | 213 | def __getitem__(self, idx): 214 | img, target = super(CocoDetection, self).__getitem__(idx) 215 | image_id = self.ids[idx] 216 | target = dict(image_id=image_id, annotations=target) 217 | if self._transforms is not None: 218 | img, target = self._transforms(img, target) 219 | return img, target 220 | 221 | 222 | def get_coco(root, image_set, transforms, mode='instances'): 223 | anno_file_template = "{}_{}2017.json" 224 | PATHS = { 225 | "train": ("train2017", os.path.join("annotations", anno_file_template.format(mode, "train"))), 226 | "val": ("val2017", os.path.join("annotations", anno_file_template.format(mode, "val"))), 227 | # "train": ("val2017", os.path.join("annotations", anno_file_template.format(mode, "val"))) 228 | } 229 | 230 | t = [ConvertCocoPolysToMask()] 231 | 232 | if transforms is not None: 233 | t.append(transforms) 234 | transforms = T.Compose(t) 235 | 236 | img_folder, ann_file = PATHS[image_set] 237 | img_folder = os.path.join(root, img_folder) 238 | ann_file = os.path.join(root, ann_file) 239 | 240 | dataset = CocoDetection(img_folder, ann_file, transforms=transforms) 241 | 242 | if image_set == "train": 243 | dataset = _coco_remove_images_without_annotations(dataset) 244 | 245 | # dataset = torch.utils.data.Subset(dataset, [i for i in range(500)]) 246 | 247 | return dataset 248 | 249 | 250 | def get_coco_kp(root, image_set, transforms): 251 | return get_coco(root, image_set, transforms, mode="person_keypoints") 252 | -------------------------------------------------------------------------------- /utils/dataset.py: -------------------------------------------------------------------------------- 1 | import os 2 | import numpy as np 3 | import cv2 4 | import torch 5 | import torch.utils.data 6 | import utils.transforms as T 7 | from PIL import Image 8 | 9 | def get_transform(train): 10 | transforms = [] 11 | # converts the image, a PIL image, into a PyTorch Tensor 12 | transforms.append(T.ToTensor()) 13 | if train: 14 | # during training, randomly flip the training images 15 | # and ground-truth for data augmentation 16 | transforms.append(T.RandomHorizontalFlip(0.5)) 17 | return T.Compose(transforms) 18 | 19 | 20 | class maskrcnn_Dataset(torch.utils.data.Dataset): 21 | def __init__(self, root, transforms=None): 22 | self.root = root 23 | self.transforms = transforms 24 | # load all image files, sorting them to 25 | # ensure that they are aligned 26 | self.imgs = list(sorted(os.listdir(os.path.join(root, "JPEGImages")))) 27 | self.masks = list(sorted(os.listdir(os.path.join(root, "SegmentationObject")))) 28 | self.class_masks = list(sorted(os.listdir(os.path.join(root, "SegmentationClass")))) 29 | 30 | def __getitem__(self, idx): 31 | # load images ad masks 32 | img_path = os.path.join(self.root, "JPEGImages", self.imgs[idx]) 33 | mask_path = os.path.join(self.root, "SegmentationObject", self.masks[idx]) 34 | class_mask_path = os.path.join(self.root, "SegmentationClass", self.class_masks[idx]) 35 | 36 | #read and convert image to RGB 37 | img = cv2.imread(img_path) 38 | img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 39 | # note that we haven't converted the mask to RGB, 40 | # because each color corresponds to a different instance 41 | # with 0 being background 42 | # mask = Image.open(mask_path) 43 | 44 | mask = cv2.imread(mask_path,0) 45 | class_mask = Image.open(class_mask_path).convert('P') 46 | class_mask = np.asarray(class_mask) 47 | # instances are encoded as different colors 48 | obj_ids = np.unique(mask) 49 | # first id is the background, so remove it 50 | obj_ids = obj_ids[1:] 51 | 52 | # split the color-encoded mask into a set 53 | # of binary masks 54 | masks = mask == obj_ids[:, None, None] 55 | 56 | # get bounding box coordinates for each mask 57 | num_objs = len(obj_ids) 58 | boxes = [] 59 | for i in range(num_objs): 60 | pos = np.where(masks[i]) 61 | xmin = np.min(pos[1]) 62 | xmax = np.max(pos[1]) 63 | ymin = np.min(pos[0]) 64 | ymax = np.max(pos[0]) 65 | boxes.append([xmin, ymin, xmax, ymax]) 66 | 67 | boxes = torch.as_tensor(boxes, dtype=torch.float32) 68 | # there is only one class 69 | labels = np.array([]) 70 | for i in range(masks.shape[0]): 71 | labels = np.append(labels, (masks[i] * class_mask).max()) 72 | 73 | labels = torch.as_tensor(labels, dtype=torch.int64) 74 | masks = torch.as_tensor(masks, dtype=torch.uint8) 75 | 76 | image_id = torch.tensor([idx]) 77 | area = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0]) 78 | # suppose all instances are not crowd 79 | iscrowd = torch.zeros((num_objs,), dtype=torch.int64) 80 | 81 | target = {} 82 | target["boxes"] = boxes 83 | target["labels"] = labels 84 | target["masks"] = masks 85 | target["image_id"] = image_id 86 | target["area"] = area 87 | target["iscrowd"] = iscrowd 88 | 89 | if self.transforms is not None: 90 | img, target = self.transforms(img, target) 91 | 92 | return img, target 93 | 94 | def __len__(self): 95 | return len(self.imgs) -------------------------------------------------------------------------------- /utils/engine.py: -------------------------------------------------------------------------------- 1 | import math 2 | import sys 3 | import time 4 | import torch 5 | 6 | import torchvision.models.detection.mask_rcnn 7 | from utils.coco_utils import get_coco_api_from_dataset 8 | from utils.coco_eval import CocoEvaluator 9 | import utils.utils as utils 10 | 11 | 12 | def train_one_epoch(model, optimizer, data_loader, device, epoch, print_freq): 13 | model.train() 14 | metric_logger = utils.MetricLogger(delimiter=" ") 15 | metric_logger.add_meter('lr', utils.SmoothedValue(window_size=1, fmt='{value:.6f}')) 16 | header = 'Epoch: [{}]'.format(epoch) 17 | 18 | lr_scheduler = None 19 | if epoch == 0: 20 | warmup_factor = 1. / 1000 21 | warmup_iters = min(1000, len(data_loader) - 1) 22 | 23 | lr_scheduler = utils.warmup_lr_scheduler(optimizer, warmup_iters, warmup_factor) 24 | 25 | for images, targets in metric_logger.log_every(data_loader, print_freq, header): 26 | images = list(image.to(device) for image in images) 27 | targets = [{k: v.to(device) for k, v in t.items()} for t in targets] 28 | 29 | loss_dict = model(images, targets) 30 | 31 | losses = sum(loss for loss in loss_dict.values()) 32 | 33 | # reduce losses over all GPUs for logging purposes 34 | loss_dict_reduced = utils.reduce_dict(loss_dict) 35 | losses_reduced = sum(loss for loss in loss_dict_reduced.values()) 36 | 37 | loss_value = losses_reduced.item() 38 | 39 | if not math.isfinite(loss_value): 40 | print("Loss is {}, stopping training".format(loss_value)) 41 | print(loss_dict_reduced) 42 | sys.exit(1) 43 | 44 | optimizer.zero_grad() 45 | losses.backward() 46 | optimizer.step() 47 | 48 | if lr_scheduler is not None: 49 | lr_scheduler.step() 50 | 51 | metric_logger.update(loss=losses_reduced, **loss_dict_reduced) 52 | metric_logger.update(lr=optimizer.param_groups[0]["lr"]) 53 | 54 | 55 | def _get_iou_types(model): 56 | model_without_ddp = model 57 | if isinstance(model, torch.nn.parallel.DistributedDataParallel): 58 | model_without_ddp = model.module 59 | iou_types = ["bbox"] 60 | if isinstance(model_without_ddp, torchvision.models.detection.MaskRCNN): 61 | iou_types.append("segm") 62 | if isinstance(model_without_ddp, torchvision.models.detection.KeypointRCNN): 63 | iou_types.append("keypoints") 64 | return iou_types 65 | 66 | 67 | @torch.no_grad() 68 | def evaluate(model, data_loader, device): 69 | n_threads = torch.get_num_threads() 70 | # FIXME remove this and make paste_masks_in_image run on the GPU 71 | torch.set_num_threads(1) 72 | cpu_device = torch.device("cpu") 73 | model.eval() 74 | metric_logger = utils.MetricLogger(delimiter=" ") 75 | header = 'Test:' 76 | 77 | coco = get_coco_api_from_dataset(data_loader.dataset) 78 | iou_types = _get_iou_types(model) 79 | coco_evaluator = CocoEvaluator(coco, iou_types) 80 | 81 | for image, targets in metric_logger.log_every(data_loader, 100, header): 82 | image = list(img.to(device) for img in image) 83 | targets = [{k: v.to(device) for k, v in t.items()} for t in targets] 84 | 85 | torch.cuda.synchronize() 86 | model_time = time.time() 87 | outputs = model(image) 88 | 89 | outputs = [{k: v.to(cpu_device) for k, v in t.items()} for t in outputs] 90 | model_time = time.time() - model_time 91 | 92 | res = {target["image_id"].item(): output for target, output in zip(targets, outputs)} 93 | evaluator_time = time.time() 94 | coco_evaluator.update(res) 95 | evaluator_time = time.time() - evaluator_time 96 | metric_logger.update(model_time=model_time, evaluator_time=evaluator_time) 97 | 98 | # gather the stats from all processes 99 | metric_logger.synchronize_between_processes() 100 | print("Averaged stats:", metric_logger) 101 | coco_evaluator.synchronize_between_processes() 102 | 103 | # accumulate predictions from all images 104 | coco_evaluator.accumulate() 105 | coco_evaluator.summarize() 106 | torch.set_num_threads(n_threads) 107 | return coco_evaluator 108 | -------------------------------------------------------------------------------- /utils/model.py: -------------------------------------------------------------------------------- 1 | import torchvision 2 | from torchvision.models.detection.faster_rcnn import FastRCNNPredictor 3 | from torchvision.models.detection.mask_rcnn import MaskRCNNPredictor 4 | 5 | 6 | def get_instance_segmentation_model(num_classes): 7 | # load an instance segmentation model pre-trained on COCO 8 | model = torchvision.models.detection.maskrcnn_resnet50_fpn(pretrained=True) 9 | 10 | # get the number of input features for the classifier 11 | in_features = model.roi_heads.box_predictor.cls_score.in_features 12 | # replace the pre-trained head with a new one 13 | model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes) 14 | 15 | # now get the number of input features for the mask classifier 16 | in_features_mask = model.roi_heads.mask_predictor.conv5_mask.in_channels 17 | hidden_layer = 256 18 | # and replace the mask predictor with a new one 19 | model.roi_heads.mask_predictor = MaskRCNNPredictor(in_features_mask, 20 | hidden_layer, 21 | num_classes) 22 | 23 | return model -------------------------------------------------------------------------------- /utils/transforms.py: -------------------------------------------------------------------------------- 1 | import random 2 | import torch 3 | 4 | from torchvision.transforms import functional as F 5 | 6 | 7 | def _flip_coco_person_keypoints(kps, width): 8 | flip_inds = [0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15] 9 | flipped_data = kps[:, flip_inds] 10 | flipped_data[..., 0] = width - flipped_data[..., 0] 11 | # Maintain COCO convention that if visibility == 0, then x, y = 0 12 | inds = flipped_data[..., 2] == 0 13 | flipped_data[inds] = 0 14 | return flipped_data 15 | 16 | 17 | class Compose(object): 18 | def __init__(self, transforms): 19 | self.transforms = transforms 20 | 21 | def __call__(self, image, target): 22 | for t in self.transforms: 23 | image, target = t(image, target) 24 | return image, target 25 | 26 | 27 | class RandomHorizontalFlip(object): 28 | def __init__(self, prob): 29 | self.prob = prob 30 | 31 | def __call__(self, image, target): 32 | if random.random() < self.prob: 33 | height, width = image.shape[-2:] 34 | image = image.flip(-1) 35 | bbox = target["boxes"] 36 | bbox[:, [0, 2]] = width - bbox[:, [2, 0]] 37 | target["boxes"] = bbox 38 | if "masks" in target: 39 | target["masks"] = target["masks"].flip(-1) 40 | if "keypoints" in target: 41 | keypoints = target["keypoints"] 42 | keypoints = _flip_coco_person_keypoints(keypoints, width) 43 | target["keypoints"] = keypoints 44 | return image, target 45 | 46 | 47 | class ToTensor(object): 48 | def __call__(self, image, target): 49 | image = F.to_tensor(image) 50 | return image, target 51 | -------------------------------------------------------------------------------- /utils/utils.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | 3 | from collections import defaultdict, deque 4 | import datetime 5 | import pickle 6 | import time 7 | 8 | import torch 9 | import torch.distributed as dist 10 | 11 | import errno 12 | import os 13 | 14 | 15 | class SmoothedValue(object): 16 | """Track a series of values and provide access to smoothed values over a 17 | window or the global series average. 18 | """ 19 | 20 | def __init__(self, window_size=20, fmt=None): 21 | if fmt is None: 22 | fmt = "{median:.4f} ({global_avg:.4f})" 23 | self.deque = deque(maxlen=window_size) 24 | self.total = 0.0 25 | self.count = 0 26 | self.fmt = fmt 27 | 28 | def update(self, value, n=1): 29 | self.deque.append(value) 30 | self.count += n 31 | self.total += value * n 32 | 33 | def synchronize_between_processes(self): 34 | """ 35 | Warning: does not synchronize the deque! 36 | """ 37 | if not is_dist_avail_and_initialized(): 38 | return 39 | t = torch.tensor([self.count, self.total], dtype=torch.float64, device='cuda') 40 | dist.barrier() 41 | dist.all_reduce(t) 42 | t = t.tolist() 43 | self.count = int(t[0]) 44 | self.total = t[1] 45 | 46 | @property 47 | def median(self): 48 | d = torch.tensor(list(self.deque)) 49 | return d.median().item() 50 | 51 | @property 52 | def avg(self): 53 | d = torch.tensor(list(self.deque), dtype=torch.float32) 54 | return d.mean().item() 55 | 56 | @property 57 | def global_avg(self): 58 | return self.total / self.count 59 | 60 | @property 61 | def max(self): 62 | return max(self.deque) 63 | 64 | @property 65 | def value(self): 66 | return self.deque[-1] 67 | 68 | def __str__(self): 69 | return self.fmt.format( 70 | median=self.median, 71 | avg=self.avg, 72 | global_avg=self.global_avg, 73 | max=self.max, 74 | value=self.value) 75 | 76 | 77 | def all_gather(data): 78 | """ 79 | Run all_gather on arbitrary picklable data (not necessarily tensors) 80 | Args: 81 | data: any picklable object 82 | Returns: 83 | list[data]: list of data gathered from each rank 84 | """ 85 | world_size = get_world_size() 86 | if world_size == 1: 87 | return [data] 88 | 89 | # serialized to a Tensor 90 | buffer = pickle.dumps(data) 91 | storage = torch.ByteStorage.from_buffer(buffer) 92 | tensor = torch.ByteTensor(storage).to("cuda") 93 | 94 | # obtain Tensor size of each rank 95 | local_size = torch.tensor([tensor.numel()], device="cuda") 96 | size_list = [torch.tensor([0], device="cuda") for _ in range(world_size)] 97 | dist.all_gather(size_list, local_size) 98 | size_list = [int(size.item()) for size in size_list] 99 | max_size = max(size_list) 100 | 101 | # receiving Tensor from all ranks 102 | # we pad the tensor because torch all_gather does not support 103 | # gathering tensors of different shapes 104 | tensor_list = [] 105 | for _ in size_list: 106 | tensor_list.append(torch.empty((max_size,), dtype=torch.uint8, device="cuda")) 107 | if local_size != max_size: 108 | padding = torch.empty(size=(max_size - local_size,), dtype=torch.uint8, device="cuda") 109 | tensor = torch.cat((tensor, padding), dim=0) 110 | dist.all_gather(tensor_list, tensor) 111 | 112 | data_list = [] 113 | for size, tensor in zip(size_list, tensor_list): 114 | buffer = tensor.cpu().numpy().tobytes()[:size] 115 | data_list.append(pickle.loads(buffer)) 116 | 117 | return data_list 118 | 119 | 120 | def reduce_dict(input_dict, average=True): 121 | """ 122 | Args: 123 | input_dict (dict): all the values will be reduced 124 | average (bool): whether to do average or sum 125 | Reduce the values in the dictionary from all processes so that all processes 126 | have the averaged results. Returns a dict with the same fields as 127 | input_dict, after reduction. 128 | """ 129 | world_size = get_world_size() 130 | if world_size < 2: 131 | return input_dict 132 | with torch.no_grad(): 133 | names = [] 134 | values = [] 135 | # sort the keys so that they are consistent across processes 136 | for k in sorted(input_dict.keys()): 137 | names.append(k) 138 | values.append(input_dict[k]) 139 | values = torch.stack(values, dim=0) 140 | dist.all_reduce(values) 141 | if average: 142 | values /= world_size 143 | reduced_dict = {k: v for k, v in zip(names, values)} 144 | return reduced_dict 145 | 146 | 147 | class MetricLogger(object): 148 | def __init__(self, delimiter="\t"): 149 | self.meters = defaultdict(SmoothedValue) 150 | self.delimiter = delimiter 151 | 152 | def update(self, **kwargs): 153 | for k, v in kwargs.items(): 154 | if isinstance(v, torch.Tensor): 155 | v = v.item() 156 | assert isinstance(v, (float, int)) 157 | self.meters[k].update(v) 158 | 159 | def __getattr__(self, attr): 160 | if attr in self.meters: 161 | return self.meters[attr] 162 | if attr in self.__dict__: 163 | return self.__dict__[attr] 164 | raise AttributeError("'{}' object has no attribute '{}'".format( 165 | type(self).__name__, attr)) 166 | 167 | def __str__(self): 168 | loss_str = [] 169 | for name, meter in self.meters.items(): 170 | loss_str.append( 171 | "{}: {}".format(name, str(meter)) 172 | ) 173 | return self.delimiter.join(loss_str) 174 | 175 | def synchronize_between_processes(self): 176 | for meter in self.meters.values(): 177 | meter.synchronize_between_processes() 178 | 179 | def add_meter(self, name, meter): 180 | self.meters[name] = meter 181 | 182 | def log_every(self, iterable, print_freq, header=None): 183 | i = 0 184 | if not header: 185 | header = '' 186 | start_time = time.time() 187 | end = time.time() 188 | iter_time = SmoothedValue(fmt='{avg:.4f}') 189 | data_time = SmoothedValue(fmt='{avg:.4f}') 190 | space_fmt = ':' + str(len(str(len(iterable)))) + 'd' 191 | log_msg = self.delimiter.join([ 192 | header, 193 | '[{0' + space_fmt + '}/{1}]', 194 | 'eta: {eta}', 195 | '{meters}', 196 | 'time: {time}', 197 | 'data: {data}', 198 | 'max mem: {memory:.0f}' 199 | ]) 200 | 201 | memory = torch.cuda.max_memory_allocated() / (1024.0 * 1024.0) if torch.cuda.is_available() else 0 202 | 203 | for obj in iterable: 204 | data_time.update(time.time() - end) 205 | yield obj 206 | iter_time.update(time.time() - end) 207 | if i % print_freq == 0 or i == len(iterable) - 1: 208 | eta_seconds = iter_time.global_avg * (len(iterable) - i) 209 | eta_string = str(datetime.timedelta(seconds=int(eta_seconds))) 210 | print(log_msg.format( 211 | i, len(iterable), eta=eta_string, 212 | meters=str(self), 213 | time=str(iter_time), data=str(data_time), 214 | memory=memory)) 215 | i += 1 216 | end = time.time() 217 | total_time = time.time() - start_time 218 | total_time_str = str(datetime.timedelta(seconds=int(total_time))) 219 | print('{} Total time: {} ({:.4f} s / it)'.format( 220 | header, total_time_str, total_time / len(iterable))) 221 | 222 | 223 | def collate_fn(batch): 224 | return tuple(zip(*batch)) 225 | 226 | 227 | def warmup_lr_scheduler(optimizer, warmup_iters, warmup_factor): 228 | 229 | def f(x): 230 | if x >= warmup_iters: 231 | return 1 232 | alpha = float(x) / warmup_iters 233 | return warmup_factor * (1 - alpha) + alpha 234 | 235 | return torch.optim.lr_scheduler.LambdaLR(optimizer, f) 236 | 237 | 238 | def mkdir(path): 239 | try: 240 | os.makedirs(path) 241 | except OSError as e: 242 | if e.errno != errno.EEXIST: 243 | raise 244 | 245 | 246 | def setup_for_distributed(is_master): 247 | """ 248 | This function disables printing when not in master process 249 | """ 250 | import builtins as __builtin__ 251 | builtin_print = __builtin__.print 252 | 253 | def print(*args, **kwargs): 254 | force = kwargs.pop('force', False) 255 | if is_master or force: 256 | builtin_print(*args, **kwargs) 257 | 258 | __builtin__.print = print 259 | 260 | 261 | def is_dist_avail_and_initialized(): 262 | if not dist.is_available(): 263 | return False 264 | if not dist.is_initialized(): 265 | return False 266 | return True 267 | 268 | 269 | def get_world_size(): 270 | if not is_dist_avail_and_initialized(): 271 | return 1 272 | return dist.get_world_size() 273 | 274 | 275 | def get_rank(): 276 | if not is_dist_avail_and_initialized(): 277 | return 0 278 | return dist.get_rank() 279 | 280 | 281 | def is_main_process(): 282 | return get_rank() == 0 283 | 284 | 285 | def save_on_master(*args, **kwargs): 286 | if is_main_process(): 287 | torch.save(*args, **kwargs) 288 | 289 | 290 | def init_distributed_mode(args): 291 | if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ: 292 | args.rank = int(os.environ["RANK"]) 293 | args.world_size = int(os.environ['WORLD_SIZE']) 294 | args.gpu = int(os.environ['LOCAL_RANK']) 295 | elif 'SLURM_PROCID' in os.environ: 296 | args.rank = int(os.environ['SLURM_PROCID']) 297 | args.gpu = args.rank % torch.cuda.device_count() 298 | else: 299 | print('Not using distributed mode') 300 | args.distributed = False 301 | return 302 | 303 | args.distributed = True 304 | 305 | torch.cuda.set_device(args.gpu) 306 | args.dist_backend = 'nccl' 307 | print('| distributed init (rank {}): {}'.format( 308 | args.rank, args.dist_url), flush=True) 309 | torch.distributed.init_process_group(backend=args.dist_backend, init_method=args.dist_url, 310 | world_size=args.world_size, rank=args.rank) 311 | torch.distributed.barrier() 312 | setup_for_distributed(args.rank == 0) 313 | --------------------------------------------------------------------------------