├── .gitattributes ├── LICENSE ├── README.md ├── building_seg_test.py ├── config ├── inriabuilding │ └── buildformer.py ├── massbuilding │ └── buildformer.py └── whubuilding │ └── buildformer.py ├── geoseg ├── __init__.py ├── datasets │ ├── __init__.py │ ├── inria_dataset.py │ ├── mass_dataset.py │ ├── transform.py │ └── whubuilding_dataset.py ├── losses │ ├── __init__.py │ ├── balanced_bce.py │ ├── bitempered_loss.py │ ├── cel1.py │ ├── dice.py │ ├── focal.py │ ├── focal_cosine.py │ ├── functional.py │ ├── jaccard.py │ ├── joint_loss.py │ ├── lovasz.py │ ├── soft_bce.py │ ├── soft_ce.py │ ├── soft_f1.py │ ├── useful_loss.py │ └── wing_loss.py └── models │ ├── BuildFormer.py │ └── __init__.py ├── inria_patch_split.py ├── mass_patch_split.py ├── requirements.txt ├── tools ├── __init__.py ├── cfg.py └── metric.py ├── train_supervision.py └── whubuilding_mask_convert.py /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /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 | ## [Building extraction with vision transformer](https://ieeexplore.ieee.org/document/9808187) 2 | 3 | *IEEE Transactions on Geoscience and Remote Sensing*, 2022, [Libo Wang](https://WangLibo1995.github.io), Shenghui Fang, Xiaoliang Meng, [Rui Li](https://lironui.github.io/). 4 | 5 | [Research Gate link](https://www.researchgate.net/publication/361583918_Building_extraction_with_vision_transformer) 6 | 7 | ## Introduction 8 | 9 | This project (BuildFormer) is an extension of our [GeoSeg](https://github.com/WangLibo1995/GeoSeg), which mainly focuses on building extraction from remote sensing images. 10 | 11 | 12 | ## Folder Structure 13 | 14 | Prepare the following folders to organize this repo: 15 | ```none 16 | airs 17 | ├── BuildFormer (code) 18 | ├── pretrain_weights (save the pretrained weights like vit, swin, etc) 19 | ├── model_weights (save the model weights) 20 | ├── fig_results (save the masks predicted by models) 21 | ├── lightning_logs (CSV format training logs) 22 | ├── data 23 | │ ├── AerialImageDataset (i.e. INRIA) 24 | │ │ ├── train 25 | │ │ │ ├── val_images (splited original images, ID 1-5 of each city) 26 | │ │ │ ├── vak_masks (splited original masks, ID 1-5 of each city) 27 | │ │ │ ├── train_images (splited original images, the other IDs) 28 | │ │ │ ├── train_masks (splited original masks, the other IDs) 29 | │ │ │ ├── train 30 | │ │ │ │ ├── images (processed) 31 | │ │ │ │ ├── masks (processed) 32 | │ │ │ ├── val 33 | │ │ │ │ ├── images (processed) 34 | │ │ │ │ ├── masks (processed) 35 | │ │ │ │ ├── masks_gt (processed, for visualization) 36 | │ ├── mass_build 37 | │ │ ├── png 38 | │ │ │ ├── train (original images) 39 | │ │ │ ├── train_labels (original masks, RGB format) 40 | │ │ │ ├── train_images (processed images) 41 | │ │ │ ├── train_masks (processed masks, unit8 format) 42 | │ │ │ ├── val (original images) 43 | │ │ │ ├── val_labels (original masks, RGB format) 44 | │ │ │ ├── val_images (processed images) 45 | │ │ │ ├── val_masks (processed masks, unit8 format) 46 | │ │ │ ├── test (original images) 47 | │ │ │ ├── test_labels (original masks, RGB format) 48 | │ │ │ ├── test_images (processed images) 49 | │ │ │ ├── test_masks (processed masks, unit8 format) 50 | │ ├── whubuilding 51 | │ │ ├── train 52 | │ │ │ ├── images (original images) 53 | │ │ │ ├── masks_origin (original masks) 54 | │ │ │ ├── masks (converted masks) 55 | │ │ ├── val (the same with train) 56 | │ │ ├── test (the same with test) 57 | │ │ ├── train_val (Merge train and val) 58 | ``` 59 | 60 | ## Install 61 | 62 | Open the folder **airs** using **Linux Terminal** and create python environment: 63 | ``` 64 | conda create -n airs python=3.8 65 | conda activate airs 66 | 67 | conda install pytorch==1.10.0 torchvision==0.11.0 torchaudio==0.10.0 cudatoolkit=11.3 -c pytorch -c conda-forge 68 | pip install -r BuildFormer/requirements.txt 69 | ``` 70 | 71 | ## Data Preprocessing 72 | 73 | Download the [WHU Aerial](https://study.rsgis.whu.edu.cn/pages/download/building_dataset.html), [Massachusetts](https://www.cs.toronto.edu/~vmnih/data/), [INRIA](https://project.inria.fr/aerialimagelabeling/) building datasets and split them by **Folder Structure**. 74 | 75 | **WHU** 76 | 77 | ``` 78 | python BuildFormer/whubuilding_mask_convert.py \ 79 | --mask-dir "data/whubuilding/train/masks_origin" \ 80 | --output-mask-dir "data/whubuilding/train/masks" 81 | ``` 82 | 83 | ``` 84 | python BuildFormer/whubuilding_mask_convert.py \ 85 | --mask-dir "data/whubuilding/val/masks_origin" \ 86 | --output-mask-dir "data/whubuilding/val/masks" 87 | ``` 88 | 89 | ``` 90 | python BuildFormer/whubuilding_mask_convert.py \ 91 | --mask-dir "data/whubuilding/test/masks_origin" \ 92 | --output-mask-dir "data/whubuilding/test/masks" 93 | ``` 94 | 95 | **Massachusetts** 96 | 97 | ``` 98 | python BuildFormer/mass_patch_split.py \ 99 | --input-img-dir "data/mass_build/png/train" \ 100 | --input-mask-dir "data/mass_build/png/train_labels" \ 101 | --output-img-dir "data/mass_build/png/train_images" \ 102 | --output-mask-dir "data/mass_build/png/train_masks" \ 103 | --mode "train" 104 | ``` 105 | 106 | ``` 107 | python BuildFormer/mass_patch_split.py \ 108 | --input-img-dir "data/mass_build/png/val" \ 109 | --input-mask-dir "data/mass_build/png/val_labels" \ 110 | --output-img-dir "data/mass_build/png/val_images" \ 111 | --output-mask-dir "data/mass_build/png/val_masks" \ 112 | --mode "val" 113 | ``` 114 | 115 | ``` 116 | python BuildFormer/mass_patch_split.py \ 117 | --input-img-dir "data/mass_build/png/test" \ 118 | --input-mask-dir "data/mass_build/png/test_labels" \ 119 | --output-img-dir "data/mass_build/png/test_images" \ 120 | --output-mask-dir "data/mass_build/png/test_masks" \ 121 | --mode "val" 122 | ``` 123 | 124 | **INRIA** 125 | 126 | ``` 127 | python BuildFormer/inria_patch_split.py \ 128 | --input-img-dir "data/AerialImageDataset/train/train_images" \ 129 | --input-mask-dir "data/AerialImageDataset/train/train_masks" \ 130 | --output-img-dir "data/AerialImageDataset/train/train/images" \ 131 | --output-mask-dir "data/AerialImageDataset/train/train/masks" \ 132 | --mode "train" 133 | ``` 134 | 135 | ``` 136 | python BuildFormer/inria_patch_split.py \ 137 | --input-img-dir "data/AerialImageDataset/train/val_images" \ 138 | --input-mask-dir "data/AerialImageDataset/train/val_masks" \ 139 | --output-img-dir "data/AerialImageDataset/train/val/images" \ 140 | --output-mask-dir "data/AerialImageDataset/train/val/masks" \ 141 | --mode "val" 142 | ``` 143 | 144 | ## Training 145 | 146 | ``` 147 | python BuildFormer/train_supervision.py -c BuildFormer/config/whubuilding/buildformer.py 148 | ``` 149 | 150 | ``` 151 | python BuildFormer/train_supervision.py -c BuildFormer/config/massbuilding/buildformer.py 152 | ``` 153 | 154 | ``` 155 | python BuildFormer/train_supervision.py -c BuildFormer/config/inriabuilding/buildformer.py 156 | ``` 157 | 158 | 159 | 160 | ## Testing 161 | 162 | ``` 163 | python BuildFormer/building_seg_test.py -c BuildFormer/config/whubuilding/buildformer.py -o fig_results/whubuilding/buildformer --rgb -t 'lr' 164 | ``` 165 | 166 | ``` 167 | python BuildFormer/building_seg_test.py -c BuildFormer/config/massbuilding/buildformer.py -o fig_results/massbuilding/buildformer --rgb -t 'lr' 168 | ``` 169 | 170 | ``` 171 | python BuildFormer/building_seg_test.py -c BuildFormer/config/inriabuilding/buildformer.py -o fig_results/inriabuilding/buildformer --rgb -t 'lr' 172 | ``` 173 | 174 | ## Citation 175 | 176 | If you find this project useful in your research, please consider citing our paper: 177 | 178 | [Building extraction with vision transformer](https://ieeexplore.ieee.org/document/9808187) 179 | 180 | ## Acknowledgement 181 | 182 | - [pytorch lightning](https://www.pytorchlightning.ai/) 183 | - [timm](https://github.com/rwightman/pytorch-image-models) 184 | - [pytorch-toolbelt](https://github.com/BloodAxe/pytorch-toolbelt) 185 | - [ttach](https://github.com/qubvel/ttach) 186 | - [catalyst](https://github.com/catalyst-team/catalyst) 187 | - [mmsegmentation](https://github.com/open-mmlab/mmsegmentation) -------------------------------------------------------------------------------- /building_seg_test.py: -------------------------------------------------------------------------------- 1 | import ttach as tta 2 | import multiprocessing.pool as mpp 3 | import multiprocessing as mp 4 | import time 5 | from train_supervision import * 6 | import argparse 7 | from pathlib import Path 8 | import cv2 9 | import numpy as np 10 | import torch 11 | 12 | from torch import nn 13 | from torch.utils.data import DataLoader 14 | from tqdm import tqdm 15 | 16 | 17 | def label_to_rgb(mask): 18 | h, w = mask.shape[0], mask.shape[1] 19 | mask_rgb = np.zeros(shape=(h, w, 3), dtype=np.uint8) 20 | mask_convert = mask[np.newaxis, :, :] 21 | mask_rgb[np.all(mask_convert == 0, axis=0)] = [255, 255, 255] 22 | mask_rgb[np.all(mask_convert == 1, axis=0)] = [0, 0, 0] 23 | return mask_rgb 24 | 25 | 26 | def img_writer(inp): 27 | (mask, mask_id, rgb) = inp 28 | if rgb: 29 | mask_name_tif = mask_id + '.png' 30 | mask_tif = label_to_rgb(mask) 31 | cv2.imwrite(mask_name_tif, mask_tif) 32 | else: 33 | mask_png = mask.astype(np.uint8) 34 | mask_name_png = mask_id + '.png' 35 | cv2.imwrite(mask_name_png, mask_png) 36 | 37 | 38 | def get_args(): 39 | parser = argparse.ArgumentParser() 40 | arg = parser.add_argument 41 | arg("-c", "--config_path", type=Path, required=True, help="Path to config") 42 | arg("-o", "--output_path", type=Path, help="Path where to save resulting masks.", required=True) 43 | arg("-t", "--tta", help="Test time augmentation.", default=None, choices=[None, "d4", "lr"]) 44 | arg("--rgb", help="whether output rgb images", action='store_true') 45 | return parser.parse_args() 46 | 47 | 48 | def main(): 49 | args = get_args() 50 | config = py2cfg(args.config_path) 51 | args.output_path.mkdir(exist_ok=True, parents=True) 52 | 53 | model = Supervision_Train.load_from_checkpoint( 54 | os.path.join(config.weights_path, config.test_weights_name + '.ckpt'), config=config) 55 | model.cuda() 56 | model.eval() 57 | evaluator = Evaluator(num_class=config.num_classes) 58 | evaluator.reset() 59 | if args.tta == "lr": 60 | transforms = tta.Compose( 61 | [ 62 | tta.HorizontalFlip(), 63 | tta.VerticalFlip() 64 | ] 65 | ) 66 | model = tta.SegmentationTTAWrapper(model, transforms) 67 | elif args.tta == "d4": 68 | transforms = tta.Compose( 69 | [ 70 | tta.HorizontalFlip(), 71 | tta.VerticalFlip(), 72 | tta.Rotate90(angles=[0, 90, 180, 270]) 73 | ] 74 | ) 75 | model = tta.SegmentationTTAWrapper(model, transforms) 76 | 77 | test_dataset = config.test_dataset 78 | 79 | with torch.no_grad(): 80 | test_loader = DataLoader( 81 | test_dataset, 82 | batch_size=2, 83 | num_workers=4, 84 | pin_memory=True, 85 | drop_last=False, 86 | ) 87 | results = [] 88 | for input in tqdm(test_loader): 89 | # raw_prediction NxCxHxW 90 | raw_predictions = model(input['img'].cuda()) 91 | image_ids = input["img_id"] 92 | if 'gt_semantic_seg' in input.keys(): 93 | masks_true = input['gt_semantic_seg'] 94 | 95 | raw_predictions = nn.Softmax(dim=1)(raw_predictions) 96 | # input_images['features'] NxCxHxW C=3 97 | predictions = raw_predictions.argmax(dim=1) 98 | # print('preds shape', predictions[0,:,:]) 99 | 100 | for i in range(raw_predictions.shape[0]): 101 | raw_mask = predictions[i].cpu().numpy() 102 | mask = raw_mask 103 | 104 | # print(mask.shape) 105 | if 'gt_semantic_seg' in input.keys(): 106 | evaluator.add_batch(pre_image=mask, gt_image=masks_true[i].cpu().numpy()) 107 | mask_name = image_ids[i] 108 | results.append((mask, str(args.output_path / mask_name), args.rgb)) 109 | t0 = time.time() 110 | mpp.Pool(processes=mp.cpu_count()).map(img_writer, results) 111 | t1 = time.time() 112 | img_write_time = t1 - t0 113 | print('images writing spends: {} s'.format(img_write_time)) 114 | iou_per_class = evaluator.Intersection_over_Union() 115 | f1_per_class = evaluator.F1() 116 | OA = evaluator.OA() 117 | precision = evaluator.Precision() 118 | recall = evaluator.Recall() 119 | for class_name, class_iou, class_f1 in zip(config.CLASSES, iou_per_class, f1_per_class): 120 | print('F1_{}:{}, IOU_{}:{}'.format(class_name, class_f1, class_name, class_iou)) 121 | print('F1:{}, mIOU:{}, OA:{}, P:{}, R:{}'.format(np.nanmean(f1_per_class[:-1]), np.nanmean(iou_per_class[:-1]), OA, 122 | np.nanmean(precision[:-1]), np.nanmean(recall[:-1]))) 123 | 124 | 125 | if __name__ == "__main__": 126 | main() 127 | -------------------------------------------------------------------------------- /config/inriabuilding/buildformer.py: -------------------------------------------------------------------------------- 1 | from torch.utils.data import DataLoader 2 | from geoseg.losses import * 3 | from geoseg.datasets.inria_dataset import * 4 | from geoseg.models.BuildFormer import BuildFormerSegDP 5 | from catalyst.contrib.nn import Lookahead 6 | from catalyst import utils 7 | 8 | # training hparam 9 | max_epoch = 105 10 | ignore_index = 255 11 | train_batch_size = 12 12 | val_batch_size = 12 13 | lr = 5e-4 14 | weight_decay = 0.0025 15 | backbone_lr = 5e-4 16 | backbone_weight_decay = 0.0025 17 | accumulate_n = 1 18 | num_classes = len(CLASSES) 19 | classes = CLASSES 20 | 21 | weights_name = "buildformer" 22 | weights_path = "model_weights/inriabuilding/{}".format(weights_name) 23 | test_weights_name = "buildformer" 24 | log_name = 'inriabuilding/{}'.format(weights_name) 25 | monitor = 'val_mIoU' 26 | monitor_mode = 'max' 27 | save_top_k = 1 28 | save_last = True 29 | check_val_every_n_epoch = 1 30 | gpus = [1] 31 | strategy = None 32 | pretrained_ckpt_path = "model_weights/whubuilding/buildformer_large_edge_all/buildformer_large_edge_all.ckpt" 33 | resume_ckpt_path = None 34 | # define the network 35 | net = BuildFormerSegDP(num_classes=num_classes) 36 | # define the loss 37 | loss = EdgeLoss(ignore_index=255) 38 | use_aux_loss = False 39 | 40 | # define the dataloader 41 | 42 | train_dataset = InriaDataset(data_root='data/AerialImageDataset/train/train', mode='train', mosaic_ratio=0.25, transform=get_training_transform()) 43 | val_dataset = InriaDataset(data_root='data/AerialImageDataset/train/val', mode='val', transform=get_validation_transform()) 44 | test_dataset = InriaDataset(data_root='data/AerialImageDataset/train/val', mode='val', transform=get_validation_transform()) 45 | 46 | train_loader = DataLoader(dataset=train_dataset, 47 | batch_size=train_batch_size, 48 | num_workers=4, 49 | pin_memory=True, 50 | shuffle=True, 51 | drop_last=True) 52 | 53 | val_loader = DataLoader(dataset=val_dataset, 54 | batch_size=val_batch_size, 55 | num_workers=4, 56 | shuffle=False, 57 | pin_memory=True, 58 | drop_last=False) 59 | 60 | # define the optimizer 61 | layerwise_params = {"backbone.*": dict(lr=backbone_lr, weight_decay=backbone_weight_decay)} 62 | net_params = utils.process_model_params(net, layerwise_params=layerwise_params) 63 | base_optimizer = torch.optim.AdamW(net_params, lr=lr, weight_decay=weight_decay) 64 | optimizer = Lookahead(base_optimizer) 65 | lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizer, T_0=15, T_mult=2) -------------------------------------------------------------------------------- /config/massbuilding/buildformer.py: -------------------------------------------------------------------------------- 1 | from torch.utils.data import DataLoader 2 | from geoseg.losses import * 3 | from geoseg.datasets.mass_dataset import * 4 | from geoseg.models.BuildFormer import BuildFormerSegDP 5 | from catalyst.contrib.nn import Lookahead 6 | from catalyst import utils 7 | 8 | # training hparam 9 | max_epoch = 105 10 | ignore_index = 255 11 | train_batch_size = 2 12 | val_batch_size = 2 13 | lr = 5e-4 14 | weight_decay = 0.0025 15 | backbone_lr = 5e-4 16 | backbone_weight_decay = 0.0025 17 | accumulate_n = 1 18 | num_classes = len(CLASSES) 19 | classes = CLASSES 20 | 21 | weights_name = "buildformer" 22 | weights_path = "model_weights/massbuilding/{}".format(weights_name) 23 | test_weights_name = "buildformer" 24 | log_name = 'massbuilding/{}'.format(weights_name) 25 | monitor = 'val_mIoU' 26 | monitor_mode = 'max' 27 | save_top_k = 5 28 | save_last = True 29 | check_val_every_n_epoch = 1 30 | gpus = [1] 31 | strategy = None 32 | pretrained_ckpt_path = "model_weights/whubuilding/buildformer_large_edge_all/buildformer_large_edge_all.ckpt" 33 | resume_ckpt_path = None 34 | # define the network 35 | net = BuildFormerSegDP(num_classes=num_classes) 36 | # define the loss 37 | loss = EdgeLoss(ignore_index=255) 38 | 39 | use_aux_loss = False 40 | 41 | # define the dataloader 42 | train_dataset = MassBuildDataset(mosaic_ratio=0.25, transform=get_training_transform()) 43 | val_dataset = MassBuildDataset(mode='val', img_dir='val_images', mask_dir='val_masks', transform=get_validation_transform()) 44 | test_dataset = MassBuildDataset(mode='val', img_dir='test_images', mask_dir='test_masks', transform=get_test_transform()) 45 | 46 | 47 | train_loader = DataLoader(dataset=train_dataset, 48 | batch_size=train_batch_size, 49 | num_workers=4, 50 | pin_memory=True, 51 | shuffle=True, 52 | drop_last=True) 53 | 54 | val_loader = DataLoader(dataset=val_dataset, 55 | batch_size=val_batch_size, 56 | num_workers=4, 57 | shuffle=False, 58 | pin_memory=True, 59 | drop_last=False) 60 | 61 | # define the optimizer 62 | layerwise_params = {"backbone.*": dict(lr=backbone_lr, weight_decay=backbone_weight_decay)} 63 | net_params = utils.process_model_params(net, layerwise_params=layerwise_params) 64 | base_optimizer = torch.optim.AdamW(net_params, lr=lr, weight_decay=weight_decay) 65 | optimizer = Lookahead(base_optimizer) 66 | lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizer, T_0=15, T_mult=2) -------------------------------------------------------------------------------- /config/whubuilding/buildformer.py: -------------------------------------------------------------------------------- 1 | from torch.utils.data import DataLoader 2 | from geoseg.losses import * 3 | from geoseg.datasets.whubuilding_dataset import * 4 | from geoseg.models.BuildFormer import BuildFormerSegDP 5 | from catalyst.contrib.nn import Lookahead 6 | from catalyst import utils 7 | 8 | # training hparam 9 | max_epoch = 105 10 | ignore_index = 255 11 | train_batch_size = 8 12 | val_batch_size = 8 13 | lr = 1e-3 14 | weight_decay = 0.0025 15 | backbone_lr = 1e-3 16 | backbone_weight_decay = 0.0025 17 | accumulate_n = 1 18 | num_classes = len(CLASSES) 19 | classes = CLASSES 20 | 21 | weights_name = "buildformer_large_edge_all" 22 | weights_path = "model_weights/whubuilding/{}".format(weights_name) 23 | test_weights_name = "buildformer_large_edge_all" 24 | log_name = 'whubuilding/{}'.format(weights_name) 25 | monitor = 'val_mIoU' 26 | monitor_mode = 'max' 27 | save_top_k = 3 28 | save_last = True 29 | check_val_every_n_epoch = 1 30 | gpus = [1] 31 | strategy = None 32 | pretrained_ckpt_path = None 33 | resume_ckpt_path = None 34 | # define the network 35 | net = BuildFormerSegDP(num_classes=num_classes) 36 | # define the loss 37 | loss = EdgeLoss(ignore_index=255) 38 | use_aux_loss = False 39 | 40 | # define the dataloader 41 | 42 | train_dataset = WHUBuildingDataset(data_root='data/whubuilding/train_val', mode='train', mosaic_ratio=0.25, transform=train_aug) 43 | val_dataset = WHUBuildingDataset(data_root='data/whubuilding/val', mode='val', transform=val_aug) 44 | test_dataset = WHUBuildingDataset(data_root='data/whubuilding/test', mode='val', transform=val_aug) 45 | 46 | train_loader = DataLoader(dataset=train_dataset, 47 | batch_size=train_batch_size, 48 | num_workers=4, 49 | pin_memory=True, 50 | shuffle=True, 51 | drop_last=True) 52 | 53 | val_loader = DataLoader(dataset=val_dataset, 54 | batch_size=val_batch_size, 55 | num_workers=4, 56 | shuffle=False, 57 | pin_memory=True, 58 | drop_last=False) 59 | 60 | # define the optimizer 61 | layerwise_params = {"backbone.*": dict(lr=backbone_lr, weight_decay=backbone_weight_decay)} 62 | net_params = utils.process_model_params(net, layerwise_params=layerwise_params) 63 | base_optimizer = torch.optim.AdamW(net_params, lr=lr, weight_decay=weight_decay) 64 | optimizer = Lookahead(base_optimizer) 65 | lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizer, T_0=15, T_mult=2) -------------------------------------------------------------------------------- /geoseg/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WangLibo1995/BuildFormer/c20f15805694fa568b8ac531ba51bc5e9c5a29c6/geoseg/__init__.py -------------------------------------------------------------------------------- /geoseg/datasets/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WangLibo1995/BuildFormer/c20f15805694fa568b8ac531ba51bc5e9c5a29c6/geoseg/datasets/__init__.py -------------------------------------------------------------------------------- /geoseg/datasets/inria_dataset.py: -------------------------------------------------------------------------------- 1 | import os 2 | import os.path as osp 3 | import numpy as np 4 | import torch 5 | from torch.utils.data import Dataset 6 | import cv2 7 | import matplotlib.pyplot as plt 8 | import albumentations as albu 9 | 10 | import matplotlib.patches as mpatches 11 | from PIL import Image 12 | import random 13 | 14 | CLASSES = ('Building', 'Background') 15 | PALETTE = [[255, 255, 255], [0, 0, 0]] 16 | 17 | ORIGIN_IMG_SIZE = (512, 512) 18 | INPUT_IMG_SIZE = (512, 512) 19 | TEST_IMG_SIZE = (512, 512) 20 | 21 | 22 | class InriaDataset(Dataset): 23 | def __init__(self, data_root='data/AerialImageDataset/train/train', mode='train', img_dir='images', mask_dir='masks', 24 | img_suffix='.png', mask_suffix='.png', transform=None, mosaic_ratio=0.25, 25 | img_size=ORIGIN_IMG_SIZE): 26 | self.data_root = data_root 27 | self.img_dir = img_dir 28 | self.mask_dir = mask_dir 29 | self.img_suffix = img_suffix 30 | self.mask_suffix = mask_suffix 31 | self.transform = transform 32 | self.mode = mode 33 | self.mosaic_ratio = mosaic_ratio 34 | self.img_size = img_size 35 | self.img_ids = self.get_img_ids(self.data_root, self.img_dir, self.mask_dir) 36 | 37 | def __getitem__(self, index): 38 | p_ratio = random.random() 39 | if p_ratio > self.mosaic_ratio or self.mode == 'val' or self.mode == 'test': 40 | img, mask = self.load_img_and_mask(index) 41 | if self.transform: 42 | augmented = self.transform(image=img, mask=mask) 43 | img = augmented['image'] 44 | mask = augmented['mask'] 45 | else: 46 | img, mask = self.load_mosaic_img_and_mask(index) 47 | if self.transform: 48 | augmented = self.transform(image=img, mask=mask) 49 | img = augmented['image'] 50 | mask = augmented['mask'] 51 | 52 | img = torch.from_numpy(img).permute(2, 0, 1).float() 53 | mask = torch.from_numpy(mask).long() 54 | img_id = self.img_ids[index] 55 | results = dict(img_id=img_id, img=img, gt_semantic_seg=mask) 56 | return results 57 | 58 | def __len__(self): 59 | return len(self.img_ids) 60 | 61 | def get_img_ids(self, data_root, img_dir, mask_dir): 62 | img_filename_list = os.listdir(osp.join(data_root, img_dir)) 63 | mask_filename_list = os.listdir(osp.join(data_root, mask_dir)) 64 | assert len(img_filename_list) == len(mask_filename_list) 65 | img_ids = [str(id.split('.')[0]) for id in mask_filename_list] 66 | return img_ids 67 | 68 | def load_img_and_mask(self, index): 69 | img_id = self.img_ids[index] 70 | img_name = osp.join(self.data_root, self.img_dir, img_id + self.img_suffix) 71 | mask_name = osp.join(self.data_root, self.mask_dir, img_id + self.mask_suffix) 72 | img = cv2.imread(img_name, cv2.IMREAD_COLOR) 73 | img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 74 | img = img.astype(np.uint8) 75 | mask = cv2.imread(mask_name, cv2.IMREAD_UNCHANGED) 76 | mask = mask.astype(np.float32) 77 | return img, mask 78 | 79 | def load_mosaic_img_and_mask(self, index): 80 | indexes = [index] + [random.randint(0, len(self.img_ids) - 1) for _ in range(3)] 81 | img_a, mask_a = self.load_img_and_mask(indexes[0]) 82 | img_b, mask_b = self.load_img_and_mask(indexes[1]) 83 | img_c, mask_c = self.load_img_and_mask(indexes[2]) 84 | img_d, mask_d = self.load_img_and_mask(indexes[3]) 85 | 86 | w = self.img_size[1] 87 | h = self.img_size[0] 88 | 89 | start_x = w // 4 90 | strat_y = h // 4 91 | # The coordinates of the splice center 92 | offset_x = random.randint(start_x, (w - start_x)) 93 | offset_y = random.randint(strat_y, (h - strat_y)) 94 | 95 | crop_size_a = (offset_x, offset_y) 96 | crop_size_b = (w - offset_x, offset_y) 97 | crop_size_c = (offset_x, h - offset_y) 98 | crop_size_d = (w - offset_x, h - offset_y) 99 | 100 | random_crop_a = albu.RandomCrop(width=crop_size_a[0], height=crop_size_a[1]) 101 | random_crop_b = albu.RandomCrop(width=crop_size_b[0], height=crop_size_b[1]) 102 | random_crop_c = albu.RandomCrop(width=crop_size_c[0], height=crop_size_c[1]) 103 | random_crop_d = albu.RandomCrop(width=crop_size_d[0], height=crop_size_d[1]) 104 | 105 | croped_a = random_crop_a(image=img_a.copy(), mask=mask_a.copy()) 106 | croped_b = random_crop_b(image=img_b.copy(), mask=mask_b.copy()) 107 | croped_c = random_crop_c(image=img_c.copy(), mask=mask_c.copy()) 108 | croped_d = random_crop_d(image=img_d.copy(), mask=mask_d.copy()) 109 | 110 | img_crop_a, mask_crop_a = croped_a['image'], croped_a['mask'] 111 | img_crop_b, mask_crop_b = croped_b['image'], croped_b['mask'] 112 | img_crop_c, mask_crop_c = croped_c['image'], croped_c['mask'] 113 | img_crop_d, mask_crop_d = croped_d['image'], croped_d['mask'] 114 | 115 | top = np.concatenate((img_crop_a, img_crop_b), axis=1) 116 | bottom = np.concatenate((img_crop_c, img_crop_d), axis=1) 117 | img = np.concatenate((top, bottom), axis=0) 118 | 119 | top_mask = np.concatenate((mask_crop_a, mask_crop_b), axis=1) 120 | bottom_mask = np.concatenate((mask_crop_c, mask_crop_d), axis=1) 121 | mask = np.concatenate((top_mask, bottom_mask), axis=0) 122 | mask = np.ascontiguousarray(mask) 123 | img = np.ascontiguousarray(img) 124 | 125 | return img, mask 126 | 127 | 128 | def get_training_transform(): 129 | train_transform = [ 130 | albu.HorizontalFlip(p=0.5), 131 | albu.VerticalFlip(p=0.5), 132 | albu.Normalize() 133 | ] 134 | return albu.Compose(train_transform) 135 | 136 | 137 | def get_validation_transform(): 138 | val_transform = [ 139 | albu.Normalize() 140 | ] 141 | return albu.Compose(val_transform) 142 | 143 | 144 | def get_test_transform(): 145 | test_transform = [ 146 | albu.Normalize() 147 | ] 148 | return albu.Compose(test_transform) 149 | -------------------------------------------------------------------------------- /geoseg/datasets/mass_dataset.py: -------------------------------------------------------------------------------- 1 | import os 2 | import os.path as osp 3 | import numpy as np 4 | import torch 5 | from torch.utils.data import Dataset 6 | import cv2 7 | import matplotlib.pyplot as plt 8 | import albumentations as albu 9 | 10 | import matplotlib.patches as mpatches 11 | from PIL import Image 12 | import random 13 | 14 | CLASSES = ('Building', 'Background') 15 | PALETTE = [[255, 255, 255], [0, 0, 0]] 16 | 17 | ORIGIN_IMG_SIZE = (1500, 1500) 18 | INPUT_IMG_SIZE = (1536, 1536) 19 | TEST_IMG_SIZE = (1500, 1500) 20 | 21 | 22 | class MassBuildDataset(Dataset): 23 | def __init__(self, data_root='data/mass_build/png', mode='train', img_dir='train_images', mask_dir='train_masks', 24 | img_suffix='.png', mask_suffix='.png', transform=None, mosaic_ratio=0.25, 25 | img_size=ORIGIN_IMG_SIZE): 26 | self.data_root = data_root 27 | self.img_dir = img_dir 28 | self.mask_dir = mask_dir 29 | self.img_suffix = img_suffix 30 | self.mask_suffix = mask_suffix 31 | self.transform = transform 32 | self.mode = mode 33 | self.mosaic_ratio = mosaic_ratio 34 | self.img_size = img_size 35 | self.img_ids = self.get_img_ids(self.data_root, self.img_dir, self.mask_dir) 36 | 37 | def __getitem__(self, index): 38 | p_ratio = random.random() 39 | if p_ratio > self.mosaic_ratio or self.mode == 'val' or self.mode == 'test': 40 | img, mask = self.load_img_and_mask(index) 41 | if self.transform: 42 | augmented = self.transform(image=img, mask=mask) 43 | img = augmented['image'] 44 | mask = augmented['mask'] 45 | else: 46 | img, mask = self.load_mosaic_img_and_mask(index) 47 | if self.transform: 48 | augmented = self.transform(image=img, mask=mask) 49 | img = augmented['image'] 50 | mask = augmented['mask'] 51 | 52 | img = torch.from_numpy(img).permute(2, 0, 1).float() 53 | mask = torch.from_numpy(mask).long() 54 | img_id = self.img_ids[index] 55 | results = dict(img_id=img_id, img=img, gt_semantic_seg=mask) 56 | return results 57 | 58 | def __len__(self): 59 | return len(self.img_ids) 60 | 61 | def get_img_ids(self, data_root, img_dir, mask_dir): 62 | img_filename_list = os.listdir(osp.join(data_root, img_dir)) 63 | mask_filename_list = os.listdir(osp.join(data_root, mask_dir)) 64 | assert len(img_filename_list) == len(mask_filename_list) 65 | img_ids = [str(id.split('.')[0]) for id in mask_filename_list] 66 | return img_ids 67 | 68 | def load_img_and_mask(self, index): 69 | img_id = self.img_ids[index] 70 | img_name = osp.join(self.data_root, self.img_dir, img_id + self.img_suffix) 71 | mask_name = osp.join(self.data_root, self.mask_dir, img_id + self.mask_suffix) 72 | img = cv2.imread(img_name, cv2.IMREAD_COLOR) 73 | img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 74 | img = img.astype(np.uint8) 75 | mask = cv2.imread(mask_name, cv2.IMREAD_UNCHANGED) 76 | mask = mask.astype(np.float32) 77 | return img, mask 78 | 79 | def load_mosaic_img_and_mask(self, index): 80 | indexes = [index] + [random.randint(0, len(self.img_ids) - 1) for _ in range(3)] 81 | img_a, mask_a = self.load_img_and_mask(indexes[0]) 82 | img_b, mask_b = self.load_img_and_mask(indexes[1]) 83 | img_c, mask_c = self.load_img_and_mask(indexes[2]) 84 | img_d, mask_d = self.load_img_and_mask(indexes[3]) 85 | 86 | w = self.img_size[1] 87 | h = self.img_size[0] 88 | 89 | start_x = w // 4 90 | strat_y = h // 4 91 | # The coordinates of the splice center 92 | offset_x = random.randint(start_x, (w - start_x)) 93 | offset_y = random.randint(strat_y, (h - strat_y)) 94 | 95 | crop_size_a = (offset_x, offset_y) 96 | crop_size_b = (w - offset_x, offset_y) 97 | crop_size_c = (offset_x, h - offset_y) 98 | crop_size_d = (w - offset_x, h - offset_y) 99 | 100 | random_crop_a = albu.RandomCrop(width=crop_size_a[0], height=crop_size_a[1]) 101 | random_crop_b = albu.RandomCrop(width=crop_size_b[0], height=crop_size_b[1]) 102 | random_crop_c = albu.RandomCrop(width=crop_size_c[0], height=crop_size_c[1]) 103 | random_crop_d = albu.RandomCrop(width=crop_size_d[0], height=crop_size_d[1]) 104 | 105 | croped_a = random_crop_a(image=img_a.copy(), mask=mask_a.copy()) 106 | croped_b = random_crop_b(image=img_b.copy(), mask=mask_b.copy()) 107 | croped_c = random_crop_c(image=img_c.copy(), mask=mask_c.copy()) 108 | croped_d = random_crop_d(image=img_d.copy(), mask=mask_d.copy()) 109 | 110 | img_crop_a, mask_crop_a = croped_a['image'], croped_a['mask'] 111 | img_crop_b, mask_crop_b = croped_b['image'], croped_b['mask'] 112 | img_crop_c, mask_crop_c = croped_c['image'], croped_c['mask'] 113 | img_crop_d, mask_crop_d = croped_d['image'], croped_d['mask'] 114 | 115 | top = np.concatenate((img_crop_a, img_crop_b), axis=1) 116 | bottom = np.concatenate((img_crop_c, img_crop_d), axis=1) 117 | img = np.concatenate((top, bottom), axis=0) 118 | 119 | top_mask = np.concatenate((mask_crop_a, mask_crop_b), axis=1) 120 | bottom_mask = np.concatenate((mask_crop_c, mask_crop_d), axis=1) 121 | mask = np.concatenate((top_mask, bottom_mask), axis=0) 122 | mask = np.ascontiguousarray(mask) 123 | img = np.ascontiguousarray(img) 124 | 125 | return img, mask 126 | 127 | 128 | def get_training_transform(): 129 | train_transform = [ 130 | albu.RandomRotate90(p=0.5), 131 | albu.RandomCrop(height=1024, width=1024, p=1.0), 132 | albu.Normalize() 133 | ] 134 | return albu.Compose(train_transform) 135 | 136 | 137 | def get_validation_transform(): 138 | val_transform = [ 139 | albu.PadIfNeeded(min_height=1536, min_width=1536, position="top_left", 140 | border_mode=0, value=[0, 0, 0], mask_value=[255, 255, 255]), 141 | albu.Normalize() 142 | ] 143 | return albu.Compose(val_transform) 144 | 145 | 146 | def get_test_transform(): 147 | test_transform = [ 148 | albu.PadIfNeeded(min_height=1536, min_width=1536, position="top_left", 149 | border_mode=0, value=[0, 0, 0], mask_value=[255, 255, 255]), 150 | albu.Normalize() 151 | ] 152 | return albu.Compose(test_transform) -------------------------------------------------------------------------------- /geoseg/datasets/transform.py: -------------------------------------------------------------------------------- 1 | import math 2 | import numbers 3 | from PIL import Image, ImageOps, ImageEnhance 4 | import numpy as np 5 | import random 6 | from scipy.ndimage.morphology import generate_binary_structure, binary_erosion 7 | from scipy.ndimage import maximum_filter 8 | 9 | 10 | class Compose(object): 11 | def __init__(self, transforms): 12 | self.transforms = transforms 13 | 14 | def __call__(self, img, mask): 15 | assert img.size == mask.size 16 | for t in self.transforms: 17 | img, mask = t(img, mask) 18 | return img, mask 19 | 20 | 21 | class RandomCrop(object): 22 | """ 23 | Take a random crop from the image. 24 | First the image or crop size may need to be adjusted if the incoming image 25 | is too small... 26 | If the image is smaller than the crop, then: 27 | the image is padded up to the size of the crop 28 | unless 'nopad', in which case the crop size is shrunk to fit the image 29 | A random crop is taken such that the crop fits within the image. 30 | If a centroid is passed in, the crop must intersect the centroid. 31 | """ 32 | def __init__(self, size=512, ignore_index=12, nopad=True): 33 | 34 | if isinstance(size, numbers.Number): 35 | self.size = (int(size), int(size)) 36 | else: 37 | self.size = size 38 | self.ignore_index = ignore_index 39 | self.nopad = nopad 40 | self.pad_color = (0, 0, 0) 41 | 42 | def __call__(self, img, mask, centroid=None): 43 | assert img.size == mask.size 44 | w, h = img.size 45 | # ASSUME H, W 46 | th, tw = self.size 47 | if w == tw and h == th: 48 | return img, mask 49 | 50 | if self.nopad: 51 | if th > h or tw > w: 52 | # Instead of padding, adjust crop size to the shorter edge of image. 53 | shorter_side = min(w, h) 54 | th, tw = shorter_side, shorter_side 55 | else: 56 | # Check if we need to pad img to fit for crop_size. 57 | if th > h: 58 | pad_h = (th - h) // 2 + 1 59 | else: 60 | pad_h = 0 61 | if tw > w: 62 | pad_w = (tw - w) // 2 + 1 63 | else: 64 | pad_w = 0 65 | border = (pad_w, pad_h, pad_w, pad_h) 66 | if pad_h or pad_w: 67 | img = ImageOps.expand(img, border=border, fill=self.pad_color) 68 | mask = ImageOps.expand(mask, border=border, fill=self.ignore_index) 69 | w, h = img.size 70 | 71 | if centroid is not None: 72 | # Need to insure that centroid is covered by crop and that crop 73 | # sits fully within the image 74 | c_x, c_y = centroid 75 | max_x = w - tw 76 | max_y = h - th 77 | x1 = random.randint(c_x - tw, c_x) 78 | x1 = min(max_x, max(0, x1)) 79 | y1 = random.randint(c_y - th, c_y) 80 | y1 = min(max_y, max(0, y1)) 81 | else: 82 | if w == tw: 83 | x1 = 0 84 | else: 85 | x1 = random.randint(0, w - tw) 86 | if h == th: 87 | y1 = 0 88 | else: 89 | y1 = random.randint(0, h - th) 90 | return img.crop((x1, y1, x1 + tw, y1 + th)), mask.crop((x1, y1, x1 + tw, y1 + th)) 91 | 92 | 93 | class PadImage(object): 94 | def __init__(self, size=(512, 512), ignore_index=0): 95 | self.size = size 96 | self.ignore_index = ignore_index 97 | 98 | def __call__(self, img, mask): 99 | assert img.size == mask.size 100 | th, tw = self.size, self.size 101 | 102 | w, h = img.size 103 | 104 | if w > tw or h > th: 105 | wpercent = (tw / float(w)) 106 | target_h = int((float(img.size[1]) * float(wpercent))) 107 | img, mask = img.resize((tw, target_h), Image.BICUBIC), mask.resize((tw, target_h), Image.NEAREST) 108 | 109 | w, h = img.size 110 | img = ImageOps.expand(img, border=(0, 0, tw - w, th - h), fill=0) 111 | mask = ImageOps.expand(mask, border=(0, 0, tw - w, th - h), fill=self.ignore_index) 112 | 113 | return img, mask 114 | 115 | 116 | class RandomHorizontalFlip(object): 117 | 118 | def __init__(self, prob: float = 0.5): 119 | self.prob = prob 120 | 121 | def __call__(self, img, mask=None): 122 | if mask is not None: 123 | if random.random() < self.prob: 124 | return img.transpose(Image.FLIP_LEFT_RIGHT), mask.transpose( 125 | Image.FLIP_LEFT_RIGHT) 126 | else: 127 | return img, mask 128 | else: 129 | if random.random() < self.prob: 130 | return img.transpose(Image.FLIP_LEFT_RIGHT) 131 | else: 132 | return img 133 | 134 | 135 | class RandomVerticalFlip(object): 136 | def __init__(self, prob: float = 0.5): 137 | self.prob = prob 138 | 139 | def __call__(self, img, mask=None): 140 | if mask is not None: 141 | if random.random() < self.prob: 142 | return img.transpose(Image.FLIP_TOP_BOTTOM), mask.transpose( 143 | Image.FLIP_TOP_BOTTOM) 144 | else: 145 | return img, mask 146 | else: 147 | if random.random() < self.prob: 148 | return img.transpose(Image.FLIP_TOP_BOTTOM) 149 | else: 150 | return img 151 | 152 | 153 | class Resize(object): 154 | def __init__(self, size: tuple = (512, 512)): 155 | self.size = size # size: (h, w) 156 | 157 | def __call__(self, img, mask): 158 | assert img.size == mask.size 159 | return img.resize(self.size, Image.BICUBIC), mask.resize(self.size, Image.NEAREST) 160 | 161 | 162 | class RandomScale(object): 163 | def __init__(self, scale_list=[0.75, 1.0, 1.25], mode='value'): 164 | self.scale_list = scale_list 165 | self.mode = mode 166 | 167 | def __call__(self, img, mask): 168 | oh, ow = img.size 169 | scale_amt = 1.0 170 | if self.mode == 'value': 171 | scale_amt = np.random.choice(self.scale_list, 1) 172 | elif self.mode == 'range': 173 | scale_amt = random.uniform(self.scale_list[0], self.scale_list[-1]) 174 | h = int(scale_amt * oh) 175 | w = int(scale_amt * ow) 176 | return img.resize((w, h), Image.BICUBIC), mask.resize((w, h), Image.NEAREST) 177 | 178 | 179 | class ColorJitter(object): 180 | def __init__(self, brightness=0.5, contrast=0.5, saturation=0.5): 181 | if not brightness is None and brightness>0: 182 | self.brightness = [max(1-brightness, 0), 1+brightness] 183 | if not contrast is None and contrast>0: 184 | self.contrast = [max(1-contrast, 0), 1+contrast] 185 | if not saturation is None and saturation>0: 186 | self.saturation = [max(1-saturation, 0), 1+saturation] 187 | 188 | def __call__(self, img, mask=None): 189 | r_brightness = random.uniform(self.brightness[0], self.brightness[1]) 190 | r_contrast = random.uniform(self.contrast[0], self.contrast[1]) 191 | r_saturation = random.uniform(self.saturation[0], self.saturation[1]) 192 | img = ImageEnhance.Brightness(img).enhance(r_brightness) 193 | img = ImageEnhance.Contrast(img).enhance(r_contrast) 194 | img = ImageEnhance.Color(img).enhance(r_saturation) 195 | if mask is None: 196 | return img 197 | else: 198 | return img, mask 199 | 200 | 201 | class SmartCropV1(object): 202 | def __init__(self, crop_size=512, 203 | max_ratio=0.75, 204 | ignore_index=12, nopad=False): 205 | self.crop_size = crop_size 206 | self.max_ratio = max_ratio 207 | self.ignore_index = ignore_index 208 | self.crop = RandomCrop(crop_size, ignore_index=ignore_index, nopad=nopad) 209 | 210 | def __call__(self, img, mask): 211 | assert img.size == mask.size 212 | count = 0 213 | while True: 214 | img_crop, mask_crop = self.crop(img.copy(), mask.copy()) 215 | count += 1 216 | labels, cnt = np.unique(np.array(mask_crop), return_counts=True) 217 | cnt = cnt[labels != self.ignore_index] 218 | if len(cnt) > 1 and np.max(cnt) / np.sum(cnt) < self.max_ratio: 219 | break 220 | if count > 10: 221 | break 222 | 223 | return img_crop, mask_crop 224 | 225 | 226 | class SmartCropV2(object): 227 | def __init__(self, crop_size=512, num_classes=13, 228 | class_interest=[2, 3], 229 | class_ratio=[0.1, 0.25], 230 | max_ratio=0.75, 231 | ignore_index=12, nopad=True): 232 | self.crop_size = crop_size 233 | self.num_classes = num_classes 234 | self.class_interest = class_interest 235 | self.class_ratio = class_ratio 236 | self.max_ratio = max_ratio 237 | self.ignore_index = ignore_index 238 | self.crop = RandomCrop(crop_size, ignore_index=ignore_index, nopad=nopad) 239 | 240 | def __call__(self, img, mask): 241 | assert img.size == mask.size 242 | count = 0 243 | while True: 244 | img_crop, mask_crop = self.crop(img.copy(), mask.copy()) 245 | count += 1 246 | bins = np.array(range(self.num_classes + 1)) 247 | class_pixel_counts, _ = np.histogram(np.array(mask_crop), bins=bins) 248 | cf = class_pixel_counts / (self.crop_size * self.crop_size) 249 | cf = np.array(cf) 250 | for c, f in zip(self.class_interest, self.class_ratio): 251 | if cf[c] > f: 252 | break 253 | if np.max(cf) < 0.75 and np.argmax(cf) != self.ignore_index: 254 | break 255 | if count > 10: 256 | break 257 | 258 | return img_crop, mask_crop -------------------------------------------------------------------------------- /geoseg/datasets/whubuilding_dataset.py: -------------------------------------------------------------------------------- 1 | import os 2 | import os.path as osp 3 | import numpy as np 4 | import torch 5 | from torch.utils.data import Dataset 6 | import cv2 7 | import matplotlib.pyplot as plt 8 | import albumentations as albu 9 | from .transform import * 10 | import matplotlib.patches as mpatches 11 | from PIL import Image 12 | import random 13 | 14 | CLASSES = ('Building', 'Background') 15 | PALETTE = [[255, 255, 255], [0, 0, 0]] 16 | 17 | ORIGIN_IMG_SIZE = (512, 512) 18 | INPUT_IMG_SIZE = (512, 512) 19 | TEST_IMG_SIZE = (512, 512) 20 | 21 | 22 | def get_training_transform(): 23 | train_transform = [ 24 | albu.HorizontalFlip(p=0.5), 25 | albu.VerticalFlip(p=0.5), 26 | albu.Normalize() 27 | ] 28 | return albu.Compose(train_transform) 29 | 30 | 31 | def train_aug(img, mask): 32 | # crop_aug = Compose([RandomScale(scale_list=[0.75, 1.0, 1.25, 1.5], mode='value'), 33 | # SmartCropV1(crop_size=384, max_ratio=0.5, ignore_index=len(CLASSES), nopad=False)]) 34 | # img, mask = crop_aug(img, mask) 35 | img, mask = np.array(img), np.array(mask) 36 | aug = get_training_transform()(image=img.copy(), mask=mask.copy()) 37 | img, mask = aug['image'], aug['mask'] 38 | return img, mask 39 | 40 | 41 | def get_val_transform(): 42 | val_transform = [ 43 | albu.Normalize() 44 | ] 45 | return albu.Compose(val_transform) 46 | 47 | 48 | def val_aug(img, mask): 49 | img, mask = np.array(img), np.array(mask) 50 | aug = get_val_transform()(image=img.copy(), mask=mask.copy()) 51 | img, mask = aug['image'], aug['mask'] 52 | return img, mask 53 | 54 | 55 | class WHUBuildingDataset(Dataset): 56 | def __init__(self, data_root='data/whubuilding/train', mode='train', img_dir='images', mask_dir='masks', 57 | img_suffix='.tif', mask_suffix='.png', transform=None, mosaic_ratio=0.25, 58 | img_size=ORIGIN_IMG_SIZE): 59 | self.data_root = data_root 60 | self.img_dir = img_dir 61 | self.mask_dir = mask_dir 62 | self.img_suffix = img_suffix 63 | self.mask_suffix = mask_suffix 64 | self.transform = transform 65 | self.mode = mode 66 | self.mosaic_ratio = mosaic_ratio 67 | self.img_size = img_size 68 | self.img_ids = self.get_img_ids(self.data_root, self.img_dir, self.mask_dir) 69 | 70 | def __getitem__(self, index): 71 | p_ratio = random.random() 72 | if p_ratio > self.mosaic_ratio or self.mode == 'val' or self.mode == 'test': 73 | img, mask = self.load_img_and_mask(index) 74 | if self.transform: 75 | img, mask = self.transform(img, mask) 76 | else: 77 | img, mask = self.load_mosaic_img_and_mask(index) 78 | if self.transform: 79 | img, mask = self.transform(img, mask) 80 | 81 | img = torch.from_numpy(img).permute(2, 0, 1).float() 82 | mask = torch.from_numpy(mask).long() 83 | img_id = self.img_ids[index] 84 | results = dict(img_id=img_id, img=img, gt_semantic_seg=mask) 85 | return results 86 | 87 | def __len__(self): 88 | return len(self.img_ids) 89 | 90 | def get_img_ids(self, data_root, img_dir, mask_dir): 91 | img_filename_list = os.listdir(osp.join(data_root, img_dir)) 92 | mask_filename_list = os.listdir(osp.join(data_root, mask_dir)) 93 | assert len(img_filename_list) == len(mask_filename_list) 94 | img_ids = [str(id.split('.')[0]) for id in mask_filename_list] 95 | return img_ids 96 | 97 | def load_img_and_mask(self, index): 98 | img_id = self.img_ids[index] 99 | img_name = osp.join(self.data_root, self.img_dir, img_id + self.img_suffix) 100 | mask_name = osp.join(self.data_root, self.mask_dir, img_id + self.mask_suffix) 101 | img = Image.open(img_name).convert('RGB') 102 | mask = Image.open(mask_name).convert('L') 103 | return img, mask 104 | 105 | def load_mosaic_img_and_mask(self, index): 106 | indexes = [index] + [random.randint(0, len(self.img_ids) - 1) for _ in range(3)] 107 | img_a, mask_a = self.load_img_and_mask(indexes[0]) 108 | img_b, mask_b = self.load_img_and_mask(indexes[1]) 109 | img_c, mask_c = self.load_img_and_mask(indexes[2]) 110 | img_d, mask_d = self.load_img_and_mask(indexes[3]) 111 | 112 | img_a, mask_a = np.array(img_a), np.array(mask_a) 113 | img_b, mask_b = np.array(img_b), np.array(mask_b) 114 | img_c, mask_c = np.array(img_c), np.array(mask_c) 115 | img_d, mask_d = np.array(img_d), np.array(mask_d) 116 | 117 | w = self.img_size[1] 118 | h = self.img_size[0] 119 | 120 | start_x = w // 4 121 | strat_y = h // 4 122 | # The coordinates of the splice center 123 | offset_x = random.randint(start_x, (w - start_x)) 124 | offset_y = random.randint(strat_y, (h - strat_y)) 125 | 126 | crop_size_a = (offset_x, offset_y) 127 | crop_size_b = (w - offset_x, offset_y) 128 | crop_size_c = (offset_x, h - offset_y) 129 | crop_size_d = (w - offset_x, h - offset_y) 130 | 131 | random_crop_a = albu.RandomCrop(width=crop_size_a[0], height=crop_size_a[1]) 132 | random_crop_b = albu.RandomCrop(width=crop_size_b[0], height=crop_size_b[1]) 133 | random_crop_c = albu.RandomCrop(width=crop_size_c[0], height=crop_size_c[1]) 134 | random_crop_d = albu.RandomCrop(width=crop_size_d[0], height=crop_size_d[1]) 135 | 136 | croped_a = random_crop_a(image=img_a.copy(), mask=mask_a.copy()) 137 | croped_b = random_crop_b(image=img_b.copy(), mask=mask_b.copy()) 138 | croped_c = random_crop_c(image=img_c.copy(), mask=mask_c.copy()) 139 | croped_d = random_crop_d(image=img_d.copy(), mask=mask_d.copy()) 140 | 141 | img_crop_a, mask_crop_a = croped_a['image'], croped_a['mask'] 142 | img_crop_b, mask_crop_b = croped_b['image'], croped_b['mask'] 143 | img_crop_c, mask_crop_c = croped_c['image'], croped_c['mask'] 144 | img_crop_d, mask_crop_d = croped_d['image'], croped_d['mask'] 145 | 146 | top = np.concatenate((img_crop_a, img_crop_b), axis=1) 147 | bottom = np.concatenate((img_crop_c, img_crop_d), axis=1) 148 | img = np.concatenate((top, bottom), axis=0) 149 | 150 | top_mask = np.concatenate((mask_crop_a, mask_crop_b), axis=1) 151 | bottom_mask = np.concatenate((mask_crop_c, mask_crop_d), axis=1) 152 | mask = np.concatenate((top_mask, bottom_mask), axis=0) 153 | mask = np.ascontiguousarray(mask) 154 | img = np.ascontiguousarray(img) 155 | 156 | img = Image.fromarray(img) 157 | mask = Image.fromarray(mask) 158 | 159 | return img, mask -------------------------------------------------------------------------------- /geoseg/losses/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | from .balanced_bce import * 4 | from .bitempered_loss import * 5 | from .dice import * 6 | from .focal import * 7 | from .focal_cosine import * 8 | from .functional import * 9 | from .jaccard import * 10 | from .joint_loss import * 11 | from .lovasz import * 12 | from .soft_bce import * 13 | from .soft_ce import * 14 | from .soft_f1 import * 15 | from .wing_loss import * 16 | from .useful_loss import * 17 | -------------------------------------------------------------------------------- /geoseg/losses/balanced_bce.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | import torch 4 | import torch.nn.functional as F 5 | from torch import nn, Tensor 6 | 7 | __all__ = ["BalancedBCEWithLogitsLoss", "balanced_binary_cross_entropy_with_logits"] 8 | 9 | 10 | def balanced_binary_cross_entropy_with_logits( 11 | logits: Tensor, targets: Tensor, gamma: float = 1.0, ignore_index: Optional[int] = None, reduction: str = "mean" 12 | ) -> Tensor: 13 | """ 14 | Balanced binary cross entropy loss. 15 | 16 | Args: 17 | logits: 18 | targets: This loss function expects target values to be hard targets 0/1. 19 | gamma: Power factor for balancing weights 20 | ignore_index: 21 | reduction: 22 | 23 | Returns: 24 | Zero-sized tensor with reduced loss if `reduction` is `sum` or `mean`; Otherwise returns loss of the 25 | shape of `logits` tensor. 26 | """ 27 | pos_targets: Tensor = targets.eq(1).sum() 28 | neg_targets: Tensor = targets.eq(0).sum() 29 | 30 | num_targets = pos_targets + neg_targets 31 | pos_weight = torch.pow(neg_targets / (num_targets + 1e-7), gamma) 32 | neg_weight = 1.0 - pos_weight 33 | 34 | pos_term = pos_weight.pow(gamma) * targets * torch.nn.functional.logsigmoid(logits) 35 | neg_term = neg_weight.pow(gamma) * (1 - targets) * torch.nn.functional.logsigmoid(-logits) 36 | 37 | loss = -(pos_term + neg_term) 38 | 39 | if ignore_index is not None: 40 | loss = torch.masked_fill(loss, targets.eq(ignore_index), 0) 41 | 42 | if reduction == "mean": 43 | loss = loss.mean() 44 | 45 | if reduction == "sum": 46 | loss = loss.sum() 47 | 48 | return loss 49 | 50 | 51 | class BalancedBCEWithLogitsLoss(nn.Module): 52 | """ 53 | Balanced binary cross-entropy loss. 54 | 55 | https://arxiv.org/pdf/1504.06375.pdf (Formula 2) 56 | """ 57 | 58 | __constants__ = ["gamma", "reduction", "ignore_index"] 59 | 60 | def __init__(self, gamma: float = 1.0, reduction="mean", ignore_index: Optional[int] = None): 61 | """ 62 | 63 | Args: 64 | gamma: 65 | ignore_index: 66 | reduction: 67 | """ 68 | super().__init__() 69 | self.gamma = gamma 70 | self.reduction = reduction 71 | self.ignore_index = ignore_index 72 | 73 | def forward(self, output: Tensor, target: Tensor) -> Tensor: 74 | return balanced_binary_cross_entropy_with_logits( 75 | output, target, gamma=self.gamma, ignore_index=self.ignore_index, reduction=self.reduction 76 | ) 77 | -------------------------------------------------------------------------------- /geoseg/losses/bitempered_loss.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | import torch 4 | from torch import nn, Tensor 5 | 6 | __all__ = ["BiTemperedLogisticLoss", "BinaryBiTemperedLogisticLoss"] 7 | 8 | 9 | def log_t(u, t): 10 | """Compute log_t for `u'.""" 11 | if t == 1.0: 12 | return u.log() 13 | else: 14 | return (u.pow(1.0 - t) - 1.0) / (1.0 - t) 15 | 16 | 17 | def exp_t(u, t): 18 | """Compute exp_t for `u'.""" 19 | if t == 1: 20 | return u.exp() 21 | else: 22 | return (1.0 + (1.0 - t) * u).relu().pow(1.0 / (1.0 - t)) 23 | 24 | 25 | def compute_normalization_fixed_point(activations: Tensor, t: float, num_iters: int) -> Tensor: 26 | """Return the normalization value for each example (t > 1.0). 27 | Args: 28 | activations: A multi-dimensional tensor with last dimension `num_classes`. 29 | t: Temperature 2 (> 1.0 for tail heaviness). 30 | num_iters: Number of iterations to run the method. 31 | Return: A tensor of same shape as activation with the last dimension being 1. 32 | """ 33 | mu, _ = torch.max(activations, -1, keepdim=True) 34 | normalized_activations_step_0 = activations - mu 35 | 36 | normalized_activations = normalized_activations_step_0 37 | 38 | for _ in range(num_iters): 39 | logt_partition = torch.sum(exp_t(normalized_activations, t), -1, keepdim=True) 40 | normalized_activations = normalized_activations_step_0 * logt_partition.pow(1.0 - t) 41 | 42 | logt_partition = torch.sum(exp_t(normalized_activations, t), -1, keepdim=True) 43 | normalization_constants = -log_t(1.0 / logt_partition, t) + mu 44 | 45 | return normalization_constants 46 | 47 | 48 | def compute_normalization_binary_search(activations: Tensor, t: float, num_iters: int) -> Tensor: 49 | """Compute normalization value for each example (t < 1.0). 50 | Args: 51 | activations: A multi-dimensional tensor with last dimension `num_classes`. 52 | t: Temperature 2 (< 1.0 for finite support). 53 | num_iters: Number of iterations to run the method. 54 | Return: A tensor of same rank as activation with the last dimension being 1. 55 | """ 56 | mu, _ = torch.max(activations, -1, keepdim=True) 57 | normalized_activations = activations - mu 58 | 59 | effective_dim = torch.sum((normalized_activations > -1.0 / (1.0 - t)).to(torch.int32), dim=-1, keepdim=True).to( 60 | activations.dtype 61 | ) 62 | 63 | shape_partition = activations.shape[:-1] + (1,) 64 | lower = torch.zeros(shape_partition, dtype=activations.dtype, device=activations.device) 65 | upper = -log_t(1.0 / effective_dim, t) * torch.ones_like(lower) 66 | 67 | for _ in range(num_iters): 68 | logt_partition = (upper + lower) / 2.0 69 | sum_probs = torch.sum(exp_t(normalized_activations - logt_partition, t), dim=-1, keepdim=True) 70 | update = (sum_probs < 1.0).to(activations.dtype) 71 | lower = torch.reshape(lower * update + (1.0 - update) * logt_partition, shape_partition) 72 | upper = torch.reshape(upper * (1.0 - update) + update * logt_partition, shape_partition) 73 | 74 | logt_partition = (upper + lower) / 2.0 75 | return logt_partition + mu 76 | 77 | 78 | class ComputeNormalization(torch.autograd.Function): 79 | """ 80 | Class implementing custom backward pass for compute_normalization. See compute_normalization. 81 | """ 82 | 83 | @staticmethod 84 | def forward(ctx, activations, t, num_iters): 85 | if t < 1.0: 86 | normalization_constants = compute_normalization_binary_search(activations, t, num_iters) 87 | else: 88 | normalization_constants = compute_normalization_fixed_point(activations, t, num_iters) 89 | 90 | ctx.save_for_backward(activations, normalization_constants) 91 | ctx.t = t 92 | return normalization_constants 93 | 94 | @staticmethod 95 | def backward(ctx, grad_output): 96 | activations, normalization_constants = ctx.saved_tensors 97 | t = ctx.t 98 | normalized_activations = activations - normalization_constants 99 | probabilities = exp_t(normalized_activations, t) 100 | escorts = probabilities.pow(t) 101 | escorts = escorts / escorts.sum(dim=-1, keepdim=True) 102 | grad_input = escorts * grad_output 103 | 104 | return grad_input, None, None 105 | 106 | 107 | def compute_normalization(activations, t, num_iters=5): 108 | """Compute normalization value for each example. 109 | Backward pass is implemented. 110 | Args: 111 | activations: A multi-dimensional tensor with last dimension `num_classes`. 112 | t: Temperature 2 (> 1.0 for tail heaviness, < 1.0 for finite support). 113 | num_iters: Number of iterations to run the method. 114 | Return: A tensor of same rank as activation with the last dimension being 1. 115 | """ 116 | return ComputeNormalization.apply(activations, t, num_iters) 117 | 118 | 119 | def tempered_softmax(activations, t, num_iters=5): 120 | """Tempered softmax function. 121 | Args: 122 | activations: A multi-dimensional tensor with last dimension `num_classes`. 123 | t: Temperature > 1.0. 124 | num_iters: Number of iterations to run the method. 125 | Returns: 126 | A probabilities tensor. 127 | """ 128 | if t == 1.0: 129 | return activations.softmax(dim=-1) 130 | 131 | normalization_constants = compute_normalization(activations, t, num_iters) 132 | return exp_t(activations - normalization_constants, t) 133 | 134 | 135 | def bi_tempered_logistic_loss(activations, labels, t1, t2, label_smoothing=0.0, num_iters=5, reduction="mean"): 136 | """Bi-Tempered Logistic Loss. 137 | Args: 138 | activations: A multi-dimensional tensor with last dimension `num_classes`. 139 | labels: A tensor with shape and dtype as activations (onehot), 140 | or a long tensor of one dimension less than activations (pytorch standard) 141 | t1: Temperature 1 (< 1.0 for boundedness). 142 | t2: Temperature 2 (> 1.0 for tail heaviness, < 1.0 for finite support). 143 | label_smoothing: Label smoothing parameter between [0, 1). Default 0.0. 144 | num_iters: Number of iterations to run the method. Default 5. 145 | reduction: ``'none'`` | ``'mean'`` | ``'sum'``. Default ``'mean'``. 146 | ``'none'``: No reduction is applied, return shape is shape of 147 | activations without the last dimension. 148 | ``'mean'``: Loss is averaged over minibatch. Return shape (1,) 149 | ``'sum'``: Loss is summed over minibatch. Return shape (1,) 150 | Returns: 151 | A loss tensor. 152 | """ 153 | if len(labels.shape) < len(activations.shape): # not one-hot 154 | labels_onehot = torch.zeros_like(activations) 155 | labels_onehot.scatter_(1, labels[..., None], 1) 156 | else: 157 | labels_onehot = labels 158 | 159 | if label_smoothing > 0: 160 | num_classes = labels_onehot.shape[-1] 161 | labels_onehot = (1 - label_smoothing * num_classes / (num_classes - 1)) * labels_onehot + label_smoothing / ( 162 | num_classes - 1 163 | ) 164 | 165 | probabilities = tempered_softmax(activations, t2, num_iters) 166 | 167 | loss_values = ( 168 | labels_onehot * log_t(labels_onehot + 1e-10, t1) 169 | - labels_onehot * log_t(probabilities, t1) 170 | - labels_onehot.pow(2.0 - t1) / (2.0 - t1) 171 | + probabilities.pow(2.0 - t1) / (2.0 - t1) 172 | ) 173 | loss_values = loss_values.sum(dim=-1) # sum over classes 174 | 175 | if reduction == "none": 176 | return loss_values 177 | if reduction == "sum": 178 | return loss_values.sum() 179 | if reduction == "mean": 180 | return loss_values.mean() 181 | 182 | 183 | class BiTemperedLogisticLoss(nn.Module): 184 | """ 185 | 186 | https://ai.googleblog.com/2019/08/bi-tempered-logistic-loss-for-training.html 187 | https://arxiv.org/abs/1906.03361 188 | """ 189 | 190 | def __init__(self, t1: float, t2: float, smoothing=0.0, ignore_index=None, reduction: str = "mean"): 191 | """ 192 | 193 | Args: 194 | t1: 195 | t2: 196 | smoothing: 197 | ignore_index: 198 | reduction: 199 | """ 200 | super(BiTemperedLogisticLoss, self).__init__() 201 | self.t1 = t1 202 | self.t2 = t2 203 | self.smoothing = smoothing 204 | self.reduction = reduction 205 | self.ignore_index = ignore_index 206 | 207 | def forward(self, predictions: Tensor, targets: Tensor) -> Tensor: 208 | loss = bi_tempered_logistic_loss( 209 | predictions, targets, t1=self.t1, t2=self.t2, label_smoothing=self.smoothing, reduction="none" 210 | ) 211 | 212 | if self.ignore_index is not None: 213 | mask = ~targets.eq(self.ignore_index) 214 | loss *= mask 215 | 216 | if self.reduction == "mean": 217 | loss = loss.mean() 218 | elif self.reduction == "sum": 219 | loss = loss.sum() 220 | return loss 221 | 222 | 223 | class BinaryBiTemperedLogisticLoss(nn.Module): 224 | """ 225 | Modification of BiTemperedLogisticLoss for binary classification case. 226 | It's signature matches nn.BCEWithLogitsLoss: Predictions and target tensors must have shape [B,1,...] 227 | 228 | References: 229 | https://ai.googleblog.com/2019/08/bi-tempered-logistic-loss-for-training.html 230 | https://arxiv.org/abs/1906.03361 231 | """ 232 | 233 | def __init__( 234 | self, t1: float, t2: float, smoothing: float = 0.0, ignore_index: Optional[int] = None, reduction: str = "mean" 235 | ): 236 | """ 237 | 238 | Args: 239 | t1: 240 | t2: 241 | smoothing: 242 | ignore_index: 243 | reduction: 244 | """ 245 | super().__init__() 246 | self.t1 = t1 247 | self.t2 = t2 248 | self.smoothing = smoothing 249 | self.reduction = reduction 250 | self.ignore_index = ignore_index 251 | 252 | def forward(self, predictions: Tensor, targets: Tensor) -> Tensor: 253 | """ 254 | Forward method of the loss function 255 | 256 | Args: 257 | predictions: [B,1,...] 258 | targets: [B,1,...] 259 | 260 | Returns: 261 | Zero-sized tensor with reduced loss if self.reduction is `sum` or `mean`; Otherwise returns loss of the 262 | shape of `predictions` tensor. 263 | """ 264 | if predictions.size(1) != 1 or targets.size(1) != 1: 265 | raise ValueError("Channel dimension for predictions and targets must be equal to 1") 266 | 267 | loss = bi_tempered_logistic_loss( 268 | torch.cat([-predictions, predictions], dim=1).moveaxis(1, -1), 269 | torch.cat([1 - targets, targets], dim=1).moveaxis(1, -1), 270 | t1=self.t1, 271 | t2=self.t2, 272 | label_smoothing=self.smoothing, 273 | reduction="none", 274 | ).unsqueeze(dim=1) 275 | 276 | if self.ignore_index is not None: 277 | mask = targets.eq(self.ignore_index) 278 | loss = torch.masked_fill(loss, mask, 0) 279 | 280 | if self.reduction == "mean": 281 | loss = loss.mean() 282 | elif self.reduction == "sum": 283 | loss = loss.sum() 284 | return loss 285 | -------------------------------------------------------------------------------- /geoseg/losses/cel1.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import logging 3 | import torch.nn as nn 4 | import torch.nn.functional as F 5 | from typing import Optional 6 | 7 | BINARY_MODE: str = "binary" 8 | 9 | MULTICLASS_MODE: str = "multiclass" 10 | 11 | MULTILABEL_MODE: str = "multilabel" 12 | 13 | 14 | EPS = 1e-10 15 | 16 | 17 | logger = logging.getLogger(__name__) 18 | 19 | 20 | def expand_onehot_labels(labels, target_shape, ignore_index): 21 | """Expand onehot labels to match the size of prediction.""" 22 | bin_labels = labels.new_zeros(target_shape) 23 | valid_mask = (labels >= 0) & (labels != ignore_index) 24 | inds = torch.nonzero(valid_mask, as_tuple=True) 25 | 26 | if inds[0].numel() > 0: 27 | if labels.dim() == 3: 28 | bin_labels[inds[0], labels[valid_mask], inds[1], inds[2]] = 1 29 | else: 30 | bin_labels[inds[0], labels[valid_mask]] = 1 31 | 32 | return bin_labels, valid_mask 33 | 34 | 35 | def get_region_proportion(x: torch.Tensor, valid_mask: torch.Tensor = None) -> torch.Tensor: 36 | """Get region proportion 37 | Args: 38 | x : one-hot label map/mask 39 | valid_mask : indicate the considered elements 40 | """ 41 | if valid_mask is not None: 42 | if valid_mask.dim() == 4: 43 | x = torch.einsum("bcwh, bcwh->bcwh", x, valid_mask) 44 | cardinality = torch.einsum("bcwh->bc", valid_mask) 45 | else: 46 | x = torch.einsum("bcwh,bwh->bcwh", x, valid_mask) 47 | cardinality = torch.einsum("bwh->b", valid_mask).unsqueeze(dim=1).repeat(1, x.shape[1]) 48 | else: 49 | cardinality = x.shape[2] * x.shape[3] 50 | 51 | region_proportion = (torch.einsum("bcwh->bc", x) + EPS) / (cardinality + EPS) 52 | 53 | return region_proportion 54 | 55 | 56 | class CompoundLoss(nn.Module): 57 | """ 58 | The base class for implementing a compound loss: 59 | l = l_1 + alpha * l_2 60 | """ 61 | def __init__(self, mode: str = MULTICLASS_MODE, 62 | alpha: float = 0.1, 63 | factor: float = 5., 64 | step_size: int = 0, 65 | max_alpha: float = 100., 66 | temp: float = 1., 67 | ignore_index: int = 255, 68 | background_index: int = -1, 69 | weight: Optional[torch.Tensor] = None) -> None: 70 | assert mode in {BINARY_MODE, MULTILABEL_MODE, MULTICLASS_MODE} 71 | super().__init__() 72 | self.mode = mode 73 | self.alpha = alpha 74 | self.max_alpha = max_alpha 75 | self.factor = factor 76 | self.step_size = step_size 77 | self.temp = temp 78 | self.ignore_index = ignore_index 79 | self.background_index = background_index 80 | self.weight = weight 81 | 82 | def cross_entropy(self, inputs: torch.Tensor, labels: torch.Tensor): 83 | if self.mode == MULTICLASS_MODE: 84 | loss = F.cross_entropy( 85 | inputs, labels, weight=self.weight, ignore_index=self.ignore_index) 86 | else: 87 | if labels.dim() == 3: 88 | labels = labels.unsqueeze(dim=1) 89 | loss = F.binary_cross_entropy_with_logits(inputs, labels.type(torch.float32)) 90 | return loss 91 | 92 | def adjust_alpha(self, epoch: int) -> None: 93 | if self.step_size == 0: 94 | return 95 | if (epoch + 1) % self.step_size == 0: 96 | curr_alpha = self.alpha 97 | self.alpha = min(self.alpha * self.factor, self.max_alpha) 98 | logger.info( 99 | "CompoundLoss : Adjust the tradoff param alpha : {:.3g} -> {:.3g}".format(curr_alpha, self.alpha) 100 | ) 101 | 102 | def get_gt_proportion(self, mode: str, 103 | labels: torch.Tensor, 104 | target_shape, 105 | ignore_index: int = 255): 106 | if mode == MULTICLASS_MODE: 107 | bin_labels, valid_mask = expand_onehot_labels(labels, target_shape, ignore_index) 108 | else: 109 | valid_mask = (labels >= 0) & (labels != ignore_index) 110 | if labels.dim() == 3: 111 | labels = labels.unsqueeze(dim=1) 112 | bin_labels = labels 113 | gt_proportion = get_region_proportion(bin_labels, valid_mask) 114 | return gt_proportion, valid_mask 115 | 116 | def get_pred_proportion(self, mode: str, 117 | logits: torch.Tensor, 118 | temp: float = 1.0, 119 | valid_mask=None): 120 | if mode == MULTICLASS_MODE: 121 | preds = F.log_softmax(temp * logits, dim=1).exp() 122 | else: 123 | preds = F.logsigmoid(temp * logits).exp() 124 | pred_proportion = get_region_proportion(preds, valid_mask) 125 | return pred_proportion 126 | 127 | 128 | class CrossEntropyWithL1(CompoundLoss): 129 | """ 130 | Cross entropy loss with region size priors measured by l1. 131 | The loss can be described as: 132 | l = CE(X, Y) + alpha * |gt_region - prob_region| 133 | """ 134 | def forward(self, inputs: torch.Tensor, labels: torch.Tensor): 135 | # ce term 136 | loss_ce = self.cross_entropy(inputs, labels) 137 | # regularization 138 | gt_proportion, valid_mask = self.get_gt_proportion(self.mode, labels, inputs.shape) 139 | pred_proportion = self.get_pred_proportion(self.mode, inputs, temp=self.temp, valid_mask=valid_mask) 140 | loss_reg = (pred_proportion - gt_proportion).abs().mean() 141 | 142 | loss = loss_ce + self.alpha * loss_reg 143 | 144 | return loss 145 | 146 | 147 | class CrossEntropyWithKL(CompoundLoss): 148 | """ 149 | Cross entropy loss with region size priors measured by l1. 150 | The loss can be described as: 151 | l = CE(X, Y) + alpha * KL(gt_region || prob_region) 152 | """ 153 | def kl_div(self, p : torch.Tensor, q : torch.Tensor) -> torch.Tensor: 154 | x = p * torch.log(p / q) 155 | x = torch.einsum("ij->i", x) 156 | return x 157 | 158 | def forward(self, inputs: torch.Tensor, labels: torch.Tensor): 159 | # ce term 160 | loss_ce = self.cross_entropy(inputs, labels) 161 | # regularization 162 | gt_proportion, valid_mask = self.get_gt_proportion(self.mode, labels, inputs.shape) 163 | pred_proportion = self.get_pred_proportion(self.mode, inputs, temp=self.temp, valid_mask=valid_mask) 164 | 165 | if self.mode == BINARY_MODE: 166 | regularizer = ( 167 | self.kl_div(gt_proportion, pred_proportion) 168 | + self.kl_div(1 - gt_proportion, 1 - pred_proportion) 169 | ).mean() 170 | else: 171 | regularizer = self.kl_div(gt_proportion, pred_proportion).mean() 172 | 173 | loss = loss_ce + self.alpha * regularizer 174 | 175 | return loss -------------------------------------------------------------------------------- /geoseg/losses/dice.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | import torch 4 | import torch.nn.functional as F 5 | from torch import Tensor 6 | from torch.nn.modules.loss import _Loss 7 | import numpy as np 8 | 9 | from .functional import soft_dice_score 10 | 11 | __all__ = ["DiceLoss"] 12 | 13 | BINARY_MODE = "binary" 14 | MULTICLASS_MODE = "multiclass" 15 | MULTILABEL_MODE = "multilabel" 16 | 17 | 18 | def to_tensor(x, dtype=None) -> torch.Tensor: 19 | if isinstance(x, torch.Tensor): 20 | if dtype is not None: 21 | x = x.type(dtype) 22 | return x 23 | if isinstance(x, np.ndarray) and x.dtype.kind not in {"O", "M", "U", "S"}: 24 | x = torch.from_numpy(x) 25 | if dtype is not None: 26 | x = x.type(dtype) 27 | return x 28 | if isinstance(x, (list, tuple)): 29 | x = np.ndarray(x) 30 | x = torch.from_numpy(x) 31 | if dtype is not None: 32 | x = x.type(dtype) 33 | return x 34 | 35 | raise ValueError("Unsupported input type" + str(type(x))) 36 | 37 | 38 | class DiceLoss(_Loss): 39 | """ 40 | Implementation of Dice loss for image segmentation task. 41 | It supports binary, multiclass and multilabel cases 42 | """ 43 | 44 | def __init__( 45 | self, 46 | mode: str = 'multiclass', 47 | classes: List[int] = None, 48 | log_loss=False, 49 | from_logits=True, 50 | smooth: float = 0.0, 51 | ignore_index=None, 52 | eps=1e-7, 53 | ): 54 | """ 55 | 56 | :param mode: Metric mode {'binary', 'multiclass', 'multilabel'} 57 | :param classes: Optional list of classes that contribute in loss computation; 58 | By default, all channels are included. 59 | :param log_loss: If True, loss computed as `-log(jaccard)`; otherwise `1 - jaccard` 60 | :param from_logits: If True assumes input is raw logits 61 | :param smooth: 62 | :param ignore_index: Label that indicates ignored pixels (does not contribute to loss) 63 | :param eps: Small epsilon for numerical stability 64 | """ 65 | assert mode in {BINARY_MODE, MULTILABEL_MODE, MULTICLASS_MODE} 66 | super(DiceLoss, self).__init__() 67 | self.mode = mode 68 | if classes is not None: 69 | assert mode != BINARY_MODE, "Masking classes is not supported with mode=binary" 70 | classes = to_tensor(classes, dtype=torch.long) 71 | 72 | self.classes = classes 73 | self.from_logits = from_logits 74 | self.smooth = smooth 75 | self.eps = eps 76 | self.ignore_index = ignore_index 77 | self.log_loss = log_loss 78 | 79 | def forward(self, y_pred: Tensor, y_true: Tensor) -> Tensor: 80 | """ 81 | 82 | :param y_pred: NxCxHxW 83 | :param y_true: NxHxW 84 | :return: scalar 85 | """ 86 | assert y_true.size(0) == y_pred.size(0) 87 | 88 | if self.from_logits: 89 | # Apply activations to get [0..1] class probabilities 90 | # Using Log-Exp as this gives more numerically stable result and does not cause vanishing gradient on 91 | # extreme values 0 and 1 92 | if self.mode == MULTICLASS_MODE: 93 | y_pred = y_pred.log_softmax(dim=1).exp() 94 | else: 95 | y_pred = F.logsigmoid(y_pred).exp() 96 | 97 | bs = y_true.size(0) 98 | num_classes = y_pred.size(1) 99 | dims = (0, 2) 100 | 101 | if self.mode == BINARY_MODE: 102 | y_true = y_true.view(bs, 1, -1) 103 | y_pred = y_pred.view(bs, 1, -1) 104 | 105 | if self.ignore_index is not None: 106 | mask = y_true != self.ignore_index 107 | y_pred = y_pred * mask 108 | y_true = y_true * mask 109 | 110 | if self.mode == MULTICLASS_MODE: 111 | y_true = y_true.view(bs, -1) 112 | y_pred = y_pred.view(bs, num_classes, -1) 113 | 114 | if self.ignore_index is not None: 115 | mask = y_true != self.ignore_index 116 | y_pred = y_pred * mask.unsqueeze(1) 117 | 118 | y_true = F.one_hot((y_true * mask).to(torch.long), num_classes) # N,H*W -> N,H*W, C 119 | y_true = y_true.permute(0, 2, 1) * mask.unsqueeze(1) # H, C, H*W 120 | else: 121 | y_true = F.one_hot(y_true, num_classes) # N,H*W -> N,H*W, C 122 | y_true = y_true.permute(0, 2, 1) # H, C, H*W 123 | 124 | if self.mode == MULTILABEL_MODE: 125 | y_true = y_true.view(bs, num_classes, -1) 126 | y_pred = y_pred.view(bs, num_classes, -1) 127 | 128 | if self.ignore_index is not None: 129 | mask = y_true != self.ignore_index 130 | y_pred = y_pred * mask 131 | y_true = y_true * mask 132 | 133 | scores = soft_dice_score(y_pred, y_true.type_as(y_pred), smooth=self.smooth, eps=self.eps, dims=dims) 134 | 135 | if self.log_loss: 136 | loss = -torch.log(scores.clamp_min(self.eps)) 137 | else: 138 | loss = 1.0 - scores 139 | 140 | # Dice loss is undefined for non-empty classes 141 | # So we zero contribution of channel that does not have true pixels 142 | # NOTE: A better workaround would be to use loss term `mean(y_pred)` 143 | # for this case, however it will be a modified jaccard loss 144 | 145 | mask = y_true.sum(dims) > 0 146 | loss *= mask.to(loss.dtype) 147 | 148 | if self.classes is not None: 149 | loss = loss[self.classes] 150 | 151 | return loss.mean() 152 | -------------------------------------------------------------------------------- /geoseg/losses/focal.py: -------------------------------------------------------------------------------- 1 | from functools import partial 2 | 3 | import torch 4 | from torch.nn.modules.loss import _Loss 5 | 6 | from .functional import focal_loss_with_logits 7 | 8 | __all__ = ["BinaryFocalLoss", "FocalLoss"] 9 | 10 | 11 | class BinaryFocalLoss(_Loss): 12 | def __init__( 13 | self, 14 | alpha=0.5, 15 | gamma: float = 2.0, 16 | ignore_index=None, 17 | reduction="mean", 18 | normalized=False, 19 | reduced_threshold=None, 20 | ): 21 | """ 22 | 23 | :param alpha: Prior probability of having positive value in target. 24 | :param gamma: Power factor for dampening weight (focal strenght). 25 | :param ignore_index: If not None, targets may contain values to be ignored. 26 | Target values equal to ignore_index will be ignored from loss computation. 27 | :param reduced: Switch to reduced focal loss. Note, when using this mode you should use `reduction="sum"`. 28 | :param threshold: 29 | """ 30 | super().__init__() 31 | self.ignore_index = ignore_index 32 | self.focal_loss_fn = partial( 33 | focal_loss_with_logits, 34 | alpha=alpha, 35 | gamma=gamma, 36 | reduced_threshold=reduced_threshold, 37 | reduction=reduction, 38 | normalized=normalized, 39 | ignore_index=ignore_index, 40 | ) 41 | 42 | def forward(self, label_input, label_target): 43 | """Compute focal loss for binary classification problem.""" 44 | loss = self.focal_loss_fn(label_input, label_target) 45 | return loss 46 | 47 | 48 | class FocalLoss(_Loss): 49 | def __init__(self, alpha=0.5, gamma=2, ignore_index=None, reduction="mean", normalized=False, reduced_threshold=None): 50 | """ 51 | Focal loss for multi-class problem. 52 | 53 | :param alpha: 54 | :param gamma: 55 | :param ignore_index: If not None, targets with given index are ignored 56 | :param reduced_threshold: A threshold factor for computing reduced focal loss 57 | """ 58 | super().__init__() 59 | self.ignore_index = ignore_index 60 | self.focal_loss_fn = partial( 61 | focal_loss_with_logits, 62 | alpha=alpha, 63 | gamma=gamma, 64 | reduced_threshold=reduced_threshold, 65 | reduction=reduction, 66 | normalized=normalized, 67 | ) 68 | 69 | def forward(self, label_input, label_target): 70 | num_classes = label_input.size(1) 71 | loss = 0 72 | 73 | # Filter anchors with -1 label from loss computation 74 | if self.ignore_index is not None: 75 | not_ignored = label_target != self.ignore_index 76 | 77 | for cls in range(num_classes): 78 | cls_label_target = (label_target == cls).long() 79 | cls_label_input = label_input[:, cls, ...] 80 | 81 | if self.ignore_index is not None: 82 | cls_label_target = cls_label_target[not_ignored] 83 | cls_label_input = cls_label_input[not_ignored] 84 | 85 | loss += self.focal_loss_fn(cls_label_input, cls_label_target) 86 | return loss 87 | -------------------------------------------------------------------------------- /geoseg/losses/focal_cosine.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | from torch import nn, Tensor 3 | import torch.nn.functional as F 4 | import torch 5 | 6 | __all__ = ["FocalCosineLoss"] 7 | 8 | 9 | class FocalCosineLoss(nn.Module): 10 | """ 11 | Implementation Focal cosine loss from the "Data-Efficient Deep Learning Method for Image Classification 12 | Using Data Augmentation, Focal Cosine Loss, and Ensemble" (https://arxiv.org/abs/2007.07805). 13 | 14 | Credit: https://www.kaggle.com/c/cassava-leaf-disease-classification/discussion/203271 15 | """ 16 | 17 | def __init__(self, alpha: float = 1, gamma: float = 2, xent: float = 0.1, reduction="mean"): 18 | super(FocalCosineLoss, self).__init__() 19 | self.alpha = alpha 20 | self.gamma = gamma 21 | self.xent = xent 22 | self.reduction = reduction 23 | 24 | def forward(self, input: Tensor, target: Tensor) -> Tensor: 25 | cosine_loss = F.cosine_embedding_loss( 26 | input, 27 | torch.nn.functional.one_hot(target, num_classes=input.size(-1)), 28 | torch.tensor([1], device=target.device), 29 | reduction=self.reduction, 30 | ) 31 | 32 | cent_loss = F.cross_entropy(F.normalize(input), target, reduction="none") 33 | pt = torch.exp(-cent_loss) 34 | focal_loss = self.alpha * (1 - pt) ** self.gamma * cent_loss 35 | 36 | if self.reduction == "mean": 37 | focal_loss = torch.mean(focal_loss) 38 | 39 | return cosine_loss + self.xent * focal_loss 40 | -------------------------------------------------------------------------------- /geoseg/losses/functional.py: -------------------------------------------------------------------------------- 1 | import math 2 | from typing import Optional 3 | 4 | import torch 5 | import torch.nn.functional as F 6 | 7 | __all__ = [ 8 | "focal_loss_with_logits", 9 | "softmax_focal_loss_with_logits", 10 | "soft_jaccard_score", 11 | "soft_dice_score", 12 | "wing_loss", 13 | ] 14 | 15 | 16 | def focal_loss_with_logits( 17 | output: torch.Tensor, 18 | target: torch.Tensor, 19 | gamma: float = 2.0, 20 | alpha: Optional[float] = 0.25, 21 | reduction: str = "mean", 22 | normalized: bool = False, 23 | reduced_threshold: Optional[float] = None, 24 | eps: float = 1e-6, 25 | ignore_index=None, 26 | ) -> torch.Tensor: 27 | """Compute binary focal loss between target and output logits. 28 | 29 | See :class:`~pytorch_toolbelt.losses.FocalLoss` for details. 30 | 31 | Args: 32 | output: Tensor of arbitrary shape (predictions of the models) 33 | target: Tensor of the same shape as input 34 | gamma: Focal loss power factor 35 | alpha: Weight factor to balance positive and negative samples. Alpha must be in [0...1] range, 36 | high values will give more weight to positive class. 37 | reduction (string, optional): Specifies the reduction to apply to the output: 38 | 'none' | 'mean' | 'sum' | 'batchwise_mean'. 'none': no reduction will be applied, 39 | 'mean': the sum of the output will be divided by the number of 40 | elements in the output, 'sum': the output will be summed. Note: :attr:`size_average` 41 | and :attr:`reduce` are in the process of being deprecated, and in the meantime, 42 | specifying either of those two args will override :attr:`reduction`. 43 | 'batchwise_mean' computes mean loss per sample in batch. Default: 'mean' 44 | normalized (bool): Compute normalized focal loss (https://arxiv.org/pdf/1909.07829.pdf). 45 | reduced_threshold (float, optional): Compute reduced focal loss (https://arxiv.org/abs/1903.01347). 46 | 47 | References: 48 | https://github.com/open-mmlab/mmdetection/blob/master/mmdet/core/loss/losses.py 49 | """ 50 | target = target.type_as(output) 51 | 52 | p = torch.sigmoid(output) 53 | ce_loss = F.binary_cross_entropy_with_logits(output, target, reduction="none") 54 | pt = p * target + (1 - p) * (1 - target) 55 | 56 | # compute the loss 57 | if reduced_threshold is None: 58 | focal_term = (1.0 - pt).pow(gamma) 59 | else: 60 | focal_term = ((1.0 - pt) / reduced_threshold).pow(gamma) 61 | focal_term = torch.masked_fill(focal_term, pt < reduced_threshold, 1) 62 | 63 | loss = focal_term * ce_loss 64 | 65 | if alpha is not None: 66 | loss *= alpha * target + (1 - alpha) * (1 - target) 67 | 68 | if ignore_index is not None: 69 | ignore_mask = target.eq(ignore_index) 70 | loss = torch.masked_fill(loss, ignore_mask, 0) 71 | if normalized: 72 | focal_term = torch.masked_fill(focal_term, ignore_mask, 0) 73 | 74 | if normalized: 75 | norm_factor = focal_term.sum(dtype=torch.float32).clamp_min(eps) 76 | loss /= norm_factor 77 | 78 | if reduction == "mean": 79 | loss = loss.mean() 80 | if reduction == "sum": 81 | loss = loss.sum(dtype=torch.float32) 82 | if reduction == "batchwise_mean": 83 | loss = loss.sum(dim=0, dtype=torch.float32) 84 | 85 | return loss 86 | 87 | 88 | def softmax_focal_loss_with_logits( 89 | output: torch.Tensor, 90 | target: torch.Tensor, 91 | gamma: float = 2.0, 92 | reduction="mean", 93 | normalized=False, 94 | reduced_threshold: Optional[float] = None, 95 | eps: float = 1e-6, 96 | ) -> torch.Tensor: 97 | """ 98 | Softmax version of focal loss between target and output logits. 99 | See :class:`~pytorch_toolbelt.losses.FocalLoss` for details. 100 | 101 | Args: 102 | output: Tensor of shape [B, C, *] (Similar to nn.CrossEntropyLoss) 103 | target: Tensor of shape [B, *] (Similar to nn.CrossEntropyLoss) 104 | reduction (string, optional): Specifies the reduction to apply to the output: 105 | 'none' | 'mean' | 'sum' | 'batchwise_mean'. 'none': no reduction will be applied, 106 | 'mean': the sum of the output will be divided by the number of 107 | elements in the output, 'sum': the output will be summed. Note: :attr:`size_average` 108 | and :attr:`reduce` are in the process of being deprecated, and in the meantime, 109 | specifying either of those two args will override :attr:`reduction`. 110 | 'batchwise_mean' computes mean loss per sample in batch. Default: 'mean' 111 | normalized (bool): Compute normalized focal loss (https://arxiv.org/pdf/1909.07829.pdf). 112 | reduced_threshold (float, optional): Compute reduced focal loss (https://arxiv.org/abs/1903.01347). 113 | """ 114 | log_softmax = F.log_softmax(output, dim=1) 115 | 116 | loss = F.nll_loss(log_softmax, target, reduction="none") 117 | pt = torch.exp(-loss) 118 | 119 | # compute the loss 120 | if reduced_threshold is None: 121 | focal_term = (1.0 - pt).pow(gamma) 122 | else: 123 | focal_term = ((1.0 - pt) / reduced_threshold).pow(gamma) 124 | focal_term[pt < reduced_threshold] = 1 125 | 126 | loss = focal_term * loss 127 | 128 | if normalized: 129 | norm_factor = focal_term.sum().clamp_min(eps) 130 | loss = loss / norm_factor 131 | 132 | if reduction == "mean": 133 | loss = loss.mean() 134 | if reduction == "sum": 135 | loss = loss.sum() 136 | if reduction == "batchwise_mean": 137 | loss = loss.sum(0) 138 | 139 | return loss 140 | 141 | 142 | def soft_jaccard_score( 143 | output: torch.Tensor, target: torch.Tensor, smooth: float = 0.0, eps: float = 1e-7, dims=None 144 | ) -> torch.Tensor: 145 | """ 146 | 147 | :param output: 148 | :param target: 149 | :param smooth: 150 | :param eps: 151 | :param dims: 152 | :return: 153 | 154 | Shape: 155 | - Input: :math:`(N, NC, *)` where :math:`*` means 156 | any number of additional dimensions 157 | - Target: :math:`(N, NC, *)`, same shape as the input 158 | - Output: scalar. 159 | 160 | """ 161 | assert output.size() == target.size() 162 | 163 | if dims is not None: 164 | intersection = torch.sum(output * target, dim=dims) 165 | cardinality = torch.sum(output + target, dim=dims) 166 | else: 167 | intersection = torch.sum(output * target) 168 | cardinality = torch.sum(output + target) 169 | 170 | union = cardinality - intersection 171 | jaccard_score = (intersection + smooth) / (union + smooth).clamp_min(eps) 172 | return jaccard_score 173 | 174 | 175 | def soft_dice_score( 176 | output: torch.Tensor, target: torch.Tensor, smooth: float = 0.0, eps: float = 1e-7, dims=None 177 | ) -> torch.Tensor: 178 | """ 179 | 180 | :param output: 181 | :param target: 182 | :param smooth: 183 | :param eps: 184 | :return: 185 | 186 | Shape: 187 | - Input: :math:`(N, NC, *)` where :math:`*` means any number 188 | of additional dimensions 189 | - Target: :math:`(N, NC, *)`, same shape as the input 190 | - Output: scalar. 191 | 192 | """ 193 | assert output.size() == target.size() 194 | if dims is not None: 195 | intersection = torch.sum(output * target, dim=dims) 196 | cardinality = torch.sum(output + target, dim=dims) 197 | else: 198 | intersection = torch.sum(output * target) 199 | cardinality = torch.sum(output + target) 200 | dice_score = (2.0 * intersection + smooth) / (cardinality + smooth).clamp_min(eps) 201 | return dice_score 202 | 203 | 204 | def wing_loss(output: torch.Tensor, target: torch.Tensor, width=5, curvature=0.5, reduction="mean"): 205 | """ 206 | https://arxiv.org/pdf/1711.06753.pdf 207 | :param output: 208 | :param target: 209 | :param width: 210 | :param curvature: 211 | :param reduction: 212 | :return: 213 | """ 214 | diff_abs = (target - output).abs() 215 | loss = diff_abs.clone() 216 | 217 | idx_smaller = diff_abs < width 218 | idx_bigger = diff_abs >= width 219 | 220 | loss[idx_smaller] = width * torch.log(1 + diff_abs[idx_smaller] / curvature) 221 | 222 | C = width - width * math.log(1 + width / curvature) 223 | loss[idx_bigger] = loss[idx_bigger] - C 224 | 225 | if reduction == "sum": 226 | loss = loss.sum() 227 | 228 | if reduction == "mean": 229 | loss = loss.mean() 230 | 231 | return loss 232 | 233 | 234 | def label_smoothed_nll_loss( 235 | lprobs: torch.Tensor, target: torch.Tensor, epsilon: float, ignore_index=None, reduction="mean", dim=-1 236 | ) -> torch.Tensor: 237 | """ 238 | 239 | Source: https://github.com/pytorch/fairseq/blob/master/fairseq/criterions/label_smoothed_cross_entropy.py 240 | 241 | :param lprobs: Log-probabilities of predictions (e.g after log_softmax) 242 | :param target: 243 | :param epsilon: 244 | :param ignore_index: 245 | :param reduction: 246 | :return: 247 | """ 248 | if target.dim() == lprobs.dim() - 1: 249 | target = target.unsqueeze(dim) 250 | 251 | if ignore_index is not None: 252 | pad_mask = target.eq(ignore_index) 253 | target = target.masked_fill(pad_mask, 0) 254 | nll_loss = -lprobs.gather(dim=dim, index=target) 255 | smooth_loss = -lprobs.sum(dim=dim, keepdim=True) 256 | 257 | # nll_loss.masked_fill_(pad_mask, 0.0) 258 | # smooth_loss.masked_fill_(pad_mask, 0.0) 259 | nll_loss = nll_loss.masked_fill(pad_mask, 0.0) 260 | smooth_loss = smooth_loss.masked_fill(pad_mask, 0.0) 261 | else: 262 | nll_loss = -lprobs.gather(dim=dim, index=target) 263 | smooth_loss = -lprobs.sum(dim=dim, keepdim=True) 264 | 265 | nll_loss = nll_loss.squeeze(dim) 266 | smooth_loss = smooth_loss.squeeze(dim) 267 | 268 | if reduction == "sum": 269 | nll_loss = nll_loss.sum() 270 | smooth_loss = smooth_loss.sum() 271 | if reduction == "mean": 272 | nll_loss = nll_loss.mean() 273 | smooth_loss = smooth_loss.mean() 274 | 275 | eps_i = epsilon / lprobs.size(dim) 276 | loss = (1.0 - epsilon) * nll_loss + eps_i * smooth_loss 277 | return loss 278 | -------------------------------------------------------------------------------- /geoseg/losses/jaccard.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | import torch 4 | import torch.nn.functional as F 5 | from .dice import to_tensor 6 | from torch import Tensor 7 | from torch.nn.modules.loss import _Loss 8 | 9 | from .functional import soft_jaccard_score 10 | 11 | __all__ = ["JaccardLoss", "BINARY_MODE", "MULTICLASS_MODE", "MULTILABEL_MODE"] 12 | 13 | BINARY_MODE = "binary" 14 | MULTICLASS_MODE = "multiclass" 15 | MULTILABEL_MODE = "multilabel" 16 | 17 | 18 | class JaccardLoss(_Loss): 19 | """ 20 | Implementation of Jaccard loss for image segmentation task. 21 | It supports binary, multi-class and multi-label cases. 22 | """ 23 | 24 | def __init__(self, mode: str, classes: List[int] = None, log_loss=False, from_logits=True, smooth=0, eps=1e-7): 25 | """ 26 | 27 | :param mode: Metric mode {'binary', 'multiclass', 'multilabel'} 28 | :param classes: Optional list of classes that contribute in loss computation; 29 | By default, all channels are included. 30 | :param log_loss: If True, loss computed as `-log(jaccard)`; otherwise `1 - jaccard` 31 | :param from_logits: If True assumes input is raw logits 32 | :param smooth: 33 | :param eps: Small epsilon for numerical stability 34 | """ 35 | assert mode in {BINARY_MODE, MULTILABEL_MODE, MULTICLASS_MODE} 36 | super(JaccardLoss, self).__init__() 37 | self.mode = mode 38 | if classes is not None: 39 | assert mode != BINARY_MODE, "Masking classes is not supported with mode=binary" 40 | classes = to_tensor(classes, dtype=torch.long) 41 | 42 | self.classes = classes 43 | self.from_logits = from_logits 44 | self.smooth = smooth 45 | self.eps = eps 46 | self.log_loss = log_loss 47 | 48 | def forward(self, y_pred: Tensor, y_true: Tensor) -> Tensor: 49 | """ 50 | 51 | :param y_pred: NxCxHxW 52 | :param y_true: NxHxW 53 | :return: scalar 54 | """ 55 | assert y_true.size(0) == y_pred.size(0) 56 | 57 | if self.from_logits: 58 | # Apply activations to get [0..1] class probabilities 59 | # Using Log-Exp as this gives more numerically stable result and does not cause vanishing gradient on 60 | # extreme values 0 and 1 61 | if self.mode == MULTICLASS_MODE: 62 | y_pred = y_pred.log_softmax(dim=1).exp() 63 | else: 64 | y_pred = F.logsigmoid(y_pred).exp() 65 | 66 | bs = y_true.size(0) 67 | num_classes = y_pred.size(1) 68 | dims = (0, 2) 69 | 70 | if self.mode == BINARY_MODE: 71 | y_true = y_true.view(bs, 1, -1) 72 | y_pred = y_pred.view(bs, 1, -1) 73 | 74 | if self.mode == MULTICLASS_MODE: 75 | y_true = y_true.view(bs, -1) 76 | y_pred = y_pred.view(bs, num_classes, -1) 77 | 78 | y_true = F.one_hot(y_true, num_classes) # N,H*W -> N,H*W, C 79 | y_true = y_true.permute(0, 2, 1) # H, C, H*W 80 | 81 | if self.mode == MULTILABEL_MODE: 82 | y_true = y_true.view(bs, num_classes, -1) 83 | y_pred = y_pred.view(bs, num_classes, -1) 84 | 85 | scores = soft_jaccard_score(y_pred, y_true.type(y_pred.dtype), smooth=self.smooth, eps=self.eps, dims=dims) 86 | 87 | if self.log_loss: 88 | loss = -torch.log(scores.clamp_min(self.eps)) 89 | else: 90 | loss = 1.0 - scores 91 | 92 | # IoU loss is defined for non-empty classes 93 | # So we zero contribution of channel that does not have true pixels 94 | # NOTE: A better workaround would be to use loss term `mean(y_pred)` 95 | # for this case, however it will be a modified jaccard loss 96 | 97 | mask = y_true.sum(dims) > 0 98 | loss *= mask.float() 99 | 100 | if self.classes is not None: 101 | loss = loss[self.classes] 102 | 103 | return loss.mean() 104 | -------------------------------------------------------------------------------- /geoseg/losses/joint_loss.py: -------------------------------------------------------------------------------- 1 | from torch import nn 2 | from torch.nn.modules.loss import _Loss 3 | 4 | __all__ = ["JointLoss", "WeightedLoss"] 5 | 6 | 7 | class WeightedLoss(_Loss): 8 | """Wrapper class around loss function that applies weighted with fixed factor. 9 | This class helps to balance multiple losses if they have different scales 10 | """ 11 | 12 | def __init__(self, loss, weight=1.0): 13 | super().__init__() 14 | self.loss = loss 15 | self.weight = weight 16 | 17 | def forward(self, *input): 18 | return self.loss(*input) * self.weight 19 | 20 | 21 | class JointLoss(_Loss): 22 | """ 23 | Wrap two loss functions into one. This class computes a weighted sum of two losses. 24 | """ 25 | 26 | def __init__(self, first: nn.Module, second: nn.Module, first_weight=1.0, second_weight=1.0): 27 | super().__init__() 28 | self.first = WeightedLoss(first, first_weight) 29 | self.second = WeightedLoss(second, second_weight) 30 | 31 | def forward(self, *input): 32 | return self.first(*input) + self.second(*input) 33 | -------------------------------------------------------------------------------- /geoseg/losses/lovasz.py: -------------------------------------------------------------------------------- 1 | """ 2 | Lovasz-Softmax and Jaccard hinge loss in PyTorch 3 | Maxim Berman 2018 ESAT-PSI KU Leuven (MIT License) 4 | """ 5 | 6 | from __future__ import print_function, division 7 | 8 | from typing import Optional, Union 9 | 10 | import torch 11 | import torch.nn.functional as F 12 | from torch.autograd import Variable 13 | from torch.nn.modules.loss import _Loss 14 | 15 | try: 16 | from itertools import ifilterfalse 17 | except ImportError: # py3k 18 | from itertools import filterfalse as ifilterfalse 19 | 20 | __all__ = ["BinaryLovaszLoss", "LovaszLoss"] 21 | 22 | 23 | def _lovasz_grad(gt_sorted): 24 | """Compute gradient of the Lovasz extension w.r.t sorted errors 25 | See Alg. 1 in paper 26 | """ 27 | p = len(gt_sorted) 28 | gts = gt_sorted.sum() 29 | intersection = gts - gt_sorted.float().cumsum(0) 30 | union = gts + (1 - gt_sorted).float().cumsum(0) 31 | jaccard = 1.0 - intersection / union 32 | if p > 1: # cover 1-pixel case 33 | jaccard[1:p] = jaccard[1:p] - jaccard[0:-1] 34 | return jaccard 35 | 36 | 37 | def _lovasz_hinge(logits, labels, per_image=True, ignore_index=None): 38 | """ 39 | Binary Lovasz hinge loss 40 | logits: [B, H, W] Variable, logits at each pixel (between -infinity and +infinity) 41 | labels: [B, H, W] Tensor, binary ground truth masks (0 or 1) 42 | per_image: compute the loss per image instead of per batch 43 | ignore: void class id 44 | """ 45 | if per_image: 46 | loss = mean( 47 | _lovasz_hinge_flat(*_flatten_binary_scores(log.unsqueeze(0), lab.unsqueeze(0), ignore_index)) 48 | for log, lab in zip(logits, labels) 49 | ) 50 | else: 51 | loss = _lovasz_hinge_flat(*_flatten_binary_scores(logits, labels, ignore_index)) 52 | return loss 53 | 54 | 55 | def _lovasz_hinge_flat(logits, labels): 56 | """Binary Lovasz hinge loss 57 | Args: 58 | logits: [P] Variable, logits at each prediction (between -iinfinity and +iinfinity) 59 | labels: [P] Tensor, binary ground truth labels (0 or 1) 60 | ignore: label to ignore 61 | """ 62 | if len(labels) == 0: 63 | # only void pixels, the gradients should be 0 64 | return logits.sum() * 0.0 65 | signs = 2.0 * labels.float() - 1.0 66 | errors = 1.0 - logits * Variable(signs) 67 | errors_sorted, perm = torch.sort(errors, dim=0, descending=True) 68 | perm = perm.data 69 | gt_sorted = labels[perm] 70 | grad = _lovasz_grad(gt_sorted) 71 | loss = torch.dot(F.relu(errors_sorted), Variable(grad)) 72 | return loss 73 | 74 | 75 | def _flatten_binary_scores(scores, labels, ignore_index=None): 76 | """Flattens predictions in the batch (binary case) 77 | Remove labels equal to 'ignore' 78 | """ 79 | scores = scores.view(-1) 80 | labels = labels.view(-1) 81 | if ignore_index is None: 82 | return scores, labels 83 | valid = labels != ignore_index 84 | vscores = scores[valid] 85 | vlabels = labels[valid] 86 | return vscores, vlabels 87 | 88 | 89 | # --------------------------- MULTICLASS LOSSES --------------------------- 90 | 91 | 92 | def _lovasz_softmax(probas, labels, classes="present", per_image=False, ignore_index=None): 93 | """Multi-class Lovasz-Softmax loss 94 | Args: 95 | @param probas: [B, C, H, W] Variable, class probabilities at each prediction (between 0 and 1). 96 | Interpreted as binary (sigmoid) output with outputs of size [B, H, W]. 97 | @param labels: [B, H, W] Tensor, ground truth labels (between 0 and C - 1) 98 | @param classes: 'all' for all, 'present' for classes present in labels, or a list of classes to average. 99 | @param per_image: compute the loss per image instead of per batch 100 | @param ignore_index: void class labels 101 | """ 102 | if per_image: 103 | loss = mean( 104 | _lovasz_softmax_flat(*_flatten_probas(prob.unsqueeze(0), lab.unsqueeze(0), ignore_index), classes=classes) 105 | for prob, lab in zip(probas, labels) 106 | ) 107 | else: 108 | loss = _lovasz_softmax_flat(*_flatten_probas(probas, labels, ignore_index), classes=classes) 109 | return loss 110 | 111 | 112 | def _lovasz_softmax_flat(probas, labels, classes="present"): 113 | """Multi-class Lovasz-Softmax loss 114 | Args: 115 | @param probas: [P, C] Variable, class probabilities at each prediction (between 0 and 1) 116 | @param labels: [P] Tensor, ground truth labels (between 0 and C - 1) 117 | @param classes: 'all' for all, 'present' for classes present in labels, or a list of classes to average. 118 | """ 119 | if probas.numel() == 0: 120 | # only void pixels, the gradients should be 0 121 | return probas * 0.0 122 | C = probas.size(1) 123 | losses = [] 124 | class_to_sum = list(range(C)) if classes in ["all", "present"] else classes 125 | for c in class_to_sum: 126 | fg = (labels == c).type_as(probas) # foreground for class c 127 | if classes == "present" and fg.sum() == 0: 128 | continue 129 | if C == 1: 130 | if len(classes) > 1: 131 | raise ValueError("Sigmoid output possible only with 1 class") 132 | class_pred = probas[:, 0] 133 | else: 134 | class_pred = probas[:, c] 135 | errors = (fg - class_pred).abs() 136 | errors_sorted, perm = torch.sort(errors, 0, descending=True) 137 | perm = perm.data 138 | fg_sorted = fg[perm] 139 | losses.append(torch.dot(errors_sorted, _lovasz_grad(fg_sorted))) 140 | return mean(losses) 141 | 142 | 143 | def _flatten_probas(probas, labels, ignore=None): 144 | """Flattens predictions in the batch""" 145 | if probas.dim() == 3: 146 | # assumes output of a sigmoid layer 147 | B, H, W = probas.size() 148 | probas = probas.view(B, 1, H, W) 149 | 150 | C = probas.size(1) 151 | probas = torch.movedim(probas, 1, -1) # [B, C, Di, Dj, ...] -> [B, Di, Dj, ..., C] 152 | probas = probas.contiguous().view(-1, C) # [P, C] 153 | 154 | labels = labels.view(-1) 155 | if ignore is None: 156 | return probas, labels 157 | valid = labels != ignore 158 | vprobas = probas[valid] 159 | vlabels = labels[valid] 160 | return vprobas, vlabels 161 | 162 | 163 | # --------------------------- HELPER FUNCTIONS --------------------------- 164 | def isnan(x): 165 | return x != x 166 | 167 | 168 | def mean(values, ignore_nan=False, empty=0): 169 | """Nanmean compatible with generators.""" 170 | values = iter(values) 171 | if ignore_nan: 172 | values = ifilterfalse(isnan, values) 173 | try: 174 | n = 1 175 | acc = next(values) 176 | except StopIteration: 177 | if empty == "raise": 178 | raise ValueError("Empty mean") 179 | return empty 180 | for n, v in enumerate(values, 2): 181 | acc += v 182 | if n == 1: 183 | return acc 184 | return acc / n 185 | 186 | 187 | class BinaryLovaszLoss(_Loss): 188 | def __init__(self, per_image: bool = False, ignore_index: Optional[Union[int, float]] = None): 189 | super().__init__() 190 | self.ignore_index = ignore_index 191 | self.per_image = per_image 192 | 193 | def forward(self, logits, target): 194 | return _lovasz_hinge(logits, target, per_image=self.per_image, ignore_index=self.ignore_index) 195 | 196 | 197 | class LovaszLoss(_Loss): 198 | def __init__(self, per_image=False, ignore=None): 199 | super().__init__() 200 | self.ignore = ignore 201 | self.per_image = per_image 202 | 203 | def forward(self, logits, target): 204 | return _lovasz_softmax(logits, target, per_image=self.per_image, ignore_index=self.ignore) 205 | -------------------------------------------------------------------------------- /geoseg/losses/soft_bce.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | import torch.nn.functional as F 4 | from torch import nn, Tensor 5 | 6 | __all__ = ["SoftBCEWithLogitsLoss"] 7 | 8 | 9 | class SoftBCEWithLogitsLoss(nn.Module): 10 | """ 11 | Drop-in replacement for nn.BCEWithLogitsLoss with few additions: 12 | - Support of ignore_index value 13 | - Support of label smoothing 14 | """ 15 | 16 | __constants__ = ["weight", "pos_weight", "reduction", "ignore_index", "smooth_factor"] 17 | 18 | def __init__( 19 | self, weight=None, ignore_index: Optional[int] = -100, reduction="mean", smooth_factor=None, pos_weight=None 20 | ): 21 | super().__init__() 22 | self.ignore_index = ignore_index 23 | self.reduction = reduction 24 | self.smooth_factor = smooth_factor 25 | self.register_buffer("weight", weight) 26 | self.register_buffer("pos_weight", pos_weight) 27 | 28 | def forward(self, input: Tensor, target: Tensor) -> Tensor: 29 | if self.smooth_factor is not None: 30 | soft_targets = ((1 - target) * self.smooth_factor + target * (1 - self.smooth_factor)).type_as(input) 31 | else: 32 | soft_targets = target.type_as(input) 33 | 34 | loss = F.binary_cross_entropy_with_logits( 35 | input, soft_targets, self.weight, pos_weight=self.pos_weight, reduction="none" 36 | ) 37 | 38 | if self.ignore_index is not None: 39 | not_ignored_mask: Tensor = target != self.ignore_index 40 | loss *= not_ignored_mask.type_as(loss) 41 | 42 | if self.reduction == "mean": 43 | loss = loss.mean() 44 | 45 | if self.reduction == "sum": 46 | loss = loss.sum() 47 | 48 | return loss 49 | -------------------------------------------------------------------------------- /geoseg/losses/soft_ce.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | from torch import nn, Tensor 3 | import torch.nn.functional as F 4 | from .functional import label_smoothed_nll_loss 5 | 6 | __all__ = ["SoftCrossEntropyLoss"] 7 | 8 | 9 | class SoftCrossEntropyLoss(nn.Module): 10 | """ 11 | Drop-in replacement for nn.CrossEntropyLoss with few additions: 12 | - Support of label smoothing 13 | """ 14 | 15 | __constants__ = ["reduction", "ignore_index", "smooth_factor"] 16 | 17 | def __init__(self, reduction: str = "mean", smooth_factor: float = 0.0, ignore_index: Optional[int] = -100, dim=1): 18 | super().__init__() 19 | self.smooth_factor = smooth_factor 20 | self.ignore_index = ignore_index 21 | self.reduction = reduction 22 | self.dim = dim 23 | 24 | def forward(self, input: Tensor, target: Tensor) -> Tensor: 25 | log_prob = F.log_softmax(input, dim=self.dim) 26 | return label_smoothed_nll_loss( 27 | log_prob, 28 | target, 29 | epsilon=self.smooth_factor, 30 | ignore_index=self.ignore_index, 31 | reduction=self.reduction, 32 | dim=self.dim, 33 | ) 34 | -------------------------------------------------------------------------------- /geoseg/losses/soft_f1.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn, Tensor 3 | from typing import Optional 4 | 5 | __all__ = ["soft_micro_f1", "BinarySoftF1Loss", "SoftF1Loss"] 6 | 7 | 8 | def soft_micro_f1(preds: Tensor, targets: Tensor, eps=1e-6) -> Tensor: 9 | """Compute the macro soft F1-score as a cost. 10 | Average (1 - soft-F1) across all labels. 11 | Use probability values instead of binary predictions. 12 | 13 | Args: 14 | targets (Tensor): targets array of shape (Num Samples, Num Classes) 15 | preds (Tensor): probability matrix of shape (Num Samples, Num Classes) 16 | 17 | Returns: 18 | cost (scalar Tensor): value of the cost function for the batch 19 | 20 | References: 21 | https://towardsdatascience.com/the-unknown-benefits-of-using-a-soft-f1-loss-in-classification-systems-753902c0105d 22 | """ 23 | tp = torch.sum(preds * targets, dim=0) 24 | fp = torch.sum(preds * (1 - targets), dim=0) 25 | fn = torch.sum((1 - preds) * targets, dim=0) 26 | soft_f1 = 2 * tp / (2 * tp + fn + fp + eps) 27 | loss = 1 - soft_f1 # reduce 1 - soft-f1 in order to increase soft-f1 28 | return loss.mean() 29 | 30 | 31 | # TODO: Test 32 | # def macro_double_soft_f1(y, y_hat): 33 | # """Compute the macro soft F1-score as a cost (average 1 - soft-F1 across all labels). 34 | # Use probability values instead of binary predictions. 35 | # This version uses the computation of soft-F1 for both positive and negative class for each label. 36 | # 37 | # Args: 38 | # y (int32 Tensor): targets array of shape (BATCH_SIZE, N_LABELS) 39 | # y_hat (float32 Tensor): probability matrix from forward propagation of shape (BATCH_SIZE, N_LABELS) 40 | # 41 | # Returns: 42 | # cost (scalar Tensor): value of the cost function for the batch 43 | # """ 44 | # tp = tf.reduce_sum(y_hat * y, axis=0) 45 | # fp = tf.reduce_sum(y_hat * (1 - y), axis=0) 46 | # fn = tf.reduce_sum((1 - y_hat) * y, axis=0) 47 | # tn = tf.reduce_sum((1 - y_hat) * (1 - y), axis=0) 48 | # soft_f1_class1 = 2 * tp / (2 * tp + fn + fp + 1e-16) 49 | # soft_f1_class0 = 2 * tn / (2 * tn + fn + fp + 1e-16) 50 | # cost_class1 = 1 - soft_f1_class1 # reduce 1 - soft-f1_class1 in order to increase soft-f1 on class 1 51 | # cost_class0 = 1 - soft_f1_class0 # reduce 1 - soft-f1_class0 in order to increase soft-f1 on class 0 52 | # cost = 0.5 * (cost_class1 + cost_class0) # take into account both class 1 and class 0 53 | # macro_cost = tf.reduce_mean(cost) # average on all labels 54 | # return macro_cost 55 | 56 | 57 | class BinarySoftF1Loss(nn.Module): 58 | def __init__(self, ignore_index: Optional[int] = None, eps=1e-6): 59 | super().__init__() 60 | self.ignore_index = ignore_index 61 | self.eps = eps 62 | 63 | def forward(self, preds: Tensor, targets: Tensor) -> Tensor: 64 | targets = targets.view(-1) 65 | preds = preds.view(-1) 66 | 67 | if self.ignore_index is not None: 68 | # Filter predictions with ignore label from loss computation 69 | not_ignored = targets != self.ignore_index 70 | preds = preds[not_ignored] 71 | targets = targets[not_ignored] 72 | 73 | if targets.numel() == 0: 74 | return torch.tensor(0, dtype=preds.dtype, device=preds.device) 75 | 76 | preds = preds.sigmoid().clamp(self.eps, 1 - self.eps) 77 | return soft_micro_f1(preds.view(-1, 1), targets.view(-1, 1)) 78 | 79 | 80 | class SoftF1Loss(nn.Module): 81 | def __init__(self, ignore_index: Optional[int] = None, eps=1e-6): 82 | super().__init__() 83 | self.ignore_index = ignore_index 84 | self.eps = eps 85 | 86 | def forward(self, preds: Tensor, targets: Tensor) -> Tensor: 87 | preds = preds.softmax(dim=1).clamp(self.eps, 1 - self.eps) 88 | targets = torch.nn.functional.one_hot(targets, preds.size(1)) 89 | 90 | if self.ignore_index is not None: 91 | # Filter predictions with ignore label from loss computation 92 | not_ignored = targets != self.ignore_index 93 | preds = preds[not_ignored] 94 | targets = targets[not_ignored] 95 | 96 | if targets.numel() == 0: 97 | return torch.tensor(0, dtype=preds.dtype, device=preds.device) 98 | 99 | return soft_micro_f1(preds, targets) 100 | -------------------------------------------------------------------------------- /geoseg/losses/useful_loss.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import torch 3 | import torch.nn.functional as F 4 | import torch.nn as nn 5 | from torch import Tensor 6 | from .soft_ce import SoftCrossEntropyLoss 7 | from .joint_loss import JointLoss 8 | from .dice import DiceLoss 9 | 10 | 11 | class EdgeLoss(nn.Module): 12 | def __init__(self, ignore_index=255, edge_factor=10.0): 13 | super(EdgeLoss, self).__init__() 14 | self.main_loss = JointLoss(SoftCrossEntropyLoss(smooth_factor=0.05, ignore_index=ignore_index), 15 | DiceLoss(smooth=0.05, ignore_index=ignore_index), 1.0, 1.0) 16 | self.edge_factor = edge_factor 17 | 18 | def get_boundary(self, x): 19 | laplacian_kernel_target = torch.tensor( 20 | [-1, -1, -1, -1, 8, -1, -1, -1, -1], 21 | dtype=torch.float32).reshape(1, 1, 3, 3).requires_grad_(False).cuda(device=x.device) 22 | x = x.unsqueeze(1).float() 23 | x = F.conv2d(x, laplacian_kernel_target, padding=1) 24 | x = x.clamp(min=0, max=1.0) 25 | x[x >= 0.1] = 1 26 | x[x < 0.1] = 0 27 | 28 | return x 29 | 30 | def compute_edge_loss(self, logits, targets): 31 | bs = logits.size()[0] 32 | boundary_targets = self.get_boundary(targets) 33 | boundary_targets = boundary_targets.view(bs, 1, -1) 34 | # print(boundary_targets.shape) 35 | logits = F.softmax(logits, dim=1).argmax(dim=1).squeeze(dim=1) 36 | boundary_pre = self.get_boundary(logits) 37 | boundary_pre = boundary_pre / (boundary_pre + 0.01) 38 | # print(boundary_pre) 39 | boundary_pre = boundary_pre.view(bs, 1, -1) 40 | # print(boundary_pre) 41 | edge_loss = F.binary_cross_entropy_with_logits(boundary_pre, boundary_targets) 42 | 43 | return edge_loss 44 | 45 | def forward(self, logits, targets): 46 | loss = self.main_loss(logits, targets) + self.compute_edge_loss(logits, targets) * self.edge_factor 47 | return loss 48 | 49 | 50 | class OHEM_CELoss(nn.Module): 51 | 52 | def __init__(self, thresh=0.7, ignore_index=255): 53 | super(OHEM_CELoss, self).__init__() 54 | self.thresh = thresh 55 | self.ignore_index = ignore_index 56 | self.criteria = nn.CrossEntropyLoss(ignore_index=ignore_index, reduction='none') 57 | 58 | def forward(self, logits, labels): 59 | thresh = -torch.log(torch.tensor(self.thresh, requires_grad=False, dtype=torch.float)).cuda(device=logits.device) 60 | n_min = labels[labels != self.ignore_index].numel() // 16 61 | loss = self.criteria(logits, labels).view(-1) 62 | loss_hard = loss[loss > thresh] 63 | if loss_hard.numel() < n_min: 64 | loss_hard, _ = loss.topk(n_min) 65 | return torch.mean(loss_hard) 66 | 67 | 68 | class ProbOhemCrossEntropy2d(nn.Module): 69 | def __init__(self, ignore_label=255, reduction='mean', thresh=0.7, min_kept=256, 70 | down_ratio=1, use_weight=False): 71 | super(ProbOhemCrossEntropy2d, self).__init__() 72 | self.ignore_label = ignore_label 73 | self.thresh = float(thresh) 74 | self.min_kept = int(min_kept) 75 | self.down_ratio = down_ratio 76 | if use_weight: 77 | weight = torch.FloatTensor( 78 | [0.8373, 0.918, 0.866, 1.0345, 1.0166, 0.9969, 0.9754, 1.0489, 79 | 0.8786, 1.0023, 0.9539, 0.9843, 1.1116, 0.9037, 1.0865, 1.0955, 80 | 1.0865, 1.1529, 1.0507]) 81 | self.criterion = torch.nn.CrossEntropyLoss(reduction=reduction, 82 | weight=weight, 83 | ignore_index=ignore_label) 84 | else: 85 | self.criterion = torch.nn.CrossEntropyLoss(reduction=reduction, 86 | ignore_index=ignore_label) 87 | 88 | def forward(self, pred, target): 89 | b, c, h, w = pred.size() 90 | target = target.view(-1) 91 | valid_mask = target.ne(self.ignore_label) 92 | target = target * valid_mask.long() 93 | num_valid = valid_mask.sum() 94 | 95 | prob = F.softmax(pred, dim=1) 96 | prob = (prob.transpose(0, 1)).reshape(c, -1) 97 | 98 | if self.min_kept > num_valid: 99 | print('Labels: {}'.format(num_valid)) 100 | elif num_valid > 0: 101 | prob = prob.masked_fill_(~valid_mask, 1) 102 | mask_prob = prob[ 103 | target, torch.arange(len(target), dtype=torch.long)] 104 | threshold = self.thresh 105 | if self.min_kept > 0: 106 | index = mask_prob.argsort() 107 | threshold_index = index[min(len(index), self.min_kept) - 1] 108 | if mask_prob[threshold_index] > self.thresh: 109 | threshold = mask_prob[threshold_index] 110 | kept_mask = mask_prob.le(threshold) # 概率小于阈值的挖出来 111 | target = target * kept_mask.long() 112 | valid_mask = valid_mask * kept_mask 113 | # logger.info('Valid Mask: {}'.format(valid_mask.sum())) 114 | 115 | target = target.masked_fill_(~valid_mask, self.ignore_label) 116 | target = target.view(b, h, w) 117 | 118 | return self.criterion(pred, target) 119 | 120 | 121 | if __name__ == '__main__': 122 | targets = torch.randint(low=0, high=2, size=(2, 16, 16)) 123 | logits = torch.randn((2, 2, 16, 16)) 124 | # print(targets) 125 | model = EdgeLoss() 126 | loss = model.compute_edge_loss(logits, targets) 127 | 128 | print(loss) -------------------------------------------------------------------------------- /geoseg/losses/wing_loss.py: -------------------------------------------------------------------------------- 1 | from torch.nn.modules.loss import _Loss 2 | 3 | from . import functional as F 4 | 5 | __all__ = ["WingLoss"] 6 | 7 | 8 | class WingLoss(_Loss): 9 | def __init__(self, width=5, curvature=0.5, reduction="mean"): 10 | super(WingLoss, self).__init__(reduction=reduction) 11 | self.width = width 12 | self.curvature = curvature 13 | 14 | def forward(self, prediction, target): 15 | return F.wing_loss(prediction, target, self.width, self.curvature, self.reduction) 16 | -------------------------------------------------------------------------------- /geoseg/models/BuildFormer.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | import numpy as np 5 | from einops import rearrange 6 | from timm.models.layers import DropPath, to_2tuple, trunc_normal_ 7 | import timm 8 | 9 | 10 | class MaxPoolLayer(nn.Sequential): 11 | def __init__(self, kernel_size=3, dilation=1, stride=1): 12 | super(MaxPoolLayer, self).__init__( 13 | nn.MaxPool2d(kernel_size=kernel_size, dilation=dilation, stride=stride, 14 | padding=((stride - 1) + dilation * (kernel_size - 1)) // 2) 15 | ) 16 | 17 | 18 | class AvgPoolLayer(nn.Sequential): 19 | def __init__(self, kernel_size=3, stride=1): 20 | super(AvgPoolLayer, self).__init__( 21 | nn.AvgPool2d(kernel_size=kernel_size, stride=stride, 22 | padding=(kernel_size-1)//2) 23 | ) 24 | 25 | 26 | class ConvBNAct(nn.Sequential): 27 | def __init__(self, in_channels, out_channels, kernel_size=3, dilation=1, stride=1, 28 | norm_layer=nn.BatchNorm2d, act_layer=nn.ReLU6, bias=False, inplace=False): 29 | super(ConvBNAct, self).__init__( 30 | nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, bias=bias, 31 | dilation=dilation, stride=stride, padding=((stride - 1) + dilation * (kernel_size - 1)) // 2), 32 | norm_layer(out_channels), 33 | act_layer(inplace=inplace) 34 | ) 35 | 36 | 37 | class ConvGeluBN(nn.Sequential): 38 | def __init__(self, in_channels, out_channels, kernel_size=3, dilation=1, stride=1, bias=False, inplace=False): 39 | super(ConvGeluBN, self).__init__( 40 | nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, bias=bias, 41 | dilation=dilation, stride=stride, padding=((stride - 1) + dilation * (kernel_size - 1)) // 2), 42 | nn.GELU(), 43 | nn.BatchNorm2d(out_channels) 44 | ) 45 | 46 | 47 | class ConvBN(nn.Sequential): 48 | def __init__(self, in_channels, out_channels, kernel_size=3, dilation=1, stride=1, norm_layer=nn.BatchNorm2d, bias=False): 49 | super(ConvBN, self).__init__( 50 | nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, bias=bias, 51 | dilation=dilation, stride=stride, padding=((stride - 1) + dilation * (kernel_size - 1)) // 2), 52 | norm_layer(out_channels) 53 | ) 54 | 55 | 56 | class Conv(nn.Sequential): 57 | def __init__(self, in_channels, out_channels, kernel_size=3, dilation=1, stride=1, bias=False): 58 | super(Conv, self).__init__( 59 | nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, bias=bias, 60 | dilation=dilation, stride=stride, padding=((stride - 1) + dilation * (kernel_size - 1)) // 2) 61 | ) 62 | 63 | 64 | class SeparableConvBNAct(nn.Sequential): 65 | def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, dilation=1, 66 | norm_layer=nn.BatchNorm2d, act_layer=nn.ReLU6, inplace=False): 67 | super(SeparableConvBNAct, self).__init__( 68 | nn.Conv2d(in_channels, in_channels, kernel_size, stride=stride, dilation=dilation, 69 | padding=((stride - 1) + dilation * (kernel_size - 1)) // 2, 70 | groups=in_channels, bias=False), 71 | nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False), 72 | norm_layer(out_channels), 73 | act_layer(inplace=inplace) 74 | ) 75 | 76 | 77 | class SeparableConvBN(nn.Sequential): 78 | def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, dilation=1, 79 | norm_layer=nn.BatchNorm2d): 80 | super(SeparableConvBN, self).__init__( 81 | nn.Conv2d(in_channels, in_channels, kernel_size, stride=stride, dilation=dilation, 82 | padding=((stride - 1) + dilation * (kernel_size - 1)) // 2, 83 | groups=in_channels, bias=False), 84 | nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False), 85 | norm_layer(out_channels) 86 | ) 87 | 88 | 89 | class SeparableConv(nn.Sequential): 90 | def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, dilation=1): 91 | super(SeparableConv, self).__init__( 92 | nn.Conv2d(in_channels, in_channels, kernel_size, stride=stride, dilation=dilation, 93 | padding=((stride - 1) + dilation * (kernel_size - 1)) // 2, 94 | groups=in_channels, bias=False), 95 | nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False) 96 | ) 97 | 98 | 99 | class Mlp(nn.Module): 100 | def __init__( 101 | self, in_features, hidden_features=None, out_features=None, act_layer=nn.ReLU6, norm_layer=nn.BatchNorm2d, drop=0.): 102 | super().__init__() 103 | out_features = out_features or in_features 104 | hidden_features = hidden_features or in_features 105 | self.fc1 = ConvBNAct(in_features, hidden_features, kernel_size=1) 106 | self.fc2 = nn.Sequential(nn.Conv2d(hidden_features, hidden_features, kernel_size=3, padding=1, groups=hidden_features), 107 | norm_layer(hidden_features), 108 | act_layer()) 109 | self.fc3 = ConvBN(hidden_features, out_features, kernel_size=1) 110 | self.drop = nn.Dropout(drop) 111 | 112 | def forward(self, x): 113 | x = self.fc1(x) 114 | x = self.fc2(x) 115 | x = self.fc3(x) 116 | x = self.drop(x) 117 | 118 | return x 119 | 120 | 121 | class RPE(nn.Module): 122 | def __init__(self, dim): 123 | super().__init__() 124 | self.rpe_conv = nn.Conv2d(dim, dim, kernel_size=3, padding=1, groups=dim) 125 | self.rpe_norm = nn.BatchNorm2d(dim) 126 | 127 | def forward(self, x): 128 | return x + self.rpe_norm(self.rpe_conv(x)) 129 | 130 | 131 | class Stem(nn.Module): 132 | def __init__(self, img_dim=3, out_dim=64, rpe=True): 133 | super(Stem, self).__init__() 134 | self.conv1 = ConvBNAct(img_dim, out_dim//2, kernel_size=3, stride=2, inplace=True) 135 | self.conv2 = ConvBNAct(out_dim//2, out_dim, kernel_size=3, stride=2, inplace=True) 136 | self.rpe = rpe 137 | if self.rpe: 138 | self.proj_rpe = RPE(out_dim) 139 | 140 | def forward(self, x): 141 | x = self.conv1(x) 142 | x = self.conv2(x) 143 | 144 | if self.rpe: 145 | x = self.proj_rpe(x) 146 | return x 147 | 148 | 149 | class LWMSA(nn.Module): 150 | def __init__(self, 151 | dim=16, 152 | num_heads=8, 153 | window_size=16, 154 | qkv_bias=False 155 | ): 156 | super().__init__() 157 | self.num_heads = num_heads 158 | self.eps = 1e-6 159 | self.ws = window_size 160 | 161 | self.qkv = Conv(dim, dim*3, kernel_size=1, bias=qkv_bias) 162 | self.proj = ConvBN(dim, dim, kernel_size=1) 163 | 164 | def pad(self, x, ps): 165 | _, _, H, W = x.size() 166 | if W % ps != 0: 167 | x = F.pad(x, (0, ps - W % ps)) 168 | if H % ps != 0: 169 | x = F.pad(x, (0, 0, 0, ps - H % ps)) 170 | return x 171 | 172 | def l2_norm(self, x): 173 | return torch.einsum("bhcn, bhn->bhcn", x, 1 / torch.norm(x, p=2, dim=-2)) 174 | 175 | def forward(self, x): 176 | _, _, H, W = x.shape 177 | x = self.pad(x, self.ws) 178 | 179 | B, C, Hp, Wp = x.shape 180 | hh, ww = Hp//self.ws, Wp//self.ws 181 | # print(x.shape) 182 | qkv = self.qkv(x) 183 | 184 | q, k, v = rearrange(qkv, 'b (qkv h d) (hh ws1) (ww ws2) -> qkv (b hh ww) h d (ws1 ws2)', 185 | b=B, h=self.num_heads, d=C//self.num_heads, qkv=3, ws1=self.ws, ws2=self.ws) 186 | 187 | q = self.l2_norm(q).permute(0, 1, 3, 2) 188 | k = self.l2_norm(k) 189 | # print(q.shape, v.shape, k.shape) 190 | 191 | tailor_sum = 1 / (self.ws * self.ws + torch.einsum("bhnc, bhc->bhn", q, torch.sum(k, dim=-1) + self.eps)) 192 | # print(tailor_sum.shape) 193 | attn = torch.einsum('bhmn, bhcn->bhmc', k, v) 194 | # print(q.shape, attn.shape) 195 | attn = torch.einsum("bhnm, bhmc->bhcn", q, attn) 196 | # print(attn.shape) 197 | v = torch.einsum("bhcn->bhc", v).unsqueeze(-1) 198 | v = v.expand(B*hh*ww, self.num_heads, C//self.num_heads, self.ws * self.ws) 199 | attn = attn + v 200 | attn = torch.einsum("bhcn, bhn->bhcn", attn, tailor_sum) 201 | attn = rearrange(attn, '(b hh ww) h d (ws1 ws2) -> b (h d) (hh ws1) (ww ws2)', 202 | b=B, h=self.num_heads, d=C // self.num_heads, ws1=self.ws, ws2=self.ws, 203 | hh=Hp // self.ws, ww=Wp // self.ws) 204 | attn = attn[:, :, :H, :W] 205 | 206 | return attn 207 | 208 | 209 | class Block(nn.Module): 210 | def __init__(self, dim=16, num_heads=8, mlp_ratio=4., qkv_bias=False, drop=0., 211 | drop_path=0., act_layer=nn.ReLU6, norm_layer=nn.BatchNorm2d, window_size=16): 212 | super().__init__() 213 | self.norm1 = norm_layer(dim) 214 | self.ws = window_size 215 | self.attn = LWMSA(dim, num_heads=num_heads, qkv_bias=qkv_bias, 216 | window_size=window_size) 217 | 218 | self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() 219 | mlp_hidden_dim = int(dim * mlp_ratio) 220 | self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, out_features=dim, act_layer=act_layer, drop=drop) 221 | 222 | def forward(self, x): 223 | x = x + self.drop_path(self.attn(self.norm1(x))) 224 | x = x + self.drop_path(self.mlp(x)) 225 | return x 226 | 227 | 228 | class PatchMerging(nn.Module): 229 | def __init__(self, dim, out_dim, norm_layer=nn.BatchNorm2d, rpe=True): 230 | super().__init__() 231 | self.dim = dim 232 | self.out_dim = out_dim 233 | self.norm = norm_layer(dim) 234 | self.reduction = nn.Conv2d(dim, out_dim, 2, 2, 0, bias=False) 235 | self.rpe = rpe 236 | if self.rpe: 237 | self.proj_rpe = RPE(out_dim) 238 | 239 | def forward(self, x): 240 | x = self.norm(x) 241 | x = self.reduction(x) 242 | if self.rpe: 243 | x = self.proj_rpe(x) 244 | return x 245 | 246 | 247 | class PatchEmbed(nn.Module): 248 | """ Image to Patch Embedding 249 | 250 | Args: 251 | patch_size (int): Patch token size. Default: 4. 252 | in_chans (int): Number of input image channels. Default: 3. 253 | embed_dim (int): Number of linear projection output channels. Default: 96. 254 | norm_layer (nn.Module, optional): Normalization layer. Default: None 255 | """ 256 | 257 | def __init__(self, img_size=(256, 256), img_dim=3, embed_dim=96, out_dim=96, patch_size=4, ape=False): 258 | super().__init__() 259 | self.embed_dim = embed_dim 260 | 261 | self.ps = patch_size 262 | self.proj_ps = nn.Conv2d(img_dim, embed_dim, kernel_size=self.ps, stride=self.ps) 263 | self.proj = nn.Sequential(ConvBN(embed_dim, embed_dim, kernel_size=3), 264 | nn.GELU(), 265 | ConvBN(embed_dim, out_dim, kernel_size=3), 266 | nn.GELU()) 267 | 268 | # absolute position embedding 269 | self.ape = ape 270 | if self.ape: 271 | h, w = img_size[0] // patch_size, img_size[1] // patch_size 272 | self.absolute_pos_embed = nn.Parameter(torch.zeros(1, embed_dim, h, w)) 273 | trunc_normal_(self.absolute_pos_embed, std=.02) 274 | 275 | def pad(self, x, ps): 276 | _, _, H, W = x.size() 277 | if W % ps != 0: 278 | x = F.pad(x, (0, ps - W % ps)) 279 | if H % ps != 0: 280 | x = F.pad(x, (0, 0, 0, ps - H % ps)) 281 | return x 282 | 283 | def forward(self, x): 284 | x = self.pad(x, self.ps) 285 | _, _, Hp, Wp = x.size() 286 | x = self.proj_ps(x) 287 | x = self.proj(x) 288 | 289 | if self.ape: 290 | absolute_pos_embed = F.interpolate(self.absolute_pos_embed, 291 | size=(Hp // self.ps, Wp // self.ps), 292 | mode='bicubic', align_corners=False) 293 | x = x + absolute_pos_embed 294 | 295 | return x 296 | 297 | 298 | class StageModule(nn.Module): 299 | def __init__(self, num_layers=2, in_dim=96, out_dim=96, num_heads=8, mlp_ratio=4., qkv_bias=False, use_pm=False, 300 | drop=0., attn_drop=0., drop_path=0., act_layer=nn.ReLU6, norm_layer=nn.BatchNorm2d, window_size=-1, shuffle=False): 301 | super().__init__() 302 | self.use_pm = use_pm 303 | if self.use_pm: 304 | self.patch_partition = PatchMerging(in_dim, out_dim) 305 | 306 | self.layers = nn.ModuleList([]) 307 | for idx in range(num_layers): 308 | self.layers.append(Block(dim=out_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, 309 | qkv_bias=qkv_bias, drop=drop, 310 | drop_path=drop_path, act_layer=act_layer, window_size=window_size, 311 | norm_layer=norm_layer)) 312 | 313 | def forward(self, x): 314 | if self.use_pm: 315 | x = self.patch_partition(x) 316 | 317 | for block in self.layers: 318 | x = block(x) 319 | 320 | return x 321 | 322 | 323 | class BuildFormer(nn.Module): 324 | def __init__(self, img_dim=3, mlp_ratio=4., window_sizes=[16, 16, 16, 16], 325 | layers=[2, 2, 2, 2], num_heads=[4, 8, 16, 32], dims=[64, 128, 256, 512], 326 | qkv_bias=False, drop_rate=0., attn_drop_rate=0., drop_path_rate=0.3): 327 | super().__init__() 328 | 329 | self.stem = Stem(img_dim=img_dim, out_dim=dims[0], rpe=True) 330 | # self.stem = PatchEmbed(img_size=img_size, img_dim=img_dim, embed_dim=dims[0], out_dim=dims[0], ape=True) 331 | self.encoder_channels = dims 332 | 333 | dpr = [x.item() for x in torch.linspace(0, drop_path_rate, 4)] # stochastic depth decay rule 334 | self.stage1 = StageModule(layers[0], dims[0], dims[0], num_heads[0], mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, 335 | use_pm=False, drop=drop_rate, attn_drop=attn_drop_rate, 336 | drop_path=dpr[0], window_size=window_sizes[0]) 337 | self.stage2 = StageModule(layers[1], dims[0], dims[1], num_heads[1], mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, 338 | use_pm=True, drop=drop_rate, attn_drop=attn_drop_rate, 339 | drop_path=dpr[1], window_size=window_sizes[1]) 340 | self.stage3 = StageModule(layers[2], dims[1], dims[2], num_heads[2], mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, 341 | use_pm=True, drop=drop_rate, attn_drop=attn_drop_rate, 342 | drop_path=dpr[2], window_size=window_sizes[2]) 343 | self.stage4 = StageModule(layers[3], dims[2], dims[3], num_heads[3], mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, 344 | use_pm=True, drop=drop_rate, attn_drop=attn_drop_rate, 345 | drop_path=dpr[3], window_size=window_sizes[3]) 346 | 347 | def forward(self, x): 348 | features = [] 349 | x = self.stem(x) 350 | x = self.stage1(x) 351 | features.append(x) 352 | x = self.stage2(x) 353 | features.append(x) 354 | x = self.stage3(x) 355 | features.append(x) 356 | x = self.stage4(x) 357 | features.append(x) 358 | 359 | return features 360 | 361 | 362 | class DetailPath(nn.Module): 363 | def __init__(self, embed_dim=64): 364 | super().__init__() 365 | dim1 = embed_dim // 4 366 | dim2 = embed_dim // 2 367 | self.dp1 = nn.Sequential(ConvBNAct(3, dim1, stride=2, inplace=False), 368 | ConvBNAct(dim1, dim1, stride=1, inplace=False)) 369 | self.dp2 = nn.Sequential(ConvBNAct(dim1, dim2, stride=2, inplace=False), 370 | ConvBNAct(dim2, dim2, stride=1, inplace=False)) 371 | self.dp3 = nn.Sequential(ConvBNAct(dim2, embed_dim, stride=1, inplace=False), 372 | ConvBNAct(embed_dim, embed_dim, stride=1, inplace=False)) 373 | 374 | def forward(self, x): 375 | feats = self.dp1(x) 376 | feats = self.dp2(feats) 377 | feats = self.dp3(feats) 378 | 379 | return feats 380 | 381 | 382 | class FPN(nn.Module): 383 | def __init__(self, encoder_channels=(64, 128, 256, 512), decoder_channels=256): 384 | super().__init__() 385 | self.pre_conv0 = Conv(encoder_channels[0], decoder_channels, kernel_size=1) 386 | self.pre_conv1 = Conv(encoder_channels[1], decoder_channels, kernel_size=1) 387 | self.pre_conv2 = Conv(encoder_channels[2], decoder_channels, kernel_size=1) 388 | self.pre_conv3 = Conv(encoder_channels[3], decoder_channels, kernel_size=1) 389 | 390 | self.post_conv3 = nn.Sequential(ConvBNAct(decoder_channels, decoder_channels), 391 | nn.UpsamplingBilinear2d(scale_factor=2), 392 | ConvBNAct(decoder_channels, decoder_channels), 393 | nn.UpsamplingBilinear2d(scale_factor=2), 394 | ConvBNAct(decoder_channels, decoder_channels)) 395 | 396 | self.post_conv2 = nn.Sequential(ConvBNAct(decoder_channels, decoder_channels), 397 | nn.UpsamplingBilinear2d(scale_factor=2), 398 | ConvBNAct(decoder_channels, decoder_channels)) 399 | 400 | self.post_conv1 = ConvBNAct(decoder_channels, decoder_channels) 401 | self.post_conv0 = ConvBNAct(decoder_channels, decoder_channels) 402 | 403 | def upsample_add(self, up, x): 404 | up = F.interpolate(up, x.size()[-2:], mode='nearest') 405 | up = up + x 406 | return up 407 | 408 | def forward(self, x0, x1, x2, x3): 409 | x3 = self.pre_conv3(x3) 410 | x2 = self.pre_conv2(x2) 411 | x1 = self.pre_conv1(x1) 412 | x0 = self.pre_conv0(x0) 413 | 414 | x2 = self.upsample_add(x3, x2) 415 | x1 = self.upsample_add(x2, x1) 416 | x0 = self.upsample_add(x1, x0) 417 | 418 | x3 = self.post_conv3(x3) 419 | x3 = F.interpolate(x3, x0.size()[-2:], mode='bilinear', align_corners=False) 420 | 421 | x2 = self.post_conv2(x2) 422 | x2 = F.interpolate(x2, x0.size()[-2:], mode='bilinear', align_corners=False) 423 | 424 | x1 = self.post_conv1(x1) 425 | x1 = F.interpolate(x1, x0.size()[-2:], mode='bilinear', align_corners=False) 426 | 427 | x0 = self.post_conv0(x0) 428 | 429 | x0 = x3 + x2 + x1 + x0 430 | 431 | return x0 432 | 433 | 434 | class BuildFormerSegDP(nn.Module): 435 | def __init__(self, 436 | decoder_channels=384, 437 | dims=[96, 192, 384, 768], 438 | window_sizes=[16, 16, 16, 16], 439 | num_classes=2): 440 | super().__init__() 441 | self.backbone = BuildFormer(layers=[2, 2, 6, 2], num_heads=[4, 8, 16, 32], 442 | dims=dims, window_sizes=window_sizes) 443 | 444 | encoder_channels = self.backbone.encoder_channels 445 | self.dp = DetailPath(embed_dim=decoder_channels) 446 | 447 | self.fpn = FPN(encoder_channels, decoder_channels) 448 | self.head = nn.Sequential(ConvBNAct(decoder_channels, encoder_channels[0]), 449 | nn.Dropout(0.1), 450 | nn.UpsamplingBilinear2d(scale_factor=2), 451 | Conv(encoder_channels[0], num_classes, kernel_size=1)) 452 | 453 | self.apply(self._init_weights) 454 | 455 | def _init_weights(self, m): 456 | if isinstance(m, nn.Conv2d): 457 | trunc_normal_(m.weight, std=0.02) 458 | elif isinstance(m, nn.Linear): 459 | trunc_normal_(m.weight, std=0.02) 460 | if m.bias is not None: 461 | nn.init.constant_(m.bias, 0) 462 | elif isinstance(m, (nn.LayerNorm, nn.BatchNorm2d)): 463 | nn.init.constant_(m.weight, 1.0) 464 | nn.init.constant_(m.bias, 0) 465 | 466 | def forward(self, x): 467 | sz = x.size()[-2:] 468 | dp = self.dp(x) 469 | x, x2, x3, x4 = self.backbone(x) 470 | x = self.fpn(x, x2, x3, x4) 471 | x = x + dp 472 | x = self.head(x) 473 | x = F.interpolate(x, sz, mode='bilinear', align_corners=False) 474 | return x -------------------------------------------------------------------------------- /geoseg/models/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WangLibo1995/BuildFormer/c20f15805694fa568b8ac531ba51bc5e9c5a29c6/geoseg/models/__init__.py -------------------------------------------------------------------------------- /inria_patch_split.py: -------------------------------------------------------------------------------- 1 | import glob 2 | import os 3 | import numpy as np 4 | import cv2 5 | import multiprocessing.pool as mpp 6 | import multiprocessing as mp 7 | import time 8 | import argparse 9 | import torch 10 | import albumentations as albu 11 | 12 | import random 13 | 14 | SEED = 42 15 | 16 | 17 | def seed_everything(seed): 18 | random.seed(seed) 19 | os.environ['PYTHONHASHSEED'] = str(seed) 20 | np.random.seed(seed) 21 | torch.manual_seed(seed) 22 | torch.cuda.manual_seed(seed) 23 | torch.backends.cudnn.deterministic = True 24 | torch.backends.cudnn.benchmark = True 25 | 26 | 27 | Building = np.array([255, 255, 255]) # label 0 28 | Clutter = np.array([0, 0, 0]) # label 1 29 | num_classes = 2 30 | 31 | 32 | # split huge RS image to small patches 33 | def parse_args(): 34 | parser = argparse.ArgumentParser() 35 | parser.add_argument("--input-img-dir", default="data/AerialImageDataset/train/train_images") 36 | parser.add_argument("--input-mask-dir", default="data/AerialImageDataset/train/train_masks") 37 | parser.add_argument("--output-img-dir", default="data/AerialImageDataset/train/train/images") 38 | parser.add_argument("--output-mask-dir", default="data/AerialImageDataset/train/train/masks") 39 | parser.add_argument("--mode", type=str, default='train') 40 | parser.add_argument("--split-size-h", type=int, default=512) 41 | parser.add_argument("--split-size-w", type=int, default=512) 42 | parser.add_argument("--stride-h", type=int, default=512) 43 | parser.add_argument("--stride-w", type=int, default=512) 44 | return parser.parse_args() 45 | 46 | 47 | def label2rgb(mask): 48 | h, w = mask.shape[0], mask.shape[1] 49 | mask_rgb = np.zeros(shape=(h, w, 3), dtype=np.uint8) 50 | mask_convert = mask[np.newaxis, :, :] 51 | mask_rgb[np.all(mask_convert == 0, axis=0)] = Building 52 | mask_rgb[np.all(mask_convert == 1, axis=0)] = Clutter 53 | 54 | return mask_rgb 55 | 56 | 57 | def rgb2label(label): 58 | label_seg = np.zeros(label.shape[:2], dtype=np.uint8) 59 | label_seg[np.all(label == Building, axis=-1)] = 0 60 | label_seg[np.all(label == Clutter, axis=-1)] = 1 61 | 62 | return label_seg 63 | 64 | 65 | def image_augment(image, mask, mode='train'): 66 | image_list = [] 67 | mask_list = [] 68 | image_width, image_height = image.shape[1], image.shape[0] 69 | mask_width, mask_height = mask.shape[1], mask.shape[0] 70 | assert image_height == mask_height and image_width == mask_width 71 | if mode == 'train': 72 | # train_transform = [ 73 | # # albu.HorizontalFlip(p=0.5), 74 | # # albu.VerticalFlip(p=0.5), 75 | # # albu.RandomRotate90(p=0.5), 76 | # # albu.RandomSizedCrop(min_max_height=(image_height//2, image_height), 77 | # # width=image_width, height=image_height, p=0.15), 78 | # # albu.RandomShadow(num_shadows_lower=2, num_shadows_upper=3, 79 | # # shadow_dimension=3, shadow_roi=(0, 0.5, 1, 1), p=0.1), 80 | # # albu.GaussianBlur(p=0.01), 81 | # albu.OneOf([ 82 | # albu.RandomBrightnessContrast(brightness_limit=0.25, contrast_limit=0.25), 83 | # albu.HueSaturationValue(hue_shift_limit=10, sat_shift_limit=35, val_shift_limit=25) 84 | # ], p=0.15) 85 | # ] 86 | # aug = albu.Compose(train_transform)(image=image.copy(), mask=mask.copy()) 87 | 88 | image_list_train = [image] 89 | mask_list_train = [mask] 90 | for i in range(len(image_list_train)): 91 | mask_tmp = rgb2label(mask_list_train[i]) 92 | image_list.append(image_list_train[i]) 93 | mask_list.append(mask_tmp) 94 | else: 95 | mask = rgb2label(mask.copy()) 96 | image_list.append(image) 97 | mask_list.append(mask) 98 | return image_list, mask_list 99 | 100 | 101 | def padifneeded(image, mask, patch_size, stride): 102 | 103 | oh, ow = image.shape[0], image.shape[1] 104 | padh, padw = 0, 0 105 | while (oh + padh -patch_size[0]) % stride[0] != 0: 106 | padh = padh + 1 107 | while (ow + padw -patch_size[1]) % stride[1] != 0: 108 | padw = padw + 1 109 | 110 | h, w = oh + padh, ow + padw 111 | 112 | pad = albu.PadIfNeeded(min_height=h, min_width=w)(image=image, mask=mask) 113 | img_pad, mask_pad = pad['image'], pad['mask'] 114 | 115 | # print(img_pad.shape) 116 | return img_pad, mask_pad 117 | 118 | 119 | def patch_format(inp): 120 | (img_path, mask_path, imgs_output_dir, masks_output_dir, mode, split_size, stride) = inp 121 | if mode == 'val': 122 | gt_path = masks_output_dir + "_gt" 123 | if not os.path.exists(gt_path): 124 | os.makedirs(gt_path) 125 | 126 | img = cv2.imread(img_path, cv2.IMREAD_COLOR) 127 | mask = cv2.imread(mask_path, cv2.IMREAD_COLOR) 128 | img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 129 | mask = cv2.cvtColor(mask, cv2.COLOR_BGR2RGB) 130 | id = os.path.splitext(os.path.basename(img_path))[0] 131 | assert img.shape == mask.shape 132 | 133 | img, mask = padifneeded(img.copy(), mask.copy(), split_size, stride) 134 | 135 | image_list, mask_list = image_augment(image=img.copy(), mask=mask.copy(), mode=mode) 136 | assert len(image_list) == len(mask_list) 137 | for m in range(len(image_list)): 138 | k = 0 139 | img = image_list[m] 140 | mask = mask_list[m] 141 | assert img.shape[0] == mask.shape[0] and img.shape[1] == mask.shape[1] 142 | for y in range(0, img.shape[0], stride[0]): 143 | for x in range(0, img.shape[1], stride[1]): 144 | img_tile_cut = img[y:y + split_size[0], x:x + split_size[1]] 145 | mask_tile_cut = mask[y:y + split_size[0], x:x + split_size[1]] 146 | img_tile, mask_tile = img_tile_cut, mask_tile_cut 147 | 148 | if img_tile.shape[0] == split_size[0] and img_tile.shape[1] == split_size[1] \ 149 | and mask_tile.shape[0] == split_size[0] and mask_tile.shape[1] == split_size[1]: 150 | bins = np.array(range(num_classes + 1)) 151 | class_pixel_counts, _ = np.histogram(mask_tile, bins=bins) 152 | cf = class_pixel_counts / (mask_tile.shape[0] * mask_tile.shape[1]) 153 | if cf[0] > 0.05: 154 | if mode == 'train': 155 | img_tile = cv2.cvtColor(img_tile, cv2.COLOR_RGB2BGR) 156 | out_img_path = os.path.join(imgs_output_dir, "{}_{}_{}.png".format(id, m, k)) 157 | cv2.imwrite(out_img_path, img_tile) 158 | 159 | out_mask_path = os.path.join(masks_output_dir, "{}_{}_{}.png".format(id, m, k)) 160 | cv2.imwrite(out_mask_path, mask_tile) 161 | else: 162 | img_tile = cv2.cvtColor(img_tile, cv2.COLOR_RGB2BGR) 163 | out_img_path = os.path.join(imgs_output_dir, "{}_{}_{}.png".format(id, m, k)) 164 | cv2.imwrite(out_img_path, img_tile) 165 | 166 | out_mask_path = os.path.join(masks_output_dir, "{}_{}_{}.png".format(id, m, k)) 167 | cv2.imwrite(out_mask_path, mask_tile) 168 | 169 | out_mask_path_gt = os.path.join(gt_path, "{}_{}_{}.png".format(id, m, k)) 170 | cv2.imwrite(out_mask_path_gt, label2rgb(mask_tile)) 171 | 172 | k += 1 173 | 174 | 175 | if __name__ == "__main__": 176 | seed_everything(SEED) 177 | args = parse_args() 178 | input_img_dir = args.input_img_dir 179 | input_mask_dir = args.input_mask_dir 180 | img_paths = glob.glob(os.path.join(input_img_dir, "*.tif")) 181 | mask_paths = glob.glob(os.path.join(input_mask_dir, "*.tif")) 182 | img_paths.sort() 183 | mask_paths.sort() 184 | 185 | imgs_output_dir = args.output_img_dir 186 | masks_output_dir = args.output_mask_dir 187 | 188 | mode = args.mode 189 | 190 | split_size_h = args.split_size_h 191 | split_size_w = args.split_size_w 192 | split_size = (split_size_h, split_size_w) 193 | stride_h = args.stride_h 194 | stride_w = args.stride_w 195 | stride = (stride_h, stride_w) 196 | 197 | if not os.path.exists(imgs_output_dir): 198 | os.makedirs(imgs_output_dir) 199 | if not os.path.exists(masks_output_dir): 200 | os.makedirs(masks_output_dir) 201 | 202 | inp = [(img_path, mask_path, imgs_output_dir, masks_output_dir, mode, split_size, stride) 203 | for img_path, mask_path in zip(img_paths, mask_paths)] 204 | 205 | t0 = time.time() 206 | mpp.Pool(processes=mp.cpu_count()).map(patch_format, inp) 207 | t1 = time.time() 208 | split_time = t1 - t0 209 | print('images spliting spends: {} s'.format(split_time)) 210 | 211 | 212 | -------------------------------------------------------------------------------- /mass_patch_split.py: -------------------------------------------------------------------------------- 1 | import glob 2 | import os 3 | import numpy as np 4 | import cv2 5 | import multiprocessing.pool as mpp 6 | import multiprocessing as mp 7 | import time 8 | import argparse 9 | import torch 10 | import albumentations as albu 11 | 12 | import random 13 | 14 | SEED = 42 15 | 16 | 17 | def seed_everything(seed): 18 | random.seed(seed) 19 | os.environ['PYTHONHASHSEED'] = str(seed) 20 | np.random.seed(seed) 21 | torch.manual_seed(seed) 22 | torch.cuda.manual_seed(seed) 23 | torch.backends.cudnn.deterministic = True 24 | torch.backends.cudnn.benchmark = True 25 | 26 | 27 | Building = np.array([255, 255, 255]) # label 0 28 | Clutter = np.array([0, 0, 0]) # label 1 29 | num_classes = 2 30 | 31 | 32 | # split huge RS image to small patches 33 | def parse_args(): 34 | parser = argparse.ArgumentParser() 35 | parser.add_argument("--input-img-dir", default="data/mass_build/png/train") 36 | parser.add_argument("--input-mask-dir", default="data/mass_build/png/train_labels") 37 | parser.add_argument("--output-img-dir", default="data/mass_build/png/train_images") 38 | parser.add_argument("--output-mask-dir", default="data/mass_build/png/train_masks") 39 | parser.add_argument("--mode", type=str, default='train') 40 | 41 | return parser.parse_args() 42 | 43 | 44 | def label2rgb(mask): 45 | h, w = mask.shape[0], mask.shape[1] 46 | mask_rgb = np.zeros(shape=(h, w, 3), dtype=np.uint8) 47 | mask_convert = mask[np.newaxis, :, :] 48 | mask_rgb[np.all(mask_convert == 0, axis=0)] = Building 49 | mask_rgb[np.all(mask_convert == 1, axis=0)] = Clutter 50 | 51 | return mask_rgb 52 | 53 | 54 | def rgb2label(label): 55 | label_seg = np.zeros(label.shape[:2], dtype=np.uint8) 56 | label_seg[np.all(label == Building, axis=-1)] = 0 57 | label_seg[np.all(label == Clutter, axis=-1)] = 1 58 | 59 | return label_seg 60 | 61 | 62 | def image_augment(image, mask, mode='train'): 63 | image_list = [] 64 | mask_list = [] 65 | image_width, image_height = image.shape[1], image.shape[0] 66 | mask_width, mask_height = mask.shape[1], mask.shape[0] 67 | assert image_height == mask_height and image_width == mask_width 68 | if mode == 'train': 69 | hflip = albu.HorizontalFlip(p=1)(image=image.copy(), mask=mask.copy()) 70 | img_h, mask_h = hflip['image'], hflip['mask'] 71 | 72 | vflip = albu.VerticalFlip(p=1)(image=image.copy(), mask=mask.copy()) 73 | img_v, mask_v = vflip['image'], vflip['mask'] 74 | 75 | image_list_train = [image, img_h, img_v] 76 | mask_list_train = [mask, mask_h, mask_v] 77 | for i in range(len(image_list_train)): 78 | mask_tmp = rgb2label(mask_list_train[i]) 79 | image_list.append(image_list_train[i]) 80 | mask_list.append(mask_tmp) 81 | else: 82 | mask = rgb2label(mask.copy()) 83 | image_list.append(image) 84 | mask_list.append(mask) 85 | return image_list, mask_list 86 | 87 | 88 | def patch_format(inp): 89 | (img_path, mask_path, imgs_output_dir, masks_output_dir, mode) = inp 90 | 91 | img = cv2.imread(img_path, cv2.IMREAD_COLOR) 92 | mask = cv2.imread(mask_path, cv2.IMREAD_COLOR) 93 | img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 94 | mask = cv2.cvtColor(mask, cv2.COLOR_BGR2RGB) 95 | id = os.path.splitext(os.path.basename(img_path))[0] 96 | assert img.shape == mask.shape 97 | 98 | if mode == 'train': 99 | mask_tmp = np.zeros(mask.shape[:2], dtype=np.uint8) 100 | mask_tmp[np.all(img == [255, 255, 255], axis=-1)] = 1 101 | mask_c = mask_tmp[np.newaxis, :, :] 102 | mask[np.all(mask_c == 1, axis=0)] = [0, 0, 0] 103 | img[np.all(img == [255, 255, 255], axis=-1)] = [0, 0, 0] 104 | 105 | image_list, mask_list = image_augment(image=img.copy(), mask=mask.copy(), mode=mode) 106 | assert len(image_list) == len(mask_list) 107 | for m in range(len(image_list)): 108 | img = image_list[m] 109 | mask = mask_list[m] 110 | img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) 111 | out_img_path = os.path.join(imgs_output_dir, "{}_{}.png".format(id, m)) 112 | cv2.imwrite(out_img_path, img) 113 | 114 | out_mask_path = os.path.join(masks_output_dir, "{}_{}.png".format(id, m)) 115 | cv2.imwrite(out_mask_path, mask) 116 | 117 | 118 | if __name__ == "__main__": 119 | seed_everything(SEED) 120 | args = parse_args() 121 | input_img_dir = args.input_img_dir 122 | input_mask_dir = args.input_mask_dir 123 | img_paths = glob.glob(os.path.join(input_img_dir, "*.png")) 124 | mask_paths = glob.glob(os.path.join(input_mask_dir, "*.png")) 125 | img_paths.sort() 126 | mask_paths.sort() 127 | 128 | imgs_output_dir = args.output_img_dir 129 | masks_output_dir = args.output_mask_dir 130 | 131 | mode = args.mode 132 | 133 | if not os.path.exists(imgs_output_dir): 134 | os.makedirs(imgs_output_dir) 135 | if not os.path.exists(masks_output_dir): 136 | os.makedirs(masks_output_dir) 137 | 138 | inp = [(img_path, mask_path, imgs_output_dir, masks_output_dir, mode) 139 | for img_path, mask_path in zip(img_paths, mask_paths)] 140 | 141 | t0 = time.time() 142 | mpp.Pool(processes=mp.cpu_count()).map(patch_format, inp) 143 | t1 = time.time() 144 | split_time = t1 - t0 145 | print('images spliting spends: {} s'.format(split_time)) 146 | 147 | 148 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | timm 2 | catalyst==20.09 3 | pytorch-lightning==1.5.9 4 | albumentations==1.1.0 5 | ttach 6 | numpy 7 | tqdm 8 | opencv-python 9 | scipy 10 | matplotlib 11 | einops 12 | addict -------------------------------------------------------------------------------- /tools/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WangLibo1995/BuildFormer/c20f15805694fa568b8ac531ba51bc5e9c5a29c6/tools/__init__.py -------------------------------------------------------------------------------- /tools/cfg.py: -------------------------------------------------------------------------------- 1 | import pydoc 2 | import sys 3 | from importlib import import_module 4 | from pathlib import Path 5 | from typing import Union 6 | 7 | from addict import Dict 8 | 9 | 10 | class ConfigDict(Dict): 11 | def __missing__(self, name): 12 | raise KeyError(name) 13 | 14 | def __getattr__(self, name): 15 | try: 16 | value = super().__getattr__(name) 17 | except KeyError: 18 | ex = AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") 19 | else: 20 | return value 21 | raise ex 22 | 23 | 24 | def py2dict(file_path: Union[str, Path]) -> dict: 25 | """Convert python file to dictionary. 26 | The main use - config parser. 27 | file: 28 | ``` 29 | a = 1 30 | b = 3 31 | c = range(10) 32 | ``` 33 | will be converted to 34 | {'a':1, 35 | 'b':3, 36 | 'c': range(10) 37 | } 38 | Args: 39 | file_path: path to the original python file. 40 | Returns: {key: value}, where key - all variables defined in the file and value is their value. 41 | """ 42 | file_path = Path(file_path).absolute() 43 | 44 | if file_path.suffix != ".py": 45 | raise TypeError(f"Only Py file can be parsed, but got {file_path.name} instead.") 46 | 47 | if not file_path.exists(): 48 | raise FileExistsError(f"There is no file at the path {file_path}") 49 | 50 | module_name = file_path.stem 51 | 52 | if "." in module_name: 53 | raise ValueError("Dots are not allowed in config file path.") 54 | 55 | config_dir = str(file_path.parent) 56 | 57 | sys.path.insert(0, config_dir) 58 | 59 | mod = import_module(module_name) 60 | sys.path.pop(0) 61 | cfg_dict = {name: value for name, value in mod.__dict__.items() if not name.startswith("__")} 62 | 63 | return cfg_dict 64 | 65 | 66 | def py2cfg(file_path: Union[str, Path]) -> ConfigDict: 67 | cfg_dict = py2dict(file_path) 68 | 69 | return ConfigDict(cfg_dict) 70 | 71 | 72 | def object_from_dict(d, parent=None, **default_kwargs): 73 | kwargs = d.copy() 74 | object_type = kwargs.pop("type") 75 | for name, value in default_kwargs.items(): 76 | kwargs.setdefault(name, value) 77 | 78 | if parent is not None: 79 | return getattr(parent, object_type)(**kwargs) # skipcq PTC-W0034 80 | 81 | return pydoc.locate(object_type)(**kwargs) -------------------------------------------------------------------------------- /tools/metric.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | class Evaluator(object): 5 | def __init__(self, num_class): 6 | self.num_class = num_class 7 | self.confusion_matrix = np.zeros((self.num_class,) * 2) 8 | self.eps = 1e-8 9 | 10 | def get_tp_fp_tn_fn(self): 11 | tp = np.diag(self.confusion_matrix) 12 | fp = self.confusion_matrix.sum(axis=0) - np.diag(self.confusion_matrix) 13 | fn = self.confusion_matrix.sum(axis=1) - np.diag(self.confusion_matrix) 14 | tn = np.diag(self.confusion_matrix).sum() - np.diag(self.confusion_matrix) 15 | return tp, fp, tn, fn 16 | 17 | def Precision(self): 18 | tp, fp, tn, fn = self.get_tp_fp_tn_fn() 19 | precision = tp / (tp + fp) 20 | return precision 21 | 22 | def Recall(self): 23 | tp, fp, tn, fn = self.get_tp_fp_tn_fn() 24 | recall = tp / (tp + fn) 25 | return recall 26 | 27 | def F1(self): 28 | tp, fp, tn, fn = self.get_tp_fp_tn_fn() 29 | Precision = tp / (tp + fp) 30 | Recall = tp / (tp + fn) 31 | F1 = (2.0 * Precision * Recall) / (Precision + Recall) 32 | return F1 33 | 34 | def OA(self): 35 | OA = np.diag(self.confusion_matrix).sum() / (self.confusion_matrix.sum() + self.eps) 36 | return OA 37 | 38 | def Intersection_over_Union(self): 39 | tp, fp, tn, fn = self.get_tp_fp_tn_fn() 40 | IoU = tp / (tp + fn + fp) 41 | return IoU 42 | 43 | def Dice(self): 44 | tp, fp, tn, fn = self.get_tp_fp_tn_fn() 45 | Dice = 2 * tp / ((tp + fp) + (tp + fn)) 46 | return Dice 47 | 48 | def Pixel_Accuracy_Class(self): 49 | # TP TP+FP 50 | Acc = np.diag(self.confusion_matrix) / (self.confusion_matrix.sum(axis=0) + self.eps) 51 | return Acc 52 | 53 | def Frequency_Weighted_Intersection_over_Union(self): 54 | freq = np.sum(self.confusion_matrix, axis=1) / (np.sum(self.confusion_matrix) + self.eps) 55 | iou = self.Intersection_over_Union() 56 | FWIoU = (freq[freq > 0] * iou[freq > 0]).sum() 57 | return FWIoU 58 | 59 | def _generate_matrix(self, gt_image, pre_image): 60 | mask = (gt_image >= 0) & (gt_image < self.num_class) 61 | label = self.num_class * gt_image[mask].astype('int') + pre_image[mask] 62 | count = np.bincount(label, minlength=self.num_class ** 2) 63 | confusion_matrix = count.reshape(self.num_class, self.num_class) 64 | return confusion_matrix 65 | 66 | def add_batch(self, gt_image, pre_image): 67 | assert gt_image.shape == pre_image.shape, 'pre_image shape {}, gt_image shape {}'.format(pre_image.shape, 68 | gt_image.shape) 69 | self.confusion_matrix += self._generate_matrix(gt_image, pre_image) 70 | 71 | def reset(self): 72 | self.confusion_matrix = np.zeros((self.num_class,) * 2) 73 | 74 | 75 | if __name__ == '__main__': 76 | 77 | gt = np.array([[0, 2, 1], 78 | [1, 2, 1], 79 | [1, 0, 1]]) 80 | 81 | pre = np.array([[0, 1, 1], 82 | [2, 0, 1], 83 | [1, 1, 1]]) 84 | 85 | eval = Evaluator(num_class=3) 86 | eval.add_batch(gt, pre) 87 | print(eval.confusion_matrix) 88 | print(eval.get_tp_fp_tn_fn()) 89 | print(eval.Precision()) 90 | print(eval.Recall()) 91 | print(eval.Intersection_over_Union()) 92 | print(eval.OA()) 93 | print(eval.F1()) 94 | print(eval.Frequency_Weighted_Intersection_over_Union()) 95 | -------------------------------------------------------------------------------- /train_supervision.py: -------------------------------------------------------------------------------- 1 | import pytorch_lightning as pl 2 | from pytorch_lightning.callbacks import ModelCheckpoint 3 | from tools.cfg import py2cfg 4 | import os 5 | import torch 6 | from torch import nn 7 | import cv2 8 | import numpy as np 9 | import argparse 10 | from pathlib import Path 11 | from tools.metric import Evaluator 12 | from pytorch_lightning.loggers import CSVLogger 13 | import random 14 | 15 | 16 | def seed_everything(seed): 17 | random.seed(seed) 18 | os.environ['PYTHONHASHSEED'] = str(seed) 19 | np.random.seed(seed) 20 | torch.manual_seed(seed) 21 | torch.cuda.manual_seed(seed) 22 | torch.backends.cudnn.deterministic = True 23 | torch.backends.cudnn.benchmark = True 24 | 25 | 26 | def get_args(): 27 | parser = argparse.ArgumentParser() 28 | arg = parser.add_argument 29 | arg("-c", "--config_path", type=Path, help="Path to the config.", required=True) 30 | return parser.parse_args() 31 | 32 | 33 | class Supervision_Train(pl.LightningModule): 34 | def __init__(self, config): 35 | super().__init__() 36 | self.config = config 37 | self.net = config.net 38 | self.automatic_optimization = False 39 | 40 | self.loss = config.loss 41 | 42 | self.metrics_train = Evaluator(num_class=config.num_classes) 43 | self.metrics_val = Evaluator(num_class=config.num_classes) 44 | 45 | def forward(self, x): 46 | # only net is used in the prediction/inference 47 | seg_pre = self.net(x) 48 | return seg_pre 49 | 50 | def training_step(self, batch, batch_idx): 51 | img, mask = batch['img'], batch['gt_semantic_seg'] 52 | 53 | prediction = self.net(img) 54 | loss = self.loss(prediction, mask) 55 | 56 | if self.config.use_aux_loss: 57 | pre_mask = nn.Softmax(dim=1)(prediction[0]) 58 | else: 59 | pre_mask = nn.Softmax(dim=1)(prediction) 60 | 61 | pre_mask = pre_mask.argmax(dim=1) 62 | for i in range(mask.shape[0]): 63 | self.metrics_train.add_batch(mask[i].cpu().numpy(), pre_mask[i].cpu().numpy()) 64 | 65 | # supervision stage 66 | opt = self.optimizers(use_pl_optimizer=False) 67 | self.manual_backward(loss) 68 | if (batch_idx + 1) % self.config.accumulate_n == 0: 69 | opt.step() 70 | opt.zero_grad() 71 | 72 | sch = self.lr_schedulers() 73 | if self.trainer.is_last_batch and (self.trainer.current_epoch + 1) % 1 == 0: 74 | sch.step() 75 | 76 | return {"loss": loss} 77 | 78 | def training_epoch_end(self, outputs): 79 | if 'vaihingen' in self.config.log_name: 80 | mIoU = np.nanmean(self.metrics_train.Intersection_over_Union()[:-1]) 81 | F1 = np.nanmean(self.metrics_train.F1()[:-1]) 82 | elif 'potsdam' in self.config.log_name: 83 | mIoU = np.nanmean(self.metrics_train.Intersection_over_Union()[:-1]) 84 | F1 = np.nanmean(self.metrics_train.F1()[:-1]) 85 | elif 'whubuilding' in self.config.log_name: 86 | mIoU = np.nanmean(self.metrics_train.Intersection_over_Union()[:-1]) 87 | F1 = np.nanmean(self.metrics_train.F1()[:-1]) 88 | elif 'massbuilding' in self.config.log_name: 89 | mIoU = np.nanmean(self.metrics_train.Intersection_over_Union()[:-1]) 90 | F1 = np.nanmean(self.metrics_train.F1()[:-1]) 91 | elif 'inriabuilding' in self.config.log_name: 92 | mIoU = np.nanmean(self.metrics_train.Intersection_over_Union()[:-1]) 93 | F1 = np.nanmean(self.metrics_train.F1()[:-1]) 94 | else: 95 | mIoU = np.nanmean(self.metrics_train.Intersection_over_Union()) 96 | F1 = np.nanmean(self.metrics_train.F1()) 97 | 98 | OA = np.nanmean(self.metrics_train.OA()) 99 | iou_per_class = self.metrics_train.Intersection_over_Union() 100 | eval_value = {'mIoU': mIoU, 101 | 'F1': F1, 102 | 'OA': OA} 103 | print('train:', eval_value) 104 | 105 | iou_value = {} 106 | for class_name, iou in zip(self.config.classes, iou_per_class): 107 | iou_value[class_name] = iou 108 | print(iou_value) 109 | self.metrics_train.reset() 110 | loss = torch.stack([x["loss"] for x in outputs]).mean() 111 | log_dict = {"train_loss": loss, 'train_mIoU': mIoU, 'train_F1': F1, 'train_OA': OA} 112 | self.log_dict(log_dict, prog_bar=True) 113 | 114 | def validation_step(self, batch, batch_idx): 115 | img, mask = batch['img'], batch['gt_semantic_seg'] 116 | prediction = self.forward(img) 117 | pre_mask = nn.Softmax(dim=1)(prediction) 118 | pre_mask = pre_mask.argmax(dim=1) 119 | for i in range(mask.shape[0]): 120 | self.metrics_val.add_batch(mask[i].cpu().numpy(), pre_mask[i].cpu().numpy()) 121 | 122 | loss_val = self.loss(prediction, mask) 123 | return {"loss_val": loss_val} 124 | 125 | def validation_epoch_end(self, outputs): 126 | if 'vaihingen' in self.config.log_name: 127 | mIoU = np.nanmean(self.metrics_val.Intersection_over_Union()[:-1]) 128 | F1 = np.nanmean(self.metrics_val.F1()[:-1]) 129 | elif 'potsdam' in self.config.log_name: 130 | mIoU = np.nanmean(self.metrics_val.Intersection_over_Union()[:-1]) 131 | F1 = np.nanmean(self.metrics_val.F1()[:-1]) 132 | elif 'whubuilding' in self.config.log_name: 133 | mIoU = np.nanmean(self.metrics_val.Intersection_over_Union()[:-1]) 134 | F1 = np.nanmean(self.metrics_val.F1()[:-1]) 135 | elif 'massbuilding' in self.config.log_name: 136 | mIoU = np.nanmean(self.metrics_val.Intersection_over_Union()[:-1]) 137 | F1 = np.nanmean(self.metrics_val.F1()[:-1]) 138 | elif 'inriabuilding' in self.config.log_name: 139 | mIoU = np.nanmean(self.metrics_val.Intersection_over_Union()[:-1]) 140 | F1 = np.nanmean(self.metrics_val.F1()[:-1]) 141 | else: 142 | mIoU = np.nanmean(self.metrics_val.Intersection_over_Union()) 143 | F1 = np.nanmean(self.metrics_val.F1()) 144 | 145 | OA = np.nanmean(self.metrics_val.OA()) 146 | iou_per_class = self.metrics_val.Intersection_over_Union() 147 | 148 | eval_value = {'mIoU': mIoU, 149 | 'F1': F1, 150 | 'OA': OA} 151 | print('val:', eval_value) 152 | iou_value = {} 153 | for class_name, iou in zip(self.config.classes, iou_per_class): 154 | iou_value[class_name] = iou 155 | print(iou_value) 156 | 157 | self.metrics_val.reset() 158 | loss = torch.stack([x["loss_val"] for x in outputs]).mean() 159 | log_dict = {"val_loss": loss, 'val_mIoU': mIoU, 'val_F1': F1, 'val_OA': OA} 160 | self.log_dict(log_dict, prog_bar=True) 161 | 162 | def configure_optimizers(self): 163 | optimizer = self.config.optimizer 164 | lr_scheduler = self.config.lr_scheduler 165 | 166 | return [optimizer], [lr_scheduler] 167 | 168 | def train_dataloader(self): 169 | 170 | return self.config.train_loader 171 | 172 | def val_dataloader(self): 173 | 174 | return self.config.val_loader 175 | 176 | 177 | # training 178 | def main(): 179 | args = get_args() 180 | config = py2cfg(args.config_path) 181 | seed_everything(42) 182 | 183 | checkpoint_callback = ModelCheckpoint(save_top_k=config.save_top_k, monitor=config.monitor, 184 | save_last=config.save_last, mode=config.monitor_mode, 185 | dirpath=config.weights_path, 186 | filename=config.weights_name) 187 | logger = CSVLogger('lightning_logs', name=config.log_name) 188 | 189 | model = Supervision_Train(config) 190 | if config.pretrained_ckpt_path: 191 | model = Supervision_Train.load_from_checkpoint(config.pretrained_ckpt_path, config=config) 192 | 193 | trainer = pl.Trainer(devices=config.gpus, max_epochs=config.max_epoch, accelerator='gpu', 194 | check_val_every_n_epoch=config.check_val_every_n_epoch, 195 | callbacks=[checkpoint_callback], strategy=config.strategy, 196 | resume_from_checkpoint=config.resume_ckpt_path, logger=logger) 197 | trainer.fit(model=model) 198 | 199 | 200 | if __name__ == "__main__": 201 | main() 202 | -------------------------------------------------------------------------------- /whubuilding_mask_convert.py: -------------------------------------------------------------------------------- 1 | import glob 2 | import os 3 | import numpy as np 4 | import cv2 5 | from PIL import Image 6 | import multiprocessing.pool as mpp 7 | import multiprocessing as mp 8 | import time 9 | import argparse 10 | import torch 11 | from torchvision.transforms import (Pad, ColorJitter, Resize, FiveCrop, RandomResizedCrop, 12 | RandomHorizontalFlip, RandomRotation, RandomVerticalFlip) 13 | import random 14 | 15 | SEED = 42 16 | 17 | 18 | def seed_everything(seed): 19 | random.seed(seed) 20 | os.environ['PYTHONHASHSEED'] = str(seed) 21 | np.random.seed(seed) 22 | torch.manual_seed(seed) 23 | torch.cuda.manual_seed(seed) 24 | torch.backends.cudnn.deterministic = True 25 | torch.backends.cudnn.benchmark = True 26 | 27 | 28 | def parse_args(): 29 | parser = argparse.ArgumentParser() 30 | parser.add_argument("--mask-dir", default="data/whubuilding/train/masks_origin") 31 | parser.add_argument("--output-mask-dir", default="data/whubuilding/train/masks") 32 | return parser.parse_args() 33 | 34 | 35 | def rgb_to_label(mask): 36 | h, w = mask.shape[0], mask.shape[1] 37 | label = np.zeros(shape=(h, w), dtype=np.uint8) 38 | label[np.all(mask == [0, 0, 0], axis=-1)] = 1 39 | label[np.all(mask == [255, 255, 255], axis=-1)] = 0 40 | return label 41 | 42 | 43 | def patch_format(inp): 44 | (mask_path, masks_output_dir) = inp 45 | # print(mask_path, masks_output_dir) 46 | mask_filename = os.path.splitext(os.path.basename(mask_path))[0] 47 | mask = cv2.imread(mask_path) 48 | label = rgb_to_label(mask) 49 | out_mask_path = os.path.join(masks_output_dir, "{}.png".format(mask_filename)) 50 | cv2.imwrite(out_mask_path, label) 51 | 52 | 53 | if __name__ == "__main__": 54 | seed_everything(SEED) 55 | args = parse_args() 56 | masks_dir = args.mask_dir 57 | masks_output_dir = args.output_mask_dir 58 | mask_paths = glob.glob(os.path.join(masks_dir, "*.png")) 59 | # print(mask_paths) 60 | 61 | if not os.path.exists(masks_output_dir): 62 | os.makedirs(masks_output_dir) 63 | 64 | inp = [(mask_path, masks_output_dir) for mask_path in mask_paths] 65 | 66 | t0 = time.time() 67 | mpp.Pool(processes=mp.cpu_count()).map(patch_format, inp) 68 | t1 = time.time() 69 | split_time = t1 - t0 70 | print('images spliting spends: {} s'.format(split_time)) 71 | 72 | 73 | --------------------------------------------------------------------------------