├── .gitignore ├── LICENSE ├── README.md ├── assets ├── figure.png └── teaser_DMENet.gif ├── config.py ├── deconvolution ├── DMENet_fast_deconv.m ├── dir2.m ├── fast_deconv.m ├── readme.md ├── run_DMENet_deconv.m ├── solve_image.m └── sources │ ├── defocus_map │ ├── CUHK │ │ └── 0027.png │ └── DPDD │ │ ├── 0000.png │ │ └── 0001.png │ └── input │ ├── CUHK │ └── 0027.jpg │ └── DPDD │ └── 1P0A0917.png ├── evaluation ├── RTF │ ├── convertion.mat │ ├── quantitative_RTF.m │ ├── readme.md │ └── run_quantitative_RTF.m └── readme.md ├── install_CUDA10.0.sh ├── install_CUDA11.1.sh ├── main.py ├── model.py ├── requirements.txt └── utils.py /.gitignore: -------------------------------------------------------------------------------- 1 | # data 2 | *.sublime* 3 | pretrained/* 4 | utils/* 5 | setup.sh 6 | update.sh 7 | update_amend.sh 8 | jupyter/* 9 | .ipynb* 10 | sample/* 11 | *.zip 12 | ckpt/ 13 | eval_self.py 14 | 15 | datasets/* 16 | logs/* 17 | backup/* 18 | deconvolution/output/* 19 | 20 | # trash 21 | .dropbox 22 | 23 | ### Python ### 24 | # Byte-compiled / optimized / DLL files 25 | __pycache__/ 26 | *.py[cod] 27 | *$py.class 28 | 29 | ### Vim ### 30 | [._]*.s[a-w][a-z] 31 | [._]s[a-w][a-z] 32 | *.un~ 33 | Session.vim 34 | .netrwhist 35 | *~ 36 | 37 | ### pycharm ### 38 | .idea 39 | 40 | ## config ## 41 | .gitignore 42 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## DMENet: Deep Defocus Map Estimation Network
Official Implementation of the CVPR 2021 Paper
[Project](https://junyonglee.me/projects/DMENet) | [Paper](https://openaccess.thecvf.com/content_CVPR_2019/papers/Lee_Deep_Defocus_Map_Estimation_Using_Domain_Adaptation_CVPR_2019_paper.pdf) | [Supp](https://www.dropbox.com/s/van0beau0npq3de/supp.zip?dl=1) | [Poster](https://www.dropbox.com/s/85umxea9uha3ptq/CVPR2019_poster.pdf?raw=1)
[![License CC BY-NC](https://img.shields.io/badge/Anvil-Open_in_Anvil_(may_be_offline)-blue.svg?style=flat)](https://2JI532DIZN4TSYWF.anvil.app/BIEWGFSFTYML53VXPQZBRNTX) 2 | 3 | This repository contains the official matlab implementation of SYNDOF generation used in the following paper: 4 | 5 | > [**Deep Defocus Map Estimation using Domain Adaptation**](https://junyonglee.me/projects/DMENet)
6 | > [Junyong Lee](https://junyonglee.me)1, [Sungkil Lee](http://cg.skku.edu/slee/)2, [Sunghyun Cho](https://www.scho.pe.kr/)3, and [Seungyong Lee](http://cg.postech.ac.kr/leesy/)1
7 | > 1POSTECH, 2Sungkyunkwan University, 3DGIST
8 | > *IEEE Computer Vision and Pattern Recognition (**CVPR**) 2019*
9 | 10 | 11 |

12 | 13 | 14 | 15 |

16 | 17 | ## Getting Started 18 | ### Prerequisites 19 | *Tested environment* 20 | 21 | ![Ubuntu](https://img.shields.io/badge/Ubuntu-16.04%20&%2018.04-blue.svg?style=plastic) 22 | ![Python 3.6](https://img.shields.io/badge/Python-3.6.13-green.svg?style=plastic) 23 | ![TensorFlow 1.15.0](https://img.shields.io/badge/tensorflow-1.15.0-green.svg?style=plastic) 24 | ![TensorLayer 1.11.1](https://img.shields.io/badge/tensorlayer-1.11.1-green.svg?style=plastic) 25 | ![CUDA 10.0.130](https://img.shields.io/badge/CUDA-10.0%20&%2011.1-green.svg?style=plastic) 26 | ![CUDNN 7.6.](https://img.shields.io/badge/CUDNN-7.6.5%20&%208.0.4-green.svg?style=plastic) 27 | 28 | 1. Setup environment 29 | * Option 1. install from scratch 30 | ```bash 31 | $ git clone https://github.com/codeslake/DMENet.git 32 | $ cd DMENet 33 | 34 | # for CUDA10 35 | $ conda create -y --name DMENet python=3.6 && conda activate DMENet 36 | $ sh install_CUDA10.0.sh 37 | 38 | # for CUDA11 (the name of conda environment matters) 39 | $ conda create -y --name DMENet_CUDA11 python=3.6 && conda activate DMENet_CUDA11 40 | $ sh install_CUDA11.1.sh 41 | ``` 42 | 43 | * Option 2. docker 44 | ```bash 45 | $ nvidia-docker run --privileged --gpus=all -it --name DMENet --rm codeslake/dmenet:CVPR2019 /bin/zsh 46 | $ git clone https://github.com/codeslake/DMENet.git 47 | $ cd DMENet 48 | 49 | # for CUDA10 50 | $ conda activate DMENet 51 | 52 | # for CUDA11 53 | $ conda activate DMENet_CUDA11 54 | ``` 55 | 56 | 3. Download and unzip datasets ([OneDrive](https://onedrive.live.com/download?resid=94530B7E5F49D254%2116358&authkey=!AETJe-m59LJctQM) | [Dropbox](https://www.dropbox.com/s/xkx1me8dvuv3xd0/datasets.zip?dl=1)) under `[DATASET_ROOT]`. 57 | 58 | ``` 59 | [DATASET_ROOT] 60 | ├── train 61 | │ ├── SYNDOF 62 | │ ├── CUHK 63 | │ └── Flickr 64 | └── test 65 | ├── CUHK 66 | ├── RTF 67 | └── SYNDOF 68 | ``` 69 | 70 | > **Note:** 71 | > 72 | > * `[DATASET_ROOT]` is currently set to `./datasets/`. It can be specified by modifying [`config.data_offset`](https://github.com/codeslake/DMENet/blob/master/config.py#L35-L36) in `./config.py`. 73 | 74 | 5. Download pretrained weights of DMENet ([OneDrive](https://onedrive.live.com/download?resid=94530B7E5F49D254%21485&authkey=!AJjiWABi0E5Or_M) | [Dropbox](https://www.dropbox.com/s/04lg03ogsto1fmw/DMENet_BDCS.zip?dl=1)) and unzip it as in `[LOG_ROOT]/DMENet_CVPR2019/DMENet_BDCS/checkpoint/DMENet_BDCS.npz` (`[LOG_ROOT]` is currently set to `./logs/`). 75 | 76 | 6. Download pretrained VGG19 weights ([OneDrive](https://onedrive.live.com/download?resid=94530B7E5F49D254%21489&authkey=!AC-Vfx3InXfEoZU) | [Dropbox](https://www.dropbox.com/s/7ah1jwrmggog4q9/vgg19.zip?dl=1)) and unzip as in `pretrained/vgg19.npy` (for training only). 77 | 78 | ### Logs 79 | * Training and testing logs will be saved under `[LOG_ROOT]/DMENet_CVPR2019/[mode]/`: 80 | 81 | ``` 82 | [LOG_ROOT] 83 | └──DMENet_CVPR2019 84 | ├── [mode] 85 | │ ├── checkpoint # model checkpoint 86 | │ ├── log # scalar/image log for tensorboard 87 | │ ├── sample # sample images of training 88 | │ └── result # resulting images of evaluation 89 | └── ... 90 | ``` 91 | > `[LOG_ROOT]` can be modified with [`config.root_offset`](https://github.com/codeslake/DMENet/blob/master/config.py#L73-L74) in `./config.py`. 92 | 93 | ## Testing final model of CVPR 2019 94 | *Please note that due to the server issue, the checkpoint used for the paper is lost. 95 |
The provided checkpoint is the new checkpoint that shows the closest evaluation results as in the paper.* 96 | 97 | *Check out [updated performance](/evaluation) with the new checkpoint.* 98 | 99 | * Test the final model by: 100 | 101 | ```bash 102 | python main.py --mode DMENet_BDCS --test_set CUHK 103 | ``` 104 | > Testing results will be saved in `[LOG_ROOT]/DMENet_CVPR2019/[mode]/result/[test_set]/`: 105 | > 106 | > ``` 107 | > ... 108 | > [LOG_ROOT]/DMENet_CVPR2019/[mode]/result/ 109 | > └── [test_set] 110 | > ├── image # input defocused images 111 | > ├── defocus_map # defocus images (network's direct output in range [0, 1]) 112 | > ├── defocus_map_min_max_norm # min-max normalized defocus images in range [0, 1] for visualization 113 | > └── sigma_map_7_norm # sigma maps containing normalized standard deviations (in range [0, 1]) for a Gaussian kernel. For the actual standard deviation value, one should multiply 7 to this map. 114 | > ``` 115 | 116 | > Quantitative results are computed from matlab. (*e.g.*, [evaluation on the RTF dataset](https://github.com/codeslake/DMENet/tree/master/evaluation/RTF)). 117 | 118 | * Options 119 | * `--mode`: The name of a model to test. The logging folder named with the `[mode]` will be created as `[LOG_ROOT]/DMENet_CVPR2019/[mode]/`. Default: `DMENet_BDCS` 120 | * `--test_set`: The name of a dataset to evaluate. `CUHK` | `RTF0` | `RTF1` | `RTF1_6` | `random`. Default: `CUHK` 121 | * The folder structure can be modified in the function [`get_eval_path(..)`](https://github.com/codeslake/DMENet/blob/master/config.py#L85-L98) in `./config.py`. 122 | * `random` is for testing models with any images, which should be placed as `[DATASET_ROOT]/test/random/*.[jpg|png]`. 123 | 124 | * Check out [the evaluation code for the RTF dataset](https://github.com/codeslake/DMENet/tree/master/evaluation/RTF), and [the deconvolution code](https://github.com/codeslake/DMENet/tree/master/deconvolution). 125 | 126 | 127 | 128 | ## Training & testing the network 129 | 130 | * Train the network by: 131 | 132 | ```bash 133 | python main.py --is_train --mode [mode] 134 | ``` 135 | 136 | > **Note:** 137 | > 138 | > * If you train DMENet with newly generated SYNDOF dataset from [this repo](https://github.com/codeslake/SYNDOF), comment [this line](https://github.com/codeslake/DMENet/blob/master/utils.py#L43) and uncomment [this line](https://github.com/codeslake/DMENet/blob/master/utils.py#L49) before the training. 139 | 140 | * Test the network by: 141 | 142 | ```bash 143 | python main.py --mode [mode] --test_set [test_set] 144 | ``` 145 | 146 | * arguments 147 | * `--mode`: The name of a model to train. The logging folder named with the `[mode]` will be created as `[LOG_ROOT]/DMENet_CVPR2019/[mode]/`. Default: `DMENet_BDCS` 148 | * `--is_pretrain`: Pretrain the network with the MSE loss (`True` | `False`). Default: `False` 149 | * `--delete_log`: Deletes `[LOG_ROOT]/DMENet_CVPR2019/[mode]/*` before training begins (`True` | `False`). Default: `False` 150 | 151 | 152 | ## Contact 153 | Open an issue for any inquiries. 154 | You may also have contact with [junyonglee@postech.ac.kr](mailto:junyonglee@postech.ac.kr) 155 | 156 | ## Related Links 157 | * CVPR 2021: Iterative Filter Adaptive Network for Single Image Defocus Deblurring \[[paper](https://openaccess.thecvf.com/content/CVPR2021/papers/Lee_Iterative_Filter_Adaptive_Network_for_Single_Image_Defocus_Deblurring_CVPR_2021_paper.pdf)\]\[[code](https://github.com/codeslake/IFAN)\] 158 | * ICCV 2021: Single Image Defocus Deblurring Using Kernel-Sharing Parallel Atrous Convolutions \[[paper](https://arxiv.org/pdf/2108.09108.pdf)\]\[[code](https://github.com/HyeongseokSon1/KPAC)\] 159 | * SYNDOF dataset generation repo \[[link](https://github.com/codeslake/SYNDOF)\] 160 | 161 | ## License 162 | ![License CC BY-NC](https://img.shields.io/badge/license-GNU_AGPv3-green.svg?style=flat)
163 | This software is being made available under the terms in the [LICENSE](LICENSE) file. 164 | Any exemptions to these terms require a license from the Pohang University of Science and Technology. 165 | 166 | ## Citation 167 | If you find this code useful, please consider citing: 168 | 169 | ``` 170 | @InProceedings{Lee2019DMENet, 171 | author = {Junyong Lee and Sungkil Lee and Sunghyun Cho and Seungyong Lee}, 172 | title = {Deep Defocus Map Estimation Using Domain Adaptation}, 173 | booktitle = {Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, 174 | year = {2019} 175 | } 176 | ``` 177 | 178 | -------------------------------------------------------------------------------- /assets/figure.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codeslake/DMENet/d844e5a6ad3e7a1c9157d50935de1a6eb6bc4bf8/assets/figure.png -------------------------------------------------------------------------------- /assets/teaser_DMENet.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codeslake/DMENet/d844e5a6ad3e7a1c9157d50935de1a6eb6bc4bf8/assets/teaser_DMENet.gif -------------------------------------------------------------------------------- /config.py: -------------------------------------------------------------------------------- 1 | from easydict import EasyDict as edict 2 | import json 3 | import os 4 | 5 | config = edict() 6 | config.TRAIN = edict() 7 | config.TEST = edict() 8 | 9 | ## Adam 10 | config.TRAIN.batch_size = 3 11 | config.TRAIN.batch_size_init = 8 12 | config.TRAIN.lr_init = 1e-4 13 | config.TRAIN.lr_init_init = 1e-4 14 | config.TRAIN.beta1 = 0.9 15 | 16 | # learning rate 17 | config.TRAIN.n_epoch = 10000 18 | config.TRAIN.n_epoch_init = 10 19 | config.TRAIN.lr_decay = 0.8 20 | config.TRAIN.decay_every = 20 21 | 22 | ## adversarial loss coefficient 23 | config.TRAIN.lambda_adv = 1e-3 24 | 25 | ## discriminator lr coefficient 26 | config.TRAIN.lambda_lr_d = 1 27 | 28 | ## binary loss coefficient 29 | config.TRAIN.lambda_binary = 2e-2 30 | 31 | ## perceptual loss coefficient 32 | config.TRAIN.lambda_perceptual = 1e-4 33 | 34 | ### TRAIN DATSET PATH 35 | data_offset = './datasets/' 36 | #data_offset = '/data1/junyonglee/defocus_map_estimation/DMENet/' 37 | config.TRAIN.synthetic_img_path = os.path.join(data_offset, 'train/SYNDOF/image/') 38 | config.TRAIN.defocus_map_path = os.path.join(data_offset, 'train/SYNDOF/blur_map/') 39 | config.TRAIN.defocus_map_norm_path = os.path.join(data_offset, 'train/SYNDOF/blur_map_norm/') 40 | config.TRAIN.synthetic_binary_map_path = os.path.join(data_offset, 'train/SYNDOF/blur_map_binary/') 41 | # Real 42 | config.TRAIN.real_img_path = os.path.join(data_offset, 'train/CUHK/image/') 43 | config.TRAIN.real_binary_map_path = os.path.join(data_offset, 'train/CUHK/gt/') 44 | config.TRAIN.real_img_no_label_path = os.path.join(data_offset, 'train/Flickr/') 45 | 46 | ### TEST DATSET PATH 47 | config.TEST.cuhk_img_path = os.path.join(data_offset, 'test/CUHK/image/') 48 | config.TEST.cuhk_binary_map_path = os.path.join(data_offset, 'test/CUHK/gt/') 49 | config.TEST.SYNDOF_img_path = os.path.join(data_offset, 'test/SYNDOF/image/') 50 | config.TEST.SYNDOF_gt_map_path = os.path.join(data_offset, 'test/SYNDOF/gt/') 51 | config.TEST.RTF0_img_path = os.path.join(data_offset, 'test/RTF/image/0/') 52 | config.TEST.RTF0_gt_map_path = os.path.join(data_offset, 'test/RTF/gt/0/') 53 | config.TEST.RTF1_img_path = os.path.join(data_offset, 'test/RTF/image/1/') 54 | config.TEST.RTF1_gt_map_path = os.path.join(data_offset, 'test/RTF/gt/1/') 55 | config.TEST.RTF1_6_img_path = os.path.join(data_offset, 'test/RTF/image/1.6/') 56 | config.TEST.RTF1_6_gt_map_path = os.path.join(data_offset, 'test/RTF/gt/1.6/') 57 | config.TEST.random_img_path = os.path.join(data_offset, 'test/random/') 58 | 59 | 60 | ## train image size 61 | config.TRAIN.height = 240 62 | config.TRAIN.width = 240 63 | 64 | ## log & checkpoint & samples 65 | # every global step 66 | config.TRAIN.write_log_every = 100 67 | config.TRAIN.write_ckpt_every = 1 68 | config.TRAIN.write_sample_every = 1000 69 | # every epoch 70 | config.TRAIN.refresh_image_log_every = 20 71 | 72 | # save dir 73 | config.root_offset = './logs/' 74 | #config.root_offset = '/Jarvis/logs/junyonglee' 75 | config.TRAIN.root_dir = os.path.join(config.root_offset, 'DMENet_CVPR2019/') 76 | 77 | config.TRAIN.max_coc = 15.; 78 | 79 | def log_config(path, cfg): 80 | with open(path + '/config.txt', 'w') as f: 81 | f.write('================================================\n') 82 | f.write(json.dumps(cfg, indent=4)) 83 | f.write('\n================================================\n') 84 | 85 | def get_eval_path(test_set, cfg): 86 | if test_set == 'CUHK': 87 | # return cfg.TEST.cuhk_img_path, cfg.TEST.cuhk_binary_map_path 88 | return cfg.TEST.cuhk_img_path, None 89 | elif test_set == 'SYNDOF': 90 | return cfg.TEST.SYNDOF_img_path, cfg.TEST.SYNDOF_gt_map_path 91 | elif test_set == 'RTF0': 92 | return cfg.TEST.RTF0_img_path, cfg.TEST.RTF0_gt_map_path 93 | elif test_set == 'RTF1': 94 | return cfg.TEST.RTF1_img_path, cfg.TEST.RTF1_gt_map_path 95 | elif test_set == 'RTF1_6': 96 | return cfg.TEST.RTF1_6_img_path, cfg.TEST.RTF1_6_gt_map_path 97 | elif test_set == 'random': 98 | return cfg.TEST.random_img_path, None 99 | -------------------------------------------------------------------------------- /deconvolution/DMENet_fast_deconv.m: -------------------------------------------------------------------------------- 1 | function [deconved, est_time] = fast_deconvolution(image, defocus_map, lambda, is_gpu) 2 | % Test the fast deconvolution method presented in the paper 3 | % D. Krishnan, R. Fergus: "Fast Image Deconvolution using Hyper-Laplacian 4 | % Priors", Proceedings of NIPS 2009. 5 | 6 | %% parameter values; other values such as the continuation regime of the parameter beta should be changed in fast_deconv.m 7 | alpha = 1.5; 8 | 9 | 10 | %% my params 11 | g_size = 101; 12 | 13 | %% deconv start 14 | 15 | unique_sigma = unique(defocus_map); 16 | 17 | g_center = (g_size + 1) / 2.; 18 | 19 | output = zeros(size(image)); 20 | if is_gpu 21 | output = gpuArray(output); 22 | end 23 | tic; 24 | parfor (c = 1:3) 25 | % for c = 1:3 26 | 27 | image_temp = image(:, :, c); 28 | output_temp = ones(size(image_temp)); 29 | if is_gpu 30 | output_temp = gpuArray(output_temp); 31 | end 32 | 33 | for j = 1:length(unique_sigma) 34 | % disp(sprintf('I[%02d/%02d], C[%d/%d], U[%03d/%03d]', i, length(image_file_paths), c, 3, j, length(unique_sigma))); 35 | s = unique_sigma(j); 36 | sigma = s; 37 | if s ~= 0 38 | G = fspecial('gaussian',[g_size, g_size], sigma); 39 | else 40 | G = zeros(g_size, g_size); 41 | G(g_center, g_center) = 1.0; 42 | end 43 | is_identity = G(g_center - 1:g_center+1, g_center - 1:g_center+1); 44 | is_identity(2, 2) = 0; 45 | is_identity = sum(is_identity(:)) == 0; 46 | 47 | if is_identity == false 48 | G_idx = find(G > 0); 49 | [y_G,x_G] = ind2sub(size(G),G_idx); 50 | kernel = G(min(y_G):max(y_G), min(x_G):max(x_G)); 51 | ks = floor((size(kernel, 1) - 1)/2); 52 | 53 | image_pad = padarray(image_temp, [1 1]*ks, 'replicate', 'both'); 54 | 55 | logical_G = logical(G > 0); 56 | if sum(logical_G(:)) > 1 57 | for a=1:4 58 | image_pad = edgetaper(image_pad, kernel); 59 | end 60 | end 61 | if is_gpu 62 | image_pad = gpuArray(image_pad); 63 | end 64 | 65 | % fast_deconv 66 | [x] = fast_deconv(image_pad, kernel, lambda, alpha); 67 | 68 | x = x(ks+1:end-ks, ks+1:end-ks); 69 | else 70 | x = image_temp; 71 | end 72 | 73 | output_temp(logical(defocus_map == s)) = x(logical(defocus_map == s)); 74 | end 75 | output(:, :, c) = output_temp; 76 | end 77 | est_time = toc(); 78 | 79 | output(logical(output > 1)) = 1; 80 | output(logical(output < 0)) = 0; 81 | if is_gpu 82 | output = gather(output); 83 | end 84 | deconved = output; 85 | 86 | -------------------------------------------------------------------------------- /deconvolution/dir2.m: -------------------------------------------------------------------------------- 1 | function full_path = dir2(varargin) 2 | if nargin == 0 3 | name = '.'; 4 | elseif nargin == 1 5 | name = varargin{1}; 6 | else 7 | error('Too many input arguments.') 8 | end 9 | 10 | listing = dir(name); 11 | 12 | inds = []; 13 | n = 0; 14 | k = 1; 15 | 16 | while k <= length(listing) 17 | if listing(k).isdir 18 | inds(end + 1) = k; 19 | end 20 | k = k + 1; 21 | end 22 | listing(inds) = []; 23 | 24 | full_path = []; 25 | for k = 1:length(listing) 26 | file_path = listing(k).folder; 27 | file_name = listing(k).name; 28 | full_path = [full_path, string(fullfile(file_path, file_name))]; 29 | end 30 | full_path = sort(full_path); 31 | 32 | end 33 | -------------------------------------------------------------------------------- /deconvolution/fast_deconv.m: -------------------------------------------------------------------------------- 1 | function [yout] = fast_deconv(yin, k, lambda, alpha, yout0) 2 | % 3 | % 4 | % fast_deconv solves the deconvolution problem in the paper (see Equation (1)) 5 | % D. Krishnan, R. Fergus: "Fast Image Deconvolution using Hyper-Laplacian 6 | % Priors", Proceedings of NIPS 2009. 7 | % 8 | % This paper and the code are related to the work and code of Wang 9 | % et. al.: 10 | % 11 | % Y. Wang, J. Yang, W. Yin and Y. Zhang, "A New Alternating Minimization 12 | % Algorithm for Total Variation Image Reconstruction", SIAM Journal on 13 | % Imaging Sciences, 1(3): 248:272, 2008. 14 | % and their FTVd code. 15 | 16 | % Input Parameters: 17 | % 18 | % yin: Observed blurry and noisy input grayscale image. 19 | % k: convolution kernel 20 | % lambda: parameter that balances likelihood and prior term weighting 21 | % alpha: parameter between 0 and 2 22 | % yout0: if this is passed in, it is used as an initialization for the 23 | % output deblurred image; if not passed in, then the input blurry image 24 | % is used as the initialization 25 | % 26 | % 27 | % Outputs: 28 | % yout: solution 29 | % 30 | % Note: for faster LUT interpolation, please download and install 31 | % matlabPyrTools of Eero Simoncelli from 32 | % www.cns.nyu.edu/~lcv/software.php. The specific MeX function required 33 | % is pointOp (used in solve_image.m). 34 | % 35 | % Copyright (C) 2009. Dilip Krishnan and Rob Fergus 36 | % Email: dilip,fergus@cs.nyu.edu 37 | 38 | % continuation parameters 39 | beta = 1; 40 | beta_rate = 2*sqrt(2); 41 | beta_max = 2^8; 42 | 43 | % number of inner iterations per outer iteration 44 | mit_inn = 1; 45 | 46 | [m n] = size(yin); 47 | % initialize with input or passed in initialization 48 | if (nargin == 5) 49 | yout = yout0; 50 | else 51 | yout = yin; 52 | end; 53 | 54 | % make sure k is a odd-sized 55 | if ((mod(size(k, 1), 2) ~= 1) | (mod(size(k, 2), 2) ~= 1)) 56 | fprintf('Error - blur kernel k must be odd-sized.\n'); 57 | return; 58 | end; 59 | ks = floor((size(k, 1)-1)/2); 60 | 61 | % compute constant quantities 62 | % see Eqn. (3) of paper 63 | [Nomin1, Denom1, Denom2] = computeDenominator(yin, k); 64 | 65 | % x and y gradients of yout (with circular boundary conditions) 66 | % other gradient filters may be used here and their transpose will then need to 67 | % be used within the inner loop (see comment below) and in the function 68 | % computeDenominator 69 | youtx = [diff(yout, 1, 2), yout(:,1) - yout(:,n)]; 70 | youty = [diff(yout, 1, 1); yout(1,:) - yout(m,:)]; 71 | 72 | % store some of the statistics 73 | costfun = []; 74 | Outiter = 0; 75 | 76 | %% Main loop 77 | while beta < beta_max 78 | Outiter = Outiter + 1; 79 | %fprintf('Outer iteration %d; beta %.3g\n',Outiter, beta); 80 | 81 | gamma = beta/lambda; 82 | Denom = Denom1 + gamma*Denom2; 83 | Inniter = 0; 84 | 85 | for Inniter = 1:mit_inn 86 | 87 | if (0) 88 | %%% Compute cost function - uncomment to see the original 89 | % minimization function costs at every iteration 90 | youtk = conv2(yout, k, 'same'); 91 | % likelihood term 92 | lh = sum(sum((youtk - yin).^2 )); 93 | 94 | if (alpha == 1) 95 | cost = (lambda/2)*lh + sum(abs(youtx(:))) + sum(abs(youty(:))); 96 | else 97 | cost = (lambda/2)*lh + sum(abs(youtx(:)).^alpha) + sum(abs(youty(:)).^alpha); 98 | end; 99 | %fprintf('Inniter iteration %d; cost %.3g\n', Inniter, cost); 100 | 101 | costfun = [costfun, cost]; 102 | end; 103 | % 104 | % w-subproblem: eqn (5) of paper 105 | % 106 | Wx = solve_image(youtx, beta, alpha); 107 | Wy = solve_image(youty, beta, alpha); 108 | 109 | % 110 | % x-subproblem: eqn (3) of paper 111 | % 112 | % The transpose of x and y gradients; if other gradient filters 113 | % (such as higher-order filters) are to be used, then add them 114 | % below the comment above as well 115 | 116 | Wxx = [Wx(:,n) - Wx(:, 1), -diff(Wx,1,2)]; 117 | Wxx = Wxx + [Wy(m,:) - Wy(1, :); -diff(Wy,1,1)]; 118 | 119 | Fyout = (Nomin1 + gamma*fft2(Wxx))./Denom; 120 | yout = real(ifft2(Fyout)); 121 | 122 | % update the gradient terms with new solution 123 | youtx = [diff(yout, 1, 2), yout(:,1) - yout(:,n)]; 124 | youty = [diff(yout, 1, 1); yout(1,:) - yout(m,:)]; 125 | 126 | end %inner 127 | beta = beta*beta_rate; 128 | end %Outer 129 | 130 | 131 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 132 | function [Nomin1, Denom1, Denom2] = computeDenominator(y, k) 133 | % 134 | % computes denominator and part of the numerator for Equation (3) of the 135 | % paper 136 | % 137 | % Inputs: 138 | % y: blurry and noisy input 139 | % k: convolution kernel 140 | % 141 | % Outputs: 142 | % Nomin1 -- F(K)'*F(y) 143 | % Denom1 -- |F(K)|.^2 144 | % Denom2 -- |F(D^1)|.^2 + |F(D^2)|.^2 145 | % 146 | 147 | sizey = size(y); 148 | otfk = psf2otf(k, sizey); 149 | Nomin1 = conj(otfk).*fft2(y); 150 | Denom1 = abs(otfk).^2; 151 | % if higher-order filters are used, they must be added here too 152 | Denom2 = abs(psf2otf([1,-1],sizey)).^2 + abs(psf2otf([1;-1],sizey)).^2; 153 | -------------------------------------------------------------------------------- /deconvolution/readme.md: -------------------------------------------------------------------------------- 1 | # Deconvolution using defocus map estimated from DMENet 2 | * *This code is based on "[Fast Image Deconvolution using Hyper-Laplacian Priors](https://papers.nips.cc/paper/2009/file/3dd48ab31d016ffcbf3314df2b3cb9ce-Paper.pdf)", Krishnan *et al.*, In Proc. NIPS 2009.
Refer [here](https://dilipkay.wordpress.com/fast-deconvolution/) for the original code.* 3 | 4 | ## Getting Started 5 | 1. Place your dataset as: 6 | 7 | ``` 8 | ... 9 | ├── deconvolution 10 | │ ├── source 11 | │ │ ├── input 12 | │ │ │ ├── [DATASET] # the name of a dataset [`CUHK` | `DPDD` | `RealDOF`] 13 | │ │ │ │ ├── *.[jpg|png] # input images 14 | │ │ ├── defocus map 15 | │ │ │ ├── [DATASET] # the name of the dataset that DMENet ran on 16 | │ │ │ │ ├── *.[jpg|png] # defocus maps (results of DMENet in `[LOG_ROOT]/[mode]/result/[test_set]/defocus_map`) 17 | ... 18 | ``` 19 | 20 | > **Note:** 21 | > 22 | > * For the DPDD dataset, refer [here](https://www.eecs.yorku.ca/~abuolaim/eccv_2020_dp_defocus_deblurring/dataset.html). 23 | > * The RealDOF test set is the test set that we used for the defocus deblurring paper, which is provisionally accepted to CVPR2021. We will release the test set soon. 24 | 25 | 2. In the matlab console, type following for the evaluation. 26 | 27 | ``` 28 | >> run_DMENet_deconv([DATASET], is_gpu, gpu_num) 29 | 30 | # gpu example 31 | >> run_DMENet_deconv('CUHK', true, 1) 32 | 33 | # cpu example 34 | >> run_DMENet_deconv('CUHK') 35 | ``` 36 | 37 | * Parameters 38 | * [DATASET]: the name of a dataset. `CUHK` | `DPDD` | `RealDOF`. 39 | * is_gpu: whether to use gpu. `true` | `false`. Default: `false` 40 | * gpu_num: the device number of a gpu. 41 | 42 | * Results will be saved as: 43 | 44 | ``` 45 | ... 46 | ├── deconvolution 47 | ... 48 | │ ├── output 49 | │ │ ├── [DATASET] # the name of the dataset used for deconvolution 50 | │ │ │ ├── *.[jpg|png] # resulting deconvolution images 51 | ``` 52 | -------------------------------------------------------------------------------- /deconvolution/run_DMENet_deconv.m: -------------------------------------------------------------------------------- 1 | function run_DMENet_deconv(dataset, is_gpu, gpu_num) 2 | % dataset = CUHK | DPDD | RealDOF 3 | if nargin == 1 4 | is_gpu = false; 5 | gpu_num = 0; 6 | elseif nargin == 2 7 | gpu_num = 1; 8 | end 9 | 10 | g = 0; 11 | if is_gpu 12 | g = gpuDevice(gpu_num); 13 | end 14 | 15 | %% directory 16 | offset = './sources'; 17 | image_file_paths = dir2(fullfile(offset, 'input', dataset)); 18 | defocus_file_paths = dir2(fullfile(offset, 'defocus_map', dataset)); 19 | out_offset = fullfile('output', dataset); 20 | 21 | % remove output directory before begin 22 | if isdir(out_offset) 23 | rmdir(out_offset, 's'); 24 | end 25 | mkdir(out_offset) 26 | 27 | %% deconv parameter 28 | if contains(dataset, 'CUHK') 29 | % for the CUHK dataset 30 | lambda = 420; 31 | elseif contains(dataset, 'DPDD') 32 | % for the DPDD dataset 33 | lambda = 16.8; 34 | elseif contains(dataset, 'RealDOF') 35 | % for the RealDOF dataset 36 | lambda = 4.2; 37 | end 38 | 39 | % my parameter 40 | bin_num = 32; % bin_number 41 | 42 | %% deconv start 43 | est_time_mean = 0; 44 | for i = 1:length(image_file_paths) 45 | % read images 46 | input = read_img(image_file_paths(i)); 47 | 48 | %%%% Read defocus map and make it to sigma map 49 | %%% This is for defocus map result of DMENet. For the results of other 50 | %%% methods, modify them to have proper standard deviation value for 51 | %%% creating spatially varying Gaussian kernels. 52 | defocus_map = double(imread(char(defocus_file_paths(i))))./255.0; 53 | % DMENET 54 | defocus_map = (defocus_map * 15 - 1)/2; 55 | defocus_map(defocus_map < 0) = 0; 56 | % EBDB 57 | % defocus_map = defocus_map * 5; 58 | % JNB 59 | % defocus_map = defocus_map * 4; 60 | %%%% 61 | 62 | % make sure to have the same resolution 63 | [input, defocus_map] = refine_img(input, defocus_map); 64 | 65 | %%% quantize (for all compared methods, results are almost the same even without the qunatization when bin_num is more than 32) 66 | unique_sigma = unique(defocus_map); 67 | w_edges = quantile(unique_sigma, bin_num); % weighted edges 68 | w_edges = [min(unique_sigma), w_edges]; 69 | w_edges = [w_edges, max(unique_sigma)]; 70 | defocus_map_index = discretize(defocus_map, w_edges); 71 | defocus_map = w_edges(defocus_map_index); 72 | unique_sigma = unique(defocus_map); 73 | 74 | 75 | %%% deconvolution start 76 | [deconv_result, est_time] = DMENet_fast_deconv(input, defocus_map, lambda, is_gpu); 77 | if is_gpu 78 | reset(g); 79 | end 80 | %%% 81 | 82 | disp(sprintf('[%02d/%02d] (%.3f sec)', i, length(image_file_paths), est_time)); 83 | est_time_mean = est_time_mean + est_time; 84 | 85 | imwrite(uint8(deconv_result*255), fullfile(out_offset, sprintf('%02d.png', i))); 86 | end 87 | 88 | est_time_mean = est_time_mean / length(image_file_paths); 89 | disp(sprintf('Deconvolution done for %s dataset (%.3f sec)', dataset, est_time_mean)); 90 | end 91 | 92 | %% 93 | function image = read_img(path) 94 | image = imread(char(path)); 95 | image = im2double(image); 96 | image = double(uint8(image * 255)) / 255; 97 | end 98 | 99 | function [in1, in2] = refine_img(in1, in2) 100 | sz_in1 = size(in1); 101 | sz_in2 = size(in2); 102 | 103 | in1 = in1(1:min(sz_in1(1), sz_in2(1)), 1:min(sz_in1(2), sz_in2(2)), :); 104 | in2 = in2(1:min(sz_in1(1), sz_in2(1)), 1:min(sz_in1(2), sz_in2(2)), :); 105 | end 106 | -------------------------------------------------------------------------------- /deconvolution/solve_image.m: -------------------------------------------------------------------------------- 1 | function [w] = solve_image(v, beta, alpha) 2 | 3 | % 4 | % solve the following component-wise separable problem 5 | % min |w|^\alpha + \frac{\beta}{2} (w - v).^2 6 | % 7 | % A LUT is used to solve the problem; when the function is first called 8 | % for a new value of beta or alpha, a LUT is built for that beta/alpha 9 | % combination and for a range of values of v. The LUT stays persistent 10 | % between calls to solve_image. It will be recomputed the first time this 11 | % function is called. 12 | 13 | % range of input data and step size; increasing the range of decreasing 14 | % the step size will increase accuracy but also increase the size of the 15 | % LUT 16 | range = 10; 17 | step = 0.0001; 18 | 19 | persistent lookup_v known_beta xx known_alpha 20 | ind = find(known_beta==beta & known_alpha==alpha); 21 | if isempty(known_beta | known_alpha) 22 | xx = [-range:step:range]; 23 | end 24 | if any(ind) 25 | %fprintf('Reusing lookup table for beta %.3g and alpha %.3g\n', beta, alpha); 26 | %%% already computed 27 | if (exist('pointOp') == 3) 28 | % Use Eero Simoncelli's function to extrapolate 29 | w = pointOp(double(v),lookup_v(ind,:), -range, step, 0); 30 | else 31 | w = interp1(xx', lookup_v(ind,:)', v(:), 'linear', 'extrap'); 32 | w = reshape(w, size(v,1), size(v,2)); 33 | end; 34 | else 35 | %%% now go and recompute xx for new value of beta and alpha 36 | tmp = compute_w(xx, beta, alpha); 37 | lookup_v = [lookup_v; tmp(:)']; 38 | known_beta = [known_beta, beta]; 39 | known_alpha = [known_alpha, alpha]; 40 | 41 | %%% and lookup current v's in the new lookup table row. 42 | if (exist('pointOp') == 3) 43 | % Use Eero Simoncelli's function to extrapolate 44 | w = pointOp(double(v),lookup_v(end,:), -range, step, 0); 45 | else 46 | w = interp1(xx', lookup_v(end,:)', v(:), 'linear', 'extrap'); 47 | w = reshape(w, size(v,1), size(v,2)); 48 | end; 49 | 50 | %fprintf('Recomputing lookup table for new value of beta %.3g and alpha %.3g\n', beta, alpha); 51 | end 52 | 53 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 54 | % 55 | % call different functions to solve the minimization problem 56 | % min |w|^\alpha + \frac{\beta}{2} (w - v).^2 for a fixed beta and alpha 57 | % 58 | function w = compute_w(v, beta, alpha) 59 | 60 | if (abs(alpha - 1) < 1e-9) 61 | % assume alpha = 1.0 62 | w = compute_w1(v, beta); 63 | return; 64 | end; 65 | 66 | if (abs(alpha - 2/3) < 1e-9) 67 | % assume alpha = 2/3 68 | w = compute_w23(v, beta); 69 | return; 70 | end; 71 | 72 | if (abs(alpha - 1/2) < 1e-9) 73 | % assume alpha = 1/2 74 | w = compute_w12(v, beta); 75 | return; 76 | end; 77 | 78 | % for any other value of alpha, plug in some other generic root-finder 79 | % here, we use Newton-Raphson 80 | w = newton_w(v, beta, alpha); 81 | 82 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 83 | function w = compute_w23(v, beta) 84 | % solve a quartic equation 85 | % for alpha = 2/3 86 | 87 | epsilon = 1e-6; %% tolerance on imag part of real root 88 | 89 | k = 8/(27*beta^3); 90 | m = ones(size(v))*k; 91 | 92 | % Now use formula from 93 | % http://en.wikipedia.org/wiki/Quartic_equation (Ferrari's method) 94 | % running our coefficients through Mathmetica (quartic_solution.nb) 95 | % optimized to use as few operations as possible... 96 | 97 | %%% precompute certain terms 98 | v2 = v .* v; 99 | v3 = v2 .* v; 100 | v4 = v3 .* v; 101 | m2 = m .* m; 102 | m3 = m2 .* m; 103 | 104 | %% Compute alpha & beta 105 | alpha = -1.125*v2; 106 | beta2 = 0.25*v3; 107 | 108 | %%% Compute p,q,r and u directly. 109 | q = -0.125*(m.*v2); 110 | r1 = -q/2 + sqrt(-m3/27 + (m2.*v4)/256); 111 | 112 | u = exp(log(r1)/3); 113 | y = 2*(-5/18*alpha + u + (m./(3*u))); 114 | 115 | W = sqrt(alpha./3 + y); 116 | 117 | %%% now form all 4 roots 118 | root = zeros(size(v,1),size(v,2),4); 119 | root(:,:,1) = 0.75.*v + 0.5.*(W + sqrt(-(alpha + y + beta2./W ))); 120 | root(:,:,2) = 0.75.*v + 0.5.*(W - sqrt(-(alpha + y + beta2./W ))); 121 | root(:,:,3) = 0.75.*v + 0.5.*(-W + sqrt(-(alpha + y - beta2./W ))); 122 | root(:,:,4) = 0.75.*v + 0.5.*(-W - sqrt(-(alpha + y - beta2./W ))); 123 | 124 | 125 | %%%%%% Now pick the correct root, including zero option. 126 | 127 | %%% Clever fast approach that avoids lookups 128 | v2 = repmat(v,[1 1 4]); 129 | sv2 = sign(v2); 130 | rsv2 = real(root).*sv2; 131 | 132 | %%% condensed fast version 133 | %%% take out imaginary roots above v/2 but below v 134 | root_flag3 = sort(((abs(imag(root))(abs(v2)/2)) & ((rsv2)<(abs(v2)))).*rsv2,3,'descend').*sv2; 135 | %%% take best 136 | w=root_flag3(:,:,1); 137 | 138 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 139 | function w = compute_w12(v, beta) 140 | % solve a cubic equation 141 | % for alpha = 1/2 142 | 143 | epsilon = 1e-6; %% tolerance on imag part of real root 144 | 145 | k = -0.25/beta^2; 146 | m = ones(size(v))*k.*sign(v); 147 | 148 | %%%%%%%%%%%%%%%%%%%%%%%%%%% Compute the roots (all 3) 149 | t1 = (2/3)*v; 150 | 151 | v2 = v .* v; 152 | v3 = v2 .* v; 153 | 154 | %%% slow (50% of time), not clear how to speed up... 155 | t2 = exp(log(-27*m - 2*v3 + (3*sqrt(3))*sqrt(27*m.^2 + 4*m.*v3))/3); 156 | 157 | t3 = v2./t2; 158 | 159 | %%% find all 3 roots 160 | root = zeros(size(v,1),size(v,2),3); 161 | root(:,:,1) = t1 + (2^(1/3))/3*t3 + (t2/(3*2^(1/3))); 162 | root(:,:,2) = t1 - ((1+i*sqrt(3))/(3*2^(2/3)))*t3 - ((1-i*sqrt(3))/(6*2^(1/3)))*t2; 163 | root(:,:,3) = t1 - ((1-i*sqrt(3))/(3*2^(2/3)))*t3 - ((1+i*sqrt(3))/(6*2^(1/3)))*t2; 164 | 165 | root(find(isnan(root) | isinf(root))) = 0; %%% catch 0/0 case 166 | 167 | %%%%%%%%%%%%%%%%%%%%%%%%%%%% Pick the right root 168 | %%% Clever fast approach that avoids lookups 169 | v2 = repmat(v,[1 1 3]); 170 | sv2 = sign(v2); 171 | rsv2 = real(root).*sv2; 172 | root_flag3 = sort(((abs(imag(root))(2*abs(v2)/3)) & ((rsv2)<(abs(v2)))).*rsv2,3,'descend').*sv2; 173 | %%% take best 174 | w=root_flag3(:,:,1); 175 | 176 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 177 | function w = compute_w1(v, beta) 178 | % solve a simple max problem for alpha = 1 179 | 180 | w = max(abs(v) - 1/beta, 0).*sign(v); 181 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 182 | function w = newton_w(v, beta, alpha) 183 | 184 | % for a general alpha, use Newton-Raphson; more accurate root-finders may 185 | % be substituted here; we are finding the roots of the equation: 186 | % \alpha*|w|^{\alpha - 1} + \beta*(v - w) = 0 187 | 188 | iterations = 4; 189 | 190 | x = v; 191 | 192 | for a=1:iterations 193 | fd = (alpha)*sign(x).*abs(x).^(alpha-1)+beta*(x-v); 194 | fdd = alpha*(alpha-1)*abs(x).^(alpha-2)+beta; 195 | 196 | x = x - fd./fdd; 197 | end; 198 | 199 | q = find(isnan(x)); 200 | x(q) = 0; 201 | 202 | % check whether the zero solution is the better one 203 | z = beta/2*v.^2; 204 | f = abs(x).^alpha + beta/2*(x-v).^2; 205 | w = (f 3.275) = 3.275; 51 | out = out / 3.275; 52 | gt = gt / 3.275; 53 | end 54 | 55 | out_shape = size(out); 56 | gt_shape = size(gt); 57 | new_shape = [min(out_shape(1), gt_shape(1)), min(out_shape(2),gt_shape(2))]; 58 | 59 | gt = gt(1:new_shape(1), 1:new_shape(2)); 60 | out = out(1:new_shape(1), 1:new_shape(2)); 61 | 62 | % compute MSE 63 | % MSE_out = immse(gt, out); 64 | MSE_out = ((gt - out).^2); 65 | MSE_out = mean(MSE_out(:)); 66 | mse_list = [mse_list; MSE_out]; 67 | mse_out_avg = mse_out_avg + MSE_out; 68 | 69 | % compute MAE 70 | MAE_out = abs(gt - out); 71 | MAE_out = mean(MAE_out(:)); 72 | mae_list = [mae_list; MAE_out]; 73 | mae_out_avg = mae_out_avg + MAE_out; 74 | 75 | end 76 | mse_out_avg = mse_out_avg / file_num; 77 | mae_out_avg = mae_out_avg / file_num; 78 | 79 | %disp(['[', method, '] ', 'MAE: ', num2str(mae_out_avg), ' MSE: ', num2str(mse_out_avg)]); 80 | end 81 | -------------------------------------------------------------------------------- /evaluation/RTF/readme.md: -------------------------------------------------------------------------------- 1 | ## Getting Started 2 | 1. Download and unzip [ground-truths of the RTF dataset and corresponding results of our method](https://www.dropbox.com/s/ph9pvj5g53vea6h/RTF_our_results_gt.zip?dl=1) under where the evaluation code is: 3 | 4 | ``` 5 | ... 6 | ├── evaluation_RTF 7 | │ ├── RTF 8 | │ │ ├── gt 9 | │ │ ├── out 10 | │ │ │ ├── BDCS 11 | │ │ ├── *.m 12 | │ │ ├── ... 13 | ``` 14 | 15 | * Images in the `out` directory is [`defocus_map`](https://github.com/codeslake/DMENet/blob/master/main.py#L481), which is the direct output of the network. 16 | 17 | > **Note:** 18 | > 19 | > Here is [the original zip file](https://www.dropbox.com/s/f2bkay9xykgmouc/Defocus_Blur_Dataset.zip?dl=1) of the RTF dataset provided by the author. 20 | 21 | 2. Type `run_quantitative_RTF` in the matlab console for the evaluation. 22 | * For evaluating the methods in Table 2 in the main paper, 23 | * Except [4], all defocus map results are converted to Gaussian PSF (which have the maximum standard deviation=3.275), using the code provided by [4]. 24 | * For [40], we set `maxBlur` in their code as 3.275 (which was originally 3). 25 | * For [30], we computed standard deviations using Eq. (4) in their paper, then clipped the results to have the maximum value 3.275. 26 | * For [24], we clipped ground-truths to have the maximum value 2.0 (according to their paper). 27 | * For [13], we clipped their results to have the maximum value 3.275 (the results have values of maximum 5.0). 28 | * For Ours, we compute standard deviation maps (*i.e.*, `(out * 15) - 1) / 2`) and clipped them to have values between 0 and 3.275 ([`evaluation/RTF/quantitative_RTF.m`](/evaluation/RTF/quantitative_RTF.m#L45-L53)). 29 | -------------------------------------------------------------------------------- /evaluation/RTF/run_quantitative_RTF.m: -------------------------------------------------------------------------------- 1 | clear all; 2 | close all; 3 | datasets = ["BDCS"]; 4 | noises = ["0", "1", "1.6"]; 5 | 6 | mse_list_total = []; 7 | mse_avg_total = []; 8 | mae_list_total = []; 9 | mae_avg_total = []; 10 | psnr_list_total = []; 11 | psnr_avg_total = []; 12 | ssim_list_total = []; 13 | ssim_avg_total = []; 14 | for i = 1:length(noises) 15 | mse_avg_temp = []; 16 | mae_avg_temp = []; 17 | psnr_avg_temp = []; 18 | ssim_avg_temp = []; 19 | for j = 1:length(datasets) 20 | [mse_list, mse_avg, mae_list, mae_avg] = quantitative_RTF(char(datasets(j)), char(noises(i))); 21 | 22 | if strcmp(noises(i), '0') 23 | mse_list_total = [mse_list_total, mse_list]; 24 | mae_list_total = [mae_list_total, mae_list]; 25 | end 26 | mse_avg_temp = [mse_avg_temp, mse_avg]; 27 | mae_avg_temp = [mae_avg_temp, mae_avg]; 28 | end 29 | mse_avg_total = [mse_avg_total; mse_avg_temp]; 30 | mae_avg_total = [mae_avg_total; mae_avg_temp]; 31 | end 32 | 33 | mae_list_total 34 | 35 | disp(datasets) 36 | disp("MSE (top to bottom: 0, 1, 1.6)") 37 | disp(mse_avg_total) 38 | disp("MAE (top to bottom: 0, 1, 1.6)") 39 | disp(mae_avg_total) 40 | 41 | -------------------------------------------------------------------------------- /evaluation/readme.md: -------------------------------------------------------------------------------- 1 | # Updates on Performance of DMENet 2 | *All results are measured in matlab.* 3 | 4 | * Accuracy (Figure 2 in the main paper) 5 | * **0.8783** 6 | 7 | * Table 2 in the main paper (the last column) 8 | | | ... | Ours | 9 | | :-------------: | :-------------: | :-------------: | 10 | | MSE | ... | **0.009** | 11 | | MAE | ... | **0.077** | 12 | * We compute standard deviation maps (*i.e.*, `(out * 15) - 1) / 2`) and clipped them to have values between 0 and 3.275 ([`evaluation/RTF/quantitative_RTF.m`](/evaluation/RTF/quantitative_RTF.m#L45-L53)). 13 | 14 | * Table 4 in the supplementary material (the last column) 15 | | datasets | ... | DMENetBDCS | 16 | | :------: | :------: | :------: | 17 | | SYNDOF | ... | **0.013** / **0.084** | 18 | | RTF | ... | **0.009** / **0.077** | 19 | 20 | * Table 5 in the supplementary material (the last row) 21 | | | SYNDOF
MSE / MAE | RTF
MSE / MAE | CUHK
acc / mAP | 22 | | :----: | :----: | :----: | :----: | 23 | | ... | ... | ... | ... | 24 | | DMENetBDCS | 0.013 / 0.084 | **0.009** / **0.077** | 0.878 / **0.987** | 25 | 26 | * Table 6 in the supplementary material (the last column) 27 | | Image # | ... | Ours | 28 | | :-------------: | :-------------: | :-------------: | 29 | | 01 | ... | **0.0643** | 30 | | 02 | ... | **0.0406** | 31 | | 03 | ... | **0.0863** | 32 | | 04 | ... | **0.0408** | 33 | | 05 | ... | **0.0335** | 34 | | 06 | ... | 0.0756 | 35 | | 07 | ... | 0.1129 | 36 | | 08 | ... | 0.1695 | 37 | | 09 | ... | **0.0427** | 38 | | 10 | ... | **0.0771** | 39 | | 11 | ... | **0.044** | 40 | | 12 | ... | 0.1347 | 41 | | 13 | ... | **0.0817** | 42 | | 14 | ... | **0.1123** | 43 | | 15 | ... | **0.0838** | 44 | | 16 | ... | **0.0881** | 45 | | 17 | ... | **0.0675** | 46 | | 18 | ... | **0.0786** | 47 | | 19 | ... | **0.0744** | 48 | | 20 | ... | **0.0841** | 49 | | 21 | ... | **0.0397** | 50 | | 22 | ... | **0.0535** | 51 | | Avg. MSE | ... | **0.0093** | 52 | | Avg. MAE | ... | **0.0767** | 53 | | Avg. MSE (s=1.0) | ... | **0.0207** | 54 | | Avg. MAE (s=1.0) | ... | **0.1006** | 55 | | Avg. MSE (s=1.6) | ... | 0.0491 | 56 | | Avg. MAE (s=1.6) | ... | 0.1579 | 57 | -------------------------------------------------------------------------------- /install_CUDA10.0.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | conda install -y cudatoolkit=10.0 3 | conda install -y cudnn=7.6 4 | pip install --no-cache tensorflow-gpu==1.15 5 | pip install --no-cache tensorlayer==1.11.1 6 | pip install --no-cache jupyterlab 7 | pip install --no-cache -r requirements.txt 8 | #apt-get install ffmpeg libsm6 libxext6 -y # cv2 error 9 | -------------------------------------------------------------------------------- /install_CUDA11.1.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | pip install --no-cache --user nvidia-pyindex 3 | conda install -y -c conda-forge openmpi 4 | export PATH="~/.local/bin:$PATH" 5 | export LD_LIBRARY_PATH="/anaconda3/envs/DMENet_CUDA11/lib/:$LD_LIBRARY_PATH" 6 | pip install --no-cache --user 'nvidia-tensorflow[horovod]' 7 | pip install --no-cache tensorlayer==1.11.1 8 | pip install --no-cache --upgrade numpy==1.16.0 9 | pip install --no-cache --upgrade warpt==1.11.1 10 | 11 | pip install --no-cache jupyterlab 12 | pip install --no-cache -r requirements.txt 13 | #apt-get install ffmpeg libsm6 libxext6 -y # cv2 error 14 | 15 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) 3 | import tensorlayer as tl 4 | #tl.logging.set_verbosity(tl.logging.ERROR) 5 | 6 | import numpy as np 7 | from random import shuffle 8 | import matplotlib 9 | import datetime 10 | import time 11 | import shutil 12 | import os 13 | 14 | from config import config, log_config, get_eval_path 15 | from utils import * 16 | from model import * 17 | 18 | 19 | 20 | batch_size = config.TRAIN.batch_size 21 | batch_size_init = config.TRAIN.batch_size_init 22 | lr_init = config.TRAIN.lr_init 23 | lr_init_init = config.TRAIN.lr_init_init 24 | beta1 = config.TRAIN.beta1 25 | 26 | n_epoch = config.TRAIN.n_epoch 27 | n_epoch_init = config.TRAIN.n_epoch_init 28 | lr_decay = config.TRAIN.lr_decay 29 | decay_every = config.TRAIN.decay_every 30 | 31 | lambda_adv = config.TRAIN.lambda_adv 32 | lambda_lr_d = config.TRAIN.lambda_lr_d 33 | lambda_binary = config.TRAIN.lambda_binary 34 | lambda_perceptual = config.TRAIN.lambda_perceptual 35 | 36 | h = config.TRAIN.height 37 | w = config.TRAIN.width 38 | 39 | ni = int(np.ceil(np.sqrt(batch_size))) 40 | 41 | def train(): 42 | ## CREATE DIRECTORIES 43 | mode_dir = config.TRAIN.root_dir + '{}'.format(tl.global_flag['mode']) 44 | 45 | ckpt_dir = os.path.join(mode_dir, 'checkpoint') 46 | init_dir = os.path.join(mode_dir, 'init') 47 | log_dir_scalar_init = os.path.join(mode_dir, 'log/scalar_init') 48 | log_dir_image_init = os.path.join(mode_dir, 'log/image_init') 49 | log_dir_scalar = os.path.join(mode_dir, 'log/scalar') 50 | log_dir_image = os.path.join(mode_dir, 'log/image') 51 | sample_dir = os.path.join(mode_dir, 'samples/train') 52 | config_dir = os.path.join(mode_dir, 'config') 53 | 54 | if tl.global_flag['delete_log']: 55 | shutil.rmtree(ckpt_dir, ignore_errors = True) 56 | if tl.global_flag['is_pretrain']: 57 | shutil.rmtree(log_dir_scalar_init, ignore_errors = True) 58 | shutil.rmtree(log_dir_image_init, ignore_errors = True) 59 | shutil.rmtree(log_dir_scalar, ignore_errors = True) 60 | shutil.rmtree(log_dir_image, ignore_errors = True) 61 | shutil.rmtree(sample_dir, ignore_errors = True) 62 | shutil.rmtree(config_dir, ignore_errors = True) 63 | 64 | tl.files.exists_or_mkdir(ckpt_dir) 65 | tl.files.exists_or_mkdir(init_dir) 66 | tl.files.exists_or_mkdir(log_dir_scalar_init) 67 | tl.files.exists_or_mkdir(log_dir_image_init) 68 | tl.files.exists_or_mkdir(log_dir_scalar) 69 | tl.files.exists_or_mkdir(log_dir_image) 70 | tl.files.exists_or_mkdir(sample_dir) 71 | tl.files.exists_or_mkdir(config_dir) 72 | log_config(config_dir, config) 73 | 74 | ## DEFINE SESSION 75 | sess = tf.Session(config = tf.ConfigProto(allow_soft_placement = True, log_device_placement = False)) 76 | 77 | ## READ DATASET LIST 78 | # train 79 | train_real_img_list = np.array(sorted(tl.files.load_file_list(path = config.TRAIN.real_img_path, regx = '.*', printable = False))) 80 | train_real_binary_map_list = np.array(sorted(tl.files.load_file_list(path = config.TRAIN.real_binary_map_path, regx = '.*', printable = False))) 81 | train_real_img_no_label_list = np.array(sorted(tl.files.load_file_list(path = config.TRAIN.real_img_no_label_path, regx = '.*', printable = False))) 82 | 83 | # test 84 | test_blur_img_list = np.array(sorted(tl.files.load_file_list(path = config.TEST.cuhk_img_path, regx = '.*', printable = False))) 85 | test_gt_list = np.array(sorted(tl.files.load_file_list(path = config.TEST.cuhk_binary_map_path, regx = '.*', printable = False))) 86 | test_blur_imgs = read_all_imgs(test_blur_img_list, path = config.TEST.cuhk_img_path, mode = 'RGB') 87 | test_gt_imgs = read_all_imgs(test_gt_list, path = config.TEST.cuhk_binary_map_path, mode = 'GRAY') 88 | 89 | ## DEFINE MODEL 90 | # input 91 | with tf.variable_scope('input'): 92 | patches_synthetic = tf.placeholder('float32', [None, h, w, 3], name = 'input_synthetic') 93 | labels_synthetic_defocus = tf.placeholder('float32', [None, h, w, 1], name = 'labels_synthetic_defocus') 94 | 95 | patches_real = tf.placeholder('float32', [None, h, w, 3], name = 'input_real') 96 | labels_real_binary = tf.placeholder('float32', [None, h, w, 1], name = 'labels_real_binary') 97 | patches_real_no_label = tf.placeholder('float32', [None, h, w, 3], name = 'input_real_no_label') 98 | 99 | patches_real_test = tf.placeholder('float32', [None, h, w, 3], name = 'input_real') 100 | labels_real_binary_test = tf.placeholder('float32', [None, h, w, 1], name = 'labels_real_binary') 101 | 102 | # model 103 | with tf.variable_scope('main_net') as scope: 104 | with tf.variable_scope('defocus_net') as scope: 105 | with tf.variable_scope('encoder') as scope: 106 | net_vgg, feats_synthetic_down, _, _ = VGG19_down(patches_synthetic, reuse = False, scope = scope) 107 | _, feats_real_down, _, _ = VGG19_down(patches_real, reuse = True, scope = scope) 108 | _, feats_real_no_label_down, _, _ = VGG19_down(patches_real_no_label, reuse = True, scope = scope) 109 | with tf.variable_scope('decoder') as scope: 110 | output_synthetic_defocus, feats_synthetic_up_aux, feats_synthetic_da, _ = UNet_up(patches_synthetic, feats_synthetic_down, is_train = True, reuse = False, scope = scope) 111 | output_real_defocus, _, feats_real_da, _ = UNet_up(patches_real, feats_real_down, is_train = True, reuse = True, scope = scope) 112 | output_real_no_label_defocus, _, feats_real_no_label_da, _ = UNet_up(patches_real_no_label, feats_real_no_label_down, is_train = True, reuse = True, scope = scope) 113 | with tf.variable_scope('binary_net') as scope: 114 | output_real_binary_logits, output_real_binary = Binary_Net(output_real_defocus, is_train = True, reuse = False, scope = scope) 115 | 116 | with tf.variable_scope('discriminator') as scope: 117 | with tf.variable_scope('feature') as scope: 118 | d_feature_logits_synthetic, d_feature_synthetic = feature_discriminator(feats_synthetic_da, is_train = True, reuse = False, scope = scope) 119 | d_feature_logits_real, d_feature_real = feature_discriminator(feats_real_da, is_train = True, reuse = True, scope = scope) 120 | d_feature_logits_real_no_label, d_feature_real_no_label = feature_discriminator(feats_real_no_label_da, is_train = True, reuse = True, scope = scope) 121 | 122 | # fixed 123 | with tf.variable_scope('perceptual') as scope: 124 | output_synthetic_defocus_3c = tf.concat([output_synthetic_defocus, output_synthetic_defocus, output_synthetic_defocus], axis = 3) 125 | net_vgg_perceptual, _, perceptual_synthetic_out, logits_perceptual_out = VGG19_down(output_synthetic_defocus_3c, reuse = False, scope = scope) 126 | labels_synthetic_defocus_3c = tf.concat([labels_synthetic_defocus, labels_synthetic_defocus, labels_synthetic_defocus], axis = 3) 127 | _, _, perceptual_synthetic_label, logits_perceptual_label = VGG19_down(labels_synthetic_defocus_3c, reuse = True, scope = scope) 128 | 129 | # for test 130 | with tf.variable_scope('main_net') as scope: 131 | with tf.variable_scope('defocus_net') as scope: 132 | with tf.variable_scope('encoder') as scope: 133 | _, feats_real_down_test, _, _ = VGG19_down(patches_real_test, reuse = True, scope = scope) 134 | with tf.variable_scope('decoder') as scope: 135 | output_real_defocus_test, _, _, _ = UNet_up(patches_real, feats_real_down_test, is_train = True, reuse = True, scope = scope) 136 | 137 | ## DEFINE LOSS 138 | with tf.variable_scope('loss'): 139 | with tf.variable_scope('discriminator'): 140 | with tf.variable_scope('feature'): 141 | loss_synthetic_d_feature = tl.cost.sigmoid_cross_entropy(d_feature_logits_synthetic, tf.ones_like(d_feature_logits_synthetic), name = 'synthetic') 142 | loss_real_d_feature = tl.cost.sigmoid_cross_entropy(d_feature_logits_real, tf.zeros_like(d_feature_logits_real), name = 'real') 143 | loss_real_no_label_d_feature = tl.cost.sigmoid_cross_entropy(d_feature_logits_real_no_label, tf.zeros_like(d_feature_logits_real_no_label), name = 'real') 144 | loss_d_feature = tf.identity((2 * loss_synthetic_d_feature + loss_real_d_feature + loss_real_no_label_d_feature) / 2. * lambda_adv, name = 'total') 145 | 146 | loss_d = tf.identity(loss_d_feature, name = 'total') 147 | 148 | with tf.variable_scope('generator'): 149 | with tf.variable_scope('feature'): 150 | loss_real_g_feature = tl.cost.sigmoid_cross_entropy(d_feature_logits_real, tf.ones_like(d_feature_logits_real), name = 'real') 151 | loss_real_no_label_g_feature = tl.cost.sigmoid_cross_entropy(d_feature_logits_real_no_label, tf.ones_like(d_feature_logits_real_no_label), name = 'real') 152 | loss_g_feature = tf.identity((loss_real_g_feature + loss_real_no_label_g_feature) / 2., name = 'total') 153 | 154 | loss_g = tf.identity(loss_g_feature * lambda_adv, name = 'total') 155 | 156 | with tf.variable_scope('defocus'): 157 | loss_defocus = tl.cost.mean_squared_error(output_synthetic_defocus, labels_synthetic_defocus, is_mean = True, name = 'synthetic') 158 | 159 | with tf.variable_scope('auxilary'): 160 | labels_layer = InputLayer(labels_synthetic_defocus) 161 | loss_aux_1 = tl.cost.mean_squared_error(feats_synthetic_up_aux[0], 162 | DownSampling2dLayer(labels_layer, (int(h / 16), int(w / 16)), is_scale = False, method = 1, align_corners=True).outputs, is_mean = True, name = 'aux1') 163 | loss_aux_2 = tl.cost.mean_squared_error(feats_synthetic_up_aux[1], 164 | DownSampling2dLayer(labels_layer, (int(h / 8), int(w / 8)), is_scale = False, method = 1, align_corners=True).outputs, is_mean = True, name = 'aux2') 165 | loss_aux_3 = tl.cost.mean_squared_error(feats_synthetic_up_aux[2], 166 | DownSampling2dLayer(labels_layer, (int(h / 4), int(w / 4)), is_scale = False, method = 1, align_corners=True).outputs, is_mean = True, name = 'aux3') 167 | loss_aux_4 = tl.cost.mean_squared_error(feats_synthetic_up_aux[3], 168 | DownSampling2dLayer(labels_layer, (int(h / 2), int(w / 2)), is_scale = False, method = 1, align_corners=True).outputs, is_mean = True, name = 'aux4') 169 | loss_aux_5 = tl.cost.mean_squared_error(feats_synthetic_up_aux[4], labels_synthetic_defocus, is_mean = True, name = 'aux5') 170 | loss_aux = tf.identity(loss_aux_1 + loss_aux_2 + loss_aux_3 + loss_aux_4 + loss_aux_5, name = 'total') 171 | 172 | with tf.variable_scope('perceptual'): 173 | loss_synthetic_perceptual = tl.cost.mean_squared_error(perceptual_synthetic_out, perceptual_synthetic_label, is_mean = True, name = 'synthetic') 174 | loss_perceptual = tf.identity(loss_synthetic_perceptual * lambda_perceptual, name = 'total') 175 | 176 | with tf.variable_scope('binary'): 177 | loss_real_binary = tl.cost.sigmoid_cross_entropy(output_real_binary_logits, labels_real_binary, name = 'real') 178 | loss_binary = tf.identity(loss_real_binary * lambda_binary, name = 'total') 179 | 180 | loss_main = tf.identity(loss_defocus + loss_binary + loss_perceptual + loss_aux + loss_g, name = 'total') 181 | loss_init = tf.identity(loss_defocus, name = 'loss_init') 182 | 183 | ## DEFINE OPTIMIZER 184 | # variables to save / train 185 | d_vars = tl.layers.get_variables_with_name('discriminator', True, False) 186 | main_vars = tl.layers.get_variables_with_name('main_net', True, False) 187 | save_vars = tl.layers.get_variables_with_name('main_net', False, False) + tl.layers.get_variables_with_name('discriminator', False, False) 188 | 189 | init_vars = tl.layers.get_variables_with_name('defocus_net', True, False) 190 | save_init_vars = tl.layers.get_variables_with_name('defocus_net', False, False) 191 | 192 | # define optimizer 193 | with tf.variable_scope('Optimizer'): 194 | learning_rate = tf.Variable(lr_init, trainable = False) 195 | learning_rate_init = tf.Variable(lr_init_init, trainable = False) 196 | optim_d = tf.train.AdamOptimizer(learning_rate * lambda_lr_d, beta1 = beta1).minimize(loss_d, var_list = d_vars) 197 | optim_main = tf.train.AdamOptimizer(learning_rate, beta1 = beta1).minimize(loss_main, var_list = main_vars) 198 | optim_init = tf.train.AdamOptimizer(learning_rate_init, beta1 = beta1).minimize(loss_init, var_list = init_vars) 199 | 200 | ## DEFINE SUMMARY 201 | # writer 202 | writer_scalar = tf.summary.FileWriter(log_dir_scalar, sess.graph, flush_secs=30, filename_suffix = '.loss_log') 203 | writer_image = tf.summary.FileWriter(log_dir_image, sess.graph, flush_secs=30, filename_suffix = '.image_log') 204 | if tl.global_flag['is_pretrain']: 205 | writer_scalar_init = tf.summary.FileWriter(log_dir_scalar_init, sess.graph, flush_secs=30, filename_suffix = '.loss_log_init') 206 | writer_image_init = tf.summary.FileWriter(log_dir_image_init, sess.graph, flush_secs=30, filename_suffix = '.image_log_init') 207 | 208 | # for pretrain 209 | loss_sum_list_init = [] 210 | with tf.variable_scope('loss_init'): 211 | loss_sum_list_init.append(tf.summary.scalar('1_total_loss_init', loss_init)) 212 | loss_sum_list_init.append(tf.summary.scalar('2_defocus_loss_init', loss_defocus)) 213 | loss_sum_init = tf.summary.merge(loss_sum_list_init) 214 | 215 | image_sum_list_init = [] 216 | image_sum_list_init.append(tf.summary.image('1_synthetic_input_init', patches_synthetic)) 217 | image_sum_list_init.append(tf.summary.image('2_synthetic_defocus_out_init', fix_image_tf(output_synthetic_defocus, 1))) 218 | image_sum_list_init.append(tf.summary.image('3_synthetic_defocus_gt_init', fix_image_tf(labels_synthetic_defocus, 1))) 219 | image_sum_init = tf.summary.merge(image_sum_list_init) 220 | 221 | # for train 222 | loss_sum_g_list = [] 223 | with tf.variable_scope('loss_generator'): 224 | loss_sum_g_list.append(tf.summary.scalar('1_total', loss_main)) 225 | loss_sum_g_list.append(tf.summary.scalar('2_g', loss_g)) 226 | loss_sum_g_list.append(tf.summary.scalar('3_defocus', loss_defocus)) 227 | loss_sum_g_list.append(tf.summary.scalar('4_perceptual', loss_perceptual)) 228 | loss_sum_g_list.append(tf.summary.scalar('5_auxilary', loss_aux)) 229 | loss_sum_g_list.append(tf.summary.scalar('6_binary', loss_binary)) 230 | loss_sum_g = tf.summary.merge(loss_sum_g_list) 231 | 232 | loss_sum_d_list = [] 233 | with tf.variable_scope('loss_discriminator'): 234 | loss_sum_d_list.append(tf.summary.scalar('1_d', loss_d_feature)) 235 | loss_sum_d = tf.summary.merge(loss_sum_d_list) 236 | 237 | image_sum_list = [] 238 | image_sum_list.append(tf.summary.image('1_synthetic_input', patches_synthetic)) 239 | image_sum_list.append(tf.summary.image('2_synthetic_defocus_out', fix_image_tf(output_synthetic_defocus, 1))) 240 | image_sum_list.append(tf.summary.image('3_synthetic_defocus_gt', fix_image_tf(labels_synthetic_defocus, 1))) 241 | image_sum_list.append(tf.summary.image('4_real_input', patches_real)) 242 | image_sum_list.append(tf.summary.image('5_real_defocus_out', fix_image_tf(output_real_defocus, 1))) 243 | image_sum_list.append(tf.summary.image('6_real_binary_out', fix_image_tf(output_real_binary, 1))) 244 | image_sum_list.append(tf.summary.image('7_real_binary_gt', fix_image_tf(labels_real_binary, 1))) 245 | image_sum_list.append(tf.summary.image('8_real_binary_gt_no_label', patches_real_no_label)) 246 | image_sum_list.append(tf.summary.image('9_real_defocus_out_no_label', fix_image_tf(output_real_no_label_defocus, 1))) 247 | image_sum = tf.summary.merge(image_sum_list) 248 | 249 | ## INITIALIZE SESSION 250 | sess.run(tf.global_variables_initializer()) 251 | ## LOAD VGG 252 | vgg19_npy_path = "pretrained/vgg19.npy" 253 | if not os.path.isfile(vgg19_npy_path): 254 | print("Please download vgg19.npz from : https://github.com/machrisaa/tensorflow-vgg") 255 | exit() 256 | npz = np.load(vgg19_npy_path, encoding='latin1', allow_pickle=True).item() 257 | 258 | params = [] 259 | for val in sorted( npz.items() ): 260 | if val[0] == 'fc6': 261 | break; 262 | W = np.asarray(val[1][0]) 263 | b = np.asarray(val[1][1]) 264 | print(" Loading %s: %s, %s" % (val[0], W.shape, b.shape)) 265 | params.extend([W, b]) 266 | tl.files.assign_params(sess, params, net_vgg) 267 | tl.files.assign_params(sess, params, net_vgg_perceptual) 268 | 269 | init_name = init_dir + '/{}_init.npz'.format(tl.global_flag['mode']) 270 | if os.path.isfile(init_name): 271 | tl.files.load_and_assign_npz_dict(name = init_name, sess = sess) 272 | if tl.global_flag['is_pretrain']: 273 | print('*****************************************') 274 | print(' PRE-TRAINING START') 275 | print('*****************************************') 276 | global_step = 0 277 | for epoch in range(0, n_epoch_init): 278 | total_loss_init, n_iter = 0, 0 279 | # reload image list 280 | train_synthetic_img_list = np.array(sorted(tl.files.load_file_list(path = config.TRAIN.synthetic_img_path, regx = '.*', printable = False))) 281 | train_defocus_map_list = np.array(sorted(tl.files.load_file_list(path = config.TRAIN.defocus_map_path, regx = '.*', printable = False))) 282 | 283 | # shuffle datasets 284 | shuffle_index = np.arange(len(train_synthetic_img_list)) 285 | np.random.shuffle(shuffle_index) 286 | train_synthetic_img_list = train_synthetic_img_list[shuffle_index] 287 | train_defocus_map_list = train_defocus_map_list[shuffle_index] 288 | 289 | epoch_time = time.time() 290 | #for idx in range(0, len(train_synthetic_img_list), batch_size_init): 291 | for idx in range(0, 10): 292 | step_time = time.time() 293 | ## READ DATA 294 | # read synthetic data 295 | b_idx = (idx + np.arange(batch_size_init)) % len(train_synthetic_img_list) 296 | synthetic_images_blur = read_all_imgs(train_synthetic_img_list[b_idx], path = config.TRAIN.synthetic_img_path, mode = 'RGB') 297 | synthetic_defocus_maps = read_all_imgs(train_defocus_map_list[b_idx], path = config.TRAIN.defocus_map_path, mode = 'DEPTH') 298 | 299 | synthetic_images_blur, synthetic_defocus_maps = \ 300 | crop_pair_with_different_shape_images(synthetic_images_blur, synthetic_defocus_maps, [h, w], is_gaussian_noise = tl.global_flag['is_noise']) 301 | 302 | err_init, lr, _ = \ 303 | sess.run([loss_init, learning_rate_init, optim_init], {patches_synthetic: synthetic_images_blur, labels_synthetic_defocus: synthetic_defocus_maps}) 304 | 305 | print('[%s] Ep [%2d/%2d] %4d/%4d time: %4.2fs, err_init: %1.2e, lr: %1.2e' % \ 306 | (tl.global_flag['mode'], epoch, n_epoch_init, n_iter, len(train_synthetic_img_list)/batch_size_init, time.time() - step_time, err_init, lr)) 307 | 308 | if global_step % config.TRAIN.write_log_every == 0: 309 | summary_loss_init, summary_image_init = sess.run([loss_sum_init, image_sum_init], {patches_synthetic: synthetic_images_blur, labels_synthetic_defocus: synthetic_defocus_maps}) 310 | writer_scalar_init.add_summary(summary_loss_init, global_step) 311 | writer_image_init.add_summary(summary_image_init, global_step) 312 | 313 | total_loss_init += err_init 314 | n_iter += 1 315 | global_step += 1 316 | 317 | if epoch % config.TRAIN.refresh_image_log_every and epoch != n_epoch_init == 0: 318 | writer_image_init.close() 319 | remove_file_end_with(log_dir_image_init, '*.image_log') 320 | writer_image_init.reopen() 321 | 322 | if epoch % 2 or epoch == n_epoch_init - 1: 323 | tl.files.save_npz_dict(save_init_vars, name = init_dir + '/{}_init.npz'.format(tl.global_flag['mode']), sess = sess) 324 | 325 | writer_image_init.close() 326 | writer_scalar_init.close() 327 | 328 | ## START TRAINING 329 | print('*****************************************') 330 | print(' TRAINING START') 331 | print('*****************************************') 332 | global_step = 0 333 | for epoch in range(0, n_epoch + 1): 334 | total_loss, n_iter = 0, 0 335 | 336 | # reload synthetic datasets 337 | train_synthetic_img_list = np.array(sorted(tl.files.load_file_list(path = config.TRAIN.synthetic_img_path, regx = '.*', printable = False))) 338 | train_defocus_map_list = np.array(sorted(tl.files.load_file_list(path = config.TRAIN.defocus_map_path, regx = '.*', printable = False))) 339 | 340 | # shuffle datasets 341 | shuffle_index = np.arange(len(train_synthetic_img_list)) 342 | np.random.shuffle(shuffle_index) 343 | 344 | train_synthetic_img_list = train_synthetic_img_list[shuffle_index] 345 | train_defocus_map_list = train_defocus_map_list[shuffle_index] 346 | 347 | shuffle_index = np.arange(len(train_real_img_list)) 348 | np.random.shuffle(shuffle_index) 349 | train_real_img_list = train_real_img_list[shuffle_index] 350 | train_real_binary_map_list = train_real_binary_map_list[shuffle_index] 351 | 352 | shuffle_index = np.arange(len(train_real_img_no_label_list)) 353 | np.random.shuffle(shuffle_index) 354 | train_real_img_no_label_list = train_real_img_no_label_list[shuffle_index] 355 | 356 | # update learning rate 357 | if epoch != 0 and (epoch % decay_every == 0): 358 | new_lr_decay = lr_decay ** (epoch // decay_every) 359 | sess.run(tf.assign(learning_rate, lr_init * new_lr_decay)) 360 | elif epoch == 0: 361 | sess.run(tf.assign(learning_rate, lr_init)) 362 | 363 | epoch_time = time.time() 364 | for idx in range(0, len(train_synthetic_img_list), batch_size): 365 | step_time = time.time() 366 | 367 | ## READ DATA 368 | # read synthetic data 369 | b_idx = (idx + np.arange(batch_size)) % len(train_synthetic_img_list) 370 | synthetic_images_blur = read_all_imgs(train_synthetic_img_list[b_idx], path = config.TRAIN.synthetic_img_path, mode = 'RGB') 371 | synthetic_defocus_maps = read_all_imgs(train_defocus_map_list[b_idx], path = config.TRAIN.defocus_map_path, mode = 'DEPTH') 372 | 373 | synthetic_images_blur, synthetic_defocus_maps = crop_pair_with_different_shape_images(synthetic_images_blur, synthetic_defocus_maps, [h, w], is_gaussian_noise = tl.global_flag['is_noise']) 374 | 375 | # read real data # 376 | b_idx = (idx % len(train_real_img_list) + np.arange(batch_size)) % len(train_real_img_list) 377 | real_images_blur = read_all_imgs(train_real_img_list[b_idx], path = config.TRAIN.real_img_path, mode = 'RGB') 378 | real_binary_maps = read_all_imgs(train_real_binary_map_list[b_idx], path = config.TRAIN.real_binary_map_path, mode = 'GRAY') 379 | real_images_blur, real_binary_maps = crop_pair_with_different_shape_images(real_images_blur, real_binary_maps, [h, w]) 380 | real_images_no_label_blur = read_all_imgs(train_real_img_no_label_list[b_idx], path = config.TRAIN.real_img_no_label_path, mode = 'RGB') 381 | real_images_no_label_blur = random_crop(real_images_no_label_blur, [h, w]) 382 | 383 | ## RUN NETWORK 384 | #discriminator 385 | feed_dict = {patches_synthetic: synthetic_images_blur, patches_real: real_images_blur, labels_synthetic_defocus: synthetic_defocus_maps, patches_real_no_label: real_images_no_label_blur} 386 | _ = sess.run(optim_d, feed_dict) 387 | 388 | #generator 389 | feed_dict = {patches_synthetic: synthetic_images_blur, labels_synthetic_defocus: synthetic_defocus_maps, patches_real: real_images_blur, labels_real_binary: real_binary_maps, patches_real_no_label: real_images_no_label_blur} 390 | _ = sess.run(optim_main, feed_dict) 391 | 392 | #log 393 | err_main, err_g, err_d, d_synthetic, d_real, lr = \ 394 | sess.run([loss_main, loss_g, loss_d, d_feature_synthetic, d_feature_real, learning_rate], feed_dict) 395 | d_acc = get_disc_accuracy([d_synthetic, d_real], [0, 1]) 396 | g_acc = get_disc_accuracy([d_synthetic, d_real], [1, 0]) 397 | 398 | print('[%s] Ep [%2d/%2d] %4d/%4d time: %4.2fs, err[main: %1.2e, g(acc): %1.2e(%1.2f), d(acc): %1.2e(%1.2f)], lr: %1.2e' % \ 399 | (tl.global_flag['mode'], epoch, n_epoch, n_iter, len(train_synthetic_img_list)/batch_size, time.time() - step_time, err_main, err_g, g_acc, err_d, d_acc, lr)) 400 | 401 | ## SAVE LOGS 402 | # save loss & image log 403 | if global_step % config.TRAIN.write_log_every == 0: 404 | summary_loss_g, summary_loss_d, summary_image = sess.run([loss_sum_g, loss_sum_d, image_sum], {patches_synthetic: synthetic_images_blur, labels_synthetic_defocus: synthetic_defocus_maps, patches_real: real_images_blur, labels_real_binary: real_binary_maps, patches_real_no_label: real_images_no_label_blur}) 405 | writer_scalar.add_summary(summary_loss_d, global_step) 406 | writer_scalar.add_summary(summary_loss_g, global_step) 407 | writer_image.add_summary(summary_image, global_step) 408 | 409 | # save samples 410 | # if global_step != 0 and global_step % config.TRAIN.write_sample_every == 0: 411 | # synthetic_defocus_out, real_defocus_out, real_binary_out = sess.run([output_synthetic_defocus, output_real_defocus, output_real_binary], {patches_synthetic: synthetic_images_blur, patches_real: real_images_blur, labels_real_binary: real_binary_maps }) 412 | # save_images(synthetic_images_blur, [ni, ni], sample_dir + '/{}_{}_1_synthetic_input.png'.format(epoch, global_step)) 413 | # save_images(norm_image(synthetic_defocus_out), [ni, ni], sample_dir + '/{}_{}_2_synthetic_defocus_out_norm.png'.format(epoch, global_step)) 414 | # save_images(norm_image(synthetic_defocus_maps), [ni, ni], sample_dir + '/{}_{}_3_synthetic_defocus_gt.png'.format(epoch, global_step)) 415 | # save_images(real_images_blur, [ni, ni], sample_dir + '/{}_{}_4_real_input.png'.format(epoch, global_step)) 416 | # save_images(norm_image(real_defocus_out), [ni, ni], sample_dir + '/{}_{}_5_real_defocus_out_norm.png'.format(epoch, global_step)) 417 | # save_images(real_binary_out, [ni, ni], sample_dir + '/{}_{}_6_real_binary_out.png'.format(epoch, global_step)) 418 | # save_images(real_binary_maps, [ni, ni], sample_dir + '/{}_{}_7_real_binary_gt.png'.format(epoch, global_step)) 419 | 420 | total_loss += err_main 421 | n_iter += 1 422 | global_step += 1 423 | 424 | print('[TRAIN] Epoch: [%2d/%2d] time: %4.4fs, total_err: %1.2e' % (epoch, n_epoch, time.time() - epoch_time, total_loss/n_iter)) 425 | # reset image log 426 | if epoch % config.TRAIN.refresh_image_log_every == 0: 427 | writer_image.close() 428 | remove_file_end_with(log_dir_image, '*.image_log') 429 | writer_image.reopen() 430 | 431 | if epoch % config.TRAIN.write_ckpt_every == 0: 432 | #remove_file_end_with(ckpt_dir, '*.npz') 433 | tl.files.save_npz_dict(save_vars, name = ckpt_dir + '/{}_{}.npz'.format(tl.global_flag['mode'], epoch), sess = sess) 434 | 435 | 436 | def evaluate(): 437 | date = datetime.datetime.now().strftime('%Y_%m_%d_%H%M') 438 | # directories 439 | mode_dir = os.path.join(config.TRAIN.root_dir, tl.global_flag['mode']) 440 | ckpt_dir = os.path.join(mode_dir, 'checkpoint') 441 | sample_dir = os.path.join(mode_dir, 'results/{}/{}'.format(tl.global_flag['test_set'], date)) 442 | 443 | # input 444 | input_path, gt_path = get_eval_path(tl.global_flag['test_set'], config) 445 | test_blur_img_list = np.array(sorted(tl.files.load_file_list(path = input_path, regx = '.*', printable = False))) 446 | test_blur_imgs = read_all_imgs(test_blur_img_list, path = input_path, mode = 'RGB') 447 | # gt 448 | if gt_path is not None: 449 | test_gt_list = np.array(sorted(tl.files.load_file_list(path = gt_path, regx = '.*', printable = False))) 450 | mode = 'NPY' if 'RTF' in tl.global_flag['test_set'] else 'GRAY' 451 | test_gt_imgs = read_all_imgs(test_gt_list, path = gt_path, mode = mode) 452 | 453 | # define session 454 | sess = tf.Session(config = tf.ConfigProto(allow_soft_placement = True, log_device_placement = False)) 455 | # define model 456 | with tf.variable_scope('input'): 457 | patches_blurred = tf.placeholder('float32', [1, None, None, 3], name = 'input_patches') 458 | 459 | with tf.variable_scope('main_net') as scope: 460 | with tf.variable_scope('defocus_net') as scope: 461 | with tf.variable_scope('encoder') as scope: 462 | feats_down = VGG19_down(patches_blurred, reuse = False, scope = scope, is_test = True) 463 | with tf.variable_scope('decoder') as scope: 464 | output_defocus, feats_up, _, refine_lists = UNet_up(patches_blurred, feats_down, is_train = False, reuse = False, scope = scope) 465 | 466 | # init vars 467 | sess.run(tf.global_variables_initializer()) 468 | # load checkpoint 469 | ckpt_path = os.path.join(ckpt_dir, '{}.npz'.format(tl.global_flag['mode'])) 470 | if os.path.isfile(ckpt_path) is False: 471 | print('{} does not exit'.format(ckpt_path)) 472 | exit() 473 | tl.files.load_and_assign_npz_dict(name = ckpt_path, sess = sess) 474 | 475 | print('================') 476 | print('Evaluation Start') 477 | print('================') 478 | print('Results will be saved in: {}\n'.format(sample_dir)) 479 | avg_time = 0. 480 | MSE_total = 0 481 | MAE_total = 0 482 | for i in np.arange(len(test_blur_imgs)): 483 | test_blur_img = refine_image(test_blur_imgs[i]) 484 | 485 | if gt_path is not None: 486 | test_gt_img = refine_image(test_gt_imgs[i]) 487 | test_gt_img = np.squeeze(test_gt_img) 488 | 489 | # run network 490 | feed_dict = {patches_blurred: np.expand_dims(test_blur_img, axis = 0)} 491 | tic = time.time() 492 | defocus_map, feats_down_out, feats_up_out, refine_lists_out = sess.run([output_defocus, feats_down, feats_up, refine_lists], feed_dict) 493 | toc = time.time() 494 | 495 | defocus_map = np.squeeze(defocus_map) 496 | defocus_map_norm = defocus_map - defocus_map.min() 497 | defocus_map_norm = defocus_map_norm / defocus_map_norm.max() 498 | 499 | ################## 500 | sigma_map = ((defocus_map * 15) - 1) / 2 501 | sigma_map[np.where(sigma_map < 0)] = 0 502 | # when you read, multipy the image by 7 to get sigma 503 | sigma_map = sigma_map / 7. 504 | ################## 505 | 506 | # quantitative 507 | if gt_path is not None: 508 | if 'RTF' in tl.global_flag['test_set']: 509 | h, w = sigma_map.shape 510 | h_gt, w_gt = test_gt_img.shape 511 | in_temp = sigma_map[:min(h, h_gt), :min(w, w_gt)] * 7. 512 | in_temp[np.where(in_temp>3.275)] = 3.275 513 | in_temp = in_temp / 3.275 514 | gt_temp = test_gt_img[:min(h, h_gt), :min(w, w_gt)] 515 | elif 'SYNDOF' in tl.global_flag['test_set']: 516 | in_temp = defocus_map 517 | gt_temp = test_gt_img 518 | 519 | MSE_total = MSE_total + np.mean((in_temp - gt_temp)**2) 520 | MAE_total = MAE_total + np.mean(np.abs(in_temp - gt_temp)) 521 | 522 | # qualitative 523 | tl.files.exists_or_mkdir(sample_dir, verbose = False) 524 | tl.files.exists_or_mkdir(sample_dir + '/image') 525 | tl.files.exists_or_mkdir(sample_dir + '/defocus_map') 526 | tl.files.exists_or_mkdir(sample_dir + '/defocus_map_min_max_norm') 527 | tl.files.exists_or_mkdir(sample_dir + '/sigma_map_7_norm') 528 | scipy.misc.toimage(test_blur_img, cmin = 0., cmax = 1.).save(sample_dir + '/image/{0:04d}.png'.format(i)) 529 | scipy.misc.toimage(defocus_map, cmin = 0., cmax = 1.).save(sample_dir + '/defocus_map/{0:04d}.png'.format(i)) 530 | scipy.misc.toimage(defocus_map_norm, cmin = 0., cmax = 1.).save(sample_dir + '/defocus_map_min_max_norm/{0:04d}.png'.format(i)) 531 | scipy.misc.toimage(sigma_map, cmin = 0., cmax = 1.).save(sample_dir + '/sigma_map_7_norm/{0:04d}.png'.format(i)) 532 | 533 | if gt_path is not None: 534 | tl.files.exists_or_mkdir(sample_dir + '/gt') 535 | scipy.misc.toimage(np.squeeze(1 - refine_image(test_gt_imgs[i])), cmin = 0., cmax = 1.).save(sample_dir + '/gt/{0:04d}.png'.format(i)) 536 | 537 | avg_time = avg_time + (toc - tic) 538 | print('[{}/{}] {} [{:.3f}s]\n'.format(i+1, len(test_blur_imgs), test_blur_img_list[i], toc - tic)) 539 | 540 | avg_time = avg_time / len(test_blur_imgs) 541 | print('averge time: {:.3f}s'.format(avg_time)) 542 | if gt_path is not None: 543 | print('MSE: ', MSE_total / len(test_blur_imgs), ' MAE: ', MAE_total / len(test_blur_imgs)) 544 | 545 | if __name__ == '__main__': 546 | import argparse 547 | parser = argparse.ArgumentParser() 548 | 549 | parser.add_argument('--mode', type = str, default = 'DMENet', help = 'model name') 550 | parser.add_argument('--is_train', action = 'store_true', default = False, help = 'whether to train or not') 551 | parser.add_argument('--is_pretrain', action = 'store_true', default = False, help = 'whether to pretrain or not') 552 | parser.add_argument('--is_noise', action = 'store_true', default = False, help = 'whether to add noise to synthetic images') 553 | parser.add_argument('--delete_log', action = 'store_true', default = False, help = 'whether to delete log or not') 554 | parser.add_argument('--test_set', type = str , default = 'CUHK', help = 'test_set CUHK|SYNDOF|RTF0|RTF1|RTF1_6|random') 555 | 556 | args = parser.parse_args() 557 | 558 | tl.global_flag['mode'] = args.mode 559 | tl.global_flag['is_train'] = args.is_train 560 | tl.global_flag['is_pretrain'] = args.is_pretrain 561 | tl.global_flag['is_noise'] = args.is_noise 562 | tl.global_flag['delete_log'] = args.delete_log 563 | 564 | if tl.global_flag['is_train']: 565 | train() 566 | else: 567 | tl.global_flag['test_set'] = args.test_set 568 | evaluate() 569 | 570 | -------------------------------------------------------------------------------- /model.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import tensorlayer as tl 3 | import numpy as np 4 | from tensorlayer.layers import * 5 | 6 | def VGG19_down(rgb, reuse, scope, is_test = False): 7 | w_init_relu = tf.contrib.layers.variance_scaling_initializer() 8 | w_init_sigmoid = tf.contrib.layers.xavier_initializer() 9 | VGG_MEAN = [103.939, 116.779, 123.68] 10 | with tf.variable_scope(scope, reuse = reuse): 11 | rgb_scaled = rgb * 255.0 12 | if tf.__version__ <= '0.11': 13 | red, green, blue = tf.split(3, 3, rgb_scaled) 14 | else: 15 | red, green, blue = tf.split(rgb_scaled, 3, 3) 16 | if tf.__version__ <= '0.11': 17 | bgr = tf.concat(3, [ 18 | blue - VGG_MEAN[0], 19 | green - VGG_MEAN[1], 20 | red - VGG_MEAN[2], 21 | ]) 22 | else: 23 | bgr = tf.concat([ 24 | blue - VGG_MEAN[0], 25 | green - VGG_MEAN[1], 26 | red - VGG_MEAN[2], 27 | ], axis=3) 28 | 29 | """ input layer """ 30 | net_in = InputLayer(bgr, name='input') 31 | """ conv1 """ 32 | network = PadLayer(net_in, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='pad1_1') 33 | network = Conv2d(network, n_filter=64, filter_size=(3, 3), strides=(1, 1), act=tf.nn.relu,padding='VALID', name='conv1_1') 34 | network = PadLayer(network, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='pad1_2') 35 | network = Conv2d(network, n_filter=64, filter_size=(3, 3), strides=(1, 1), act=tf.nn.relu,padding='VALID', name='conv1_2') 36 | d0 = network 37 | network = MaxPool2d(network, filter_size=(2, 2), strides=(2, 2), padding='SAME', name='pool1') 38 | """ conv2 """ 39 | network = PadLayer(network, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='pad2_1') 40 | network = Conv2d(network, n_filter=128, filter_size=(3, 3), strides=(1, 1), act=tf.nn.relu,padding='VALID', name='conv2_1') 41 | network = PadLayer(network, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='pad2_2') 42 | network = Conv2d(network, n_filter=128, filter_size=(3, 3), strides=(1, 1), act=tf.nn.relu,padding='VALID', name='conv2_2') 43 | d1 = network 44 | network = MaxPool2d(network, filter_size=(2, 2), strides=(2, 2), padding='SAME', name='pool2') 45 | """ conv3 """ 46 | network = PadLayer(network, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='pad3_1') 47 | network = Conv2d(network, n_filter=256, filter_size=(3, 3), strides=(1, 1), act=tf.nn.relu,padding='VALID', name='conv3_1') 48 | network = PadLayer(network, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='pad3_2') 49 | network = Conv2d(network, n_filter=256, filter_size=(3, 3), strides=(1, 1), act=tf.nn.relu,padding='VALID', name='conv3_2') 50 | network = PadLayer(network, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='pad3_3') 51 | network = Conv2d(network, n_filter=256, filter_size=(3, 3), strides=(1, 1), act=tf.nn.relu,padding='VALID', name='conv3_3') 52 | network = PadLayer(network, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='pad3_4') 53 | network = Conv2d(network, n_filter=256, filter_size=(3, 3), strides=(1, 1), act=tf.nn.relu,padding='VALID', name='conv3_4') 54 | d2 = network 55 | network = MaxPool2d(network, filter_size=(2, 2), strides=(2, 2), padding='SAME', name='pool3') 56 | """ conv4 """ 57 | network = PadLayer(network, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='pad4_1') 58 | network = Conv2d(network, n_filter=512, filter_size=(3, 3), strides=(1, 1), act=tf.nn.relu,padding='VALID', name='conv4_1') 59 | network = PadLayer(network, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='pad4_2') 60 | network = Conv2d(network, n_filter=512, filter_size=(3, 3), strides=(1, 1), act=tf.nn.relu,padding='VALID', name='conv4_2') 61 | network = PadLayer(network, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='pad4_3') 62 | network = Conv2d(network, n_filter=512, filter_size=(3, 3), strides=(1, 1), act=tf.nn.relu,padding='VALID', name='conv4_3') 63 | network = PadLayer(network, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='pad4_4') 64 | network = Conv2d(network, n_filter=512, filter_size=(3, 3), strides=(1, 1), act=tf.nn.relu,padding='VALID', name='conv4_4') 65 | d3 = network 66 | network = MaxPool2d(network, filter_size=(2, 2), strides=(2, 2), padding='SAME', name='pool4') 67 | """ conv5 """ 68 | network = PadLayer(network, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='pad5_1') 69 | network = Conv2d(network, n_filter=512, filter_size=(3, 3), strides=(1, 1), act=tf.nn.relu,padding='VALID', name='conv5_1') 70 | network = PadLayer(network, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='pad5_2') 71 | network = Conv2d(network, n_filter=512, filter_size=(3, 3), strides=(1, 1), act=tf.nn.relu,padding='VALID', name='conv5_2') 72 | network = PadLayer(network, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='pad5_3') 73 | network = Conv2d(network, n_filter=512, filter_size=(3, 3), strides=(1, 1), act=tf.nn.relu,padding='VALID', name='conv5_3') 74 | network = PadLayer(network, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='pad5_4') 75 | network = Conv2d(network, n_filter=512, filter_size=(3, 3), strides=(1, 1), act=tf.nn.relu,padding='VALID', name='conv5_4') 76 | d4 = network 77 | 78 | if is_test == False: 79 | logits = PadLayer(network, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='pad6_1') 80 | logits = Conv2d(logits, n_filter=64, filter_size=(3, 3), strides=(1, 1), act=tf.nn.relu,padding='VALID', name='conv6_1') 81 | 82 | logits = logits.outputs 83 | size = logits.get_shape().as_list() 84 | logits = InputLayer(logits) 85 | logits = Conv2d(logits, n_filter=512, filter_size=(size[1], size[2]), strides=(1, 1), act=tf.nn.relu, padding='VALID', name='c_logits_1') 86 | logits = FlattenLayer(logits, name='flatten') 87 | logits = DenseLayer(logits, n_units=512, act=tf.nn.relu, W_init = w_init_relu, name='c_logits_1') 88 | logits = DenseLayer(logits, n_units=1, act=tf.identity, W_init = w_init_sigmoid, name='c_logits_2') 89 | 90 | return network, [d0.outputs, d1.outputs, d2.outputs, d3.outputs, d4.outputs], d3.outputs, logits.outputs 91 | else: 92 | return [d0.outputs, d1.outputs, d2.outputs, d3.outputs, d4.outputs] 93 | 94 | def UNet_up(images, feats, is_train=False, reuse=False, scope = 'unet_up'): 95 | w_init_relu = tf.contrib.layers.variance_scaling_initializer() 96 | w_init_sigmoid = tf.contrib.layers.xavier_initializer() 97 | g_init = None 98 | lrelu = lambda x: tf.nn.leaky_relu(x, 0.2) 99 | 100 | def UpSampling2dLayer_(input, scale, method, align_corners, name): 101 | input = input.outputs 102 | size = tf.shape(input) 103 | 104 | n = InputLayer(input, name = name + '_in') 105 | n = UpSampling2dLayer(n, size=[size[1] * scale[0], size[2] * scale[1]], is_scale = False, method = method, align_corners = align_corners, name = name) 106 | 107 | return n 108 | 109 | with tf.variable_scope(scope, reuse=reuse): 110 | d0 = InputLayer(feats[0], name='d0') 111 | d1 = InputLayer(feats[1], name='d1') 112 | d2 = InputLayer(feats[2], name='d2') 113 | d3 = InputLayer(feats[3], name='d3') 114 | d4 = InputLayer(feats[4], name='d4') 115 | 116 | u4 = d4 117 | u4 = PadLayer(u4, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='u4_aux/pad1') 118 | u4 = Conv2d(u4, 256, (3, 3), (1, 1), act=None, padding='VALID', W_init=w_init_relu, name='u4_aux/c1') 119 | u4 = BatchNormLayer(u4, act=lrelu, is_train = is_train, gamma_init = g_init, name='u4_aux/b1') 120 | u4 = PadLayer(u4, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='u4_aux/pad2') 121 | u4 = Conv2d(u4, 1, (3, 3), (1, 1), act=None, padding='VALID', W_init=w_init_sigmoid, name='u4_aux/c2') 122 | u4 = BatchNormLayer(u4, act=tf.nn.sigmoid, is_train = is_train, gamma_init = g_init, name='u4_aux/b2') 123 | u4 = u4.outputs 124 | 125 | n = UpSampling2dLayer_(d4, (2, 2), method = 1, align_corners=True, name='u3/u') 126 | n = ConcatLayer([n, d3], concat_dim = 3, name='u3/concat') 127 | n = PadLayer(n, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='u3/pad1') 128 | n = Conv2d(n, 256, (3, 3), (1, 1), act=None, padding='VALID', W_init=w_init_relu, name='u3/c1') 129 | n = BatchNormLayer(n, act=lrelu, is_train = is_train, gamma_init = g_init, name='u3/b1') 130 | n = PadLayer(n, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='u3/pad2') 131 | n = Conv2d(n, 256, (3, 3), (1, 1), act=None, padding='VALID', W_init=w_init_relu, name='u3/c2') 132 | n = BatchNormLayer(n, act=lrelu, is_train = is_train, gamma_init = g_init, name='u3/b2') 133 | n = PadLayer(n, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='u3/pad3') 134 | n = Conv2d(n, 256, (3, 3), (1, 1), act=None, padding='VALID', W_init=w_init_relu, name='u3/c3') 135 | n = BatchNormLayer(n, act=lrelu, is_train = is_train, gamma_init = g_init, name='u3/b3') 136 | 137 | u3 = PadLayer(n, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='u3_aux/pad1') 138 | u3 = Conv2d(u3, 128, (3, 3), (1, 1), act=None, padding='VALID', W_init=w_init_relu, name='u3_aux/c1') 139 | u3 = BatchNormLayer(u3, act=lrelu, is_train = is_train, gamma_init = g_init, name='u3_aux/b1') 140 | u3 = PadLayer(u3, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='u3_aux/pad2') 141 | u3 = Conv2d(u3, 1, (3, 3), (1, 1), act=None, padding='VALID', W_init=w_init_sigmoid, name='u3_aux/c2') 142 | u3 = BatchNormLayer(u3, act=tf.nn.sigmoid, is_train = is_train, gamma_init = g_init, name='u3_aux/b2') 143 | u3 = u3.outputs 144 | 145 | n = UpSampling2dLayer_(n, (2, 2), method = 1, align_corners=True, name='u2/u') 146 | n = ConcatLayer([n, d2], concat_dim = 3, name='u2/concat') 147 | n = PadLayer(n, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='u2/pad1') 148 | n = Conv2d(n, 128, (3, 3), (1, 1), act=None, padding='VALID', W_init=w_init_relu, name='u2/c1') 149 | n = BatchNormLayer(n, act=lrelu, is_train = is_train, gamma_init = g_init, name='u2/b1') 150 | n = PadLayer(n, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='u2/pad2') 151 | n = Conv2d(n, 128, (3, 3), (1, 1), act=None, padding='VALID', W_init=w_init_relu, name='u2/c2') 152 | n = BatchNormLayer(n, act=lrelu, is_train = is_train, gamma_init = g_init, name='u2/b2') 153 | n = PadLayer(n, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='u2/pad3') 154 | n = Conv2d(n, 128, (3, 3), (1, 1), act=None, padding='VALID', W_init=w_init_relu, name='u2/c3') 155 | n = BatchNormLayer(n, act=lrelu, is_train = is_train, gamma_init = g_init, name='u2/b3') 156 | 157 | u2 = PadLayer(n, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='u2_aux/pad1') 158 | u2 = Conv2d(u2, 64, (3, 3), (1, 1), act=None, padding='VALID', W_init=w_init_relu, name='u2_aux/c1') 159 | u2 = BatchNormLayer(u2, act=lrelu, is_train = is_train, gamma_init = g_init, name='u2_aux/b1') 160 | u2 = PadLayer(u2, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='u2_aux/pad2') 161 | u2 = Conv2d(u2, 1, (3, 3), (1, 1), act=None, padding='VALID', W_init=w_init_sigmoid, name='u2_aux/c2') 162 | u2 = BatchNormLayer(u2, act=tf.nn.sigmoid, is_train = is_train, gamma_init = g_init, name='u2_aux/b2') 163 | u2 = u2.outputs 164 | 165 | n = UpSampling2dLayer_(n, (2, 2), method = 1, align_corners=True, name='u1/u') 166 | n = ConcatLayer([n, d1], concat_dim = 3, name='u1/concat') 167 | n = PadLayer(n, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='u1/pad1') 168 | n = Conv2d(n, 64, (3, 3), (1, 1), act=None, padding='VALID', W_init=w_init_relu, name='u1/c1') 169 | n = BatchNormLayer(n, act=lrelu, is_train = is_train, gamma_init = g_init, name='u1/b1') 170 | n = PadLayer(n, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='u1/pad2') 171 | n = Conv2d(n, 64, (3, 3), (1, 1), act=None, padding='VALID', W_init=w_init_relu, name='u1/c2') 172 | n = BatchNormLayer(n, act=lrelu, is_train = is_train, gamma_init = g_init, name='u1/b2') 173 | n = PadLayer(n, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='u1/pad3') 174 | n = Conv2d(n, 64, (3, 3), (1, 1), act=None, padding='VALID', W_init=w_init_relu, name='u1/c3') 175 | n = BatchNormLayer(n, act=lrelu, is_train = is_train, gamma_init = g_init, name='u1/b3') 176 | 177 | u1 = PadLayer(n, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='u1_aux/pad1') 178 | u1 = Conv2d(u1, 32, (3, 3), (1, 1), act=None, padding='VALID', W_init=w_init_relu, name='u1_aux/c1') 179 | u1 = BatchNormLayer(u1, act=lrelu, is_train = is_train, gamma_init = g_init, name='u1_aux/b1') 180 | u1 = PadLayer(u1, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='u1_aux/pad2') 181 | u1 = Conv2d(u1, 1, (3, 3), (1, 1), act=None, padding='VALID', W_init=w_init_sigmoid, name='u1_aux/c2') 182 | u1 = BatchNormLayer(u1, act=tf.nn.sigmoid, is_train = is_train, gamma_init = g_init, name='u1_aux/b2') 183 | u1 = u1.outputs 184 | 185 | n = UpSampling2dLayer_(n, (2, 2), method = 1, align_corners=True, name='u0/u') 186 | n = ConcatLayer([n, d0], concat_dim = 3, name='u0/concat') 187 | n = PadLayer(n, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='u0/pad_init') 188 | n = Conv2d(n, 64, (3, 3), (1, 1), act=None, padding='VALID', W_init=w_init_relu, name='u0/c_init') 189 | n = BatchNormLayer(n, act=lrelu, is_train = is_train, gamma_init = g_init, name='u0/b_init') 190 | gan_feat = n.outputs 191 | 192 | u0 = PadLayer(n, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='u0_aux/pad1') 193 | u0 = Conv2d(u0, 32, (3, 3), (1, 1), act=None, padding='VALID', W_init=w_init_relu, name='u0_aux/c1') 194 | u0 = BatchNormLayer(u0, act=lrelu, is_train = is_train, gamma_init = g_init, name='u0_aux/b1') 195 | u0 = PadLayer(u0, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='u0_aux/pad2') 196 | u0 = Conv2d(u0, 1, (3, 3), (1, 1), act=None, padding='VALID', W_init=w_init_sigmoid, name='u0_aux/c2') 197 | u0 = BatchNormLayer(u0, act=tf.nn.sigmoid, is_train = is_train, gamma_init = g_init, name='u0_aux/b2') 198 | u0 = u0.outputs 199 | 200 | refine_lists = [] 201 | refine_lists.append(n.outputs) 202 | for i in np.arange(7): 203 | n_res = n 204 | n_res = Conv2d(n_res, 64, (1, 1), (1, 1), act=None, padding='VALID', W_init=w_init_relu, name='u0/c_res{}'.format(i))# 205 | n_res = BatchNormLayer(n_res, act=lrelu, is_train = is_train, gamma_init = g_init, name='u0/b_res{}'.format(i))# 206 | 207 | n = PadLayer(n, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='u0/pad{}_1'.format(i)) 208 | n = Conv2d(n, 64, (3, 3), (1, 1), act=None, padding='VALID', W_init=w_init_relu, name='u0/c{}_1'.format(i)) 209 | n = BatchNormLayer(n, act=lrelu, is_train = is_train, gamma_init = g_init, name='u0/b{}_1'.format(i)) 210 | n = PadLayer(n, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='u0/pad{}_2'.format(i)) 211 | n = Conv2d(n, 64, (3, 3), (1, 1), act=None, padding='VALID', W_init=w_init_relu, name='u0/c{}_2'.format(i)) 212 | n = BatchNormLayer(n, act=lrelu, is_train = is_train, gamma_init = g_init, name='u0/b{}_2'.format(i)) 213 | n = ElementwiseLayer([n, n_res], tf.add, name='u0/add{}'.format(i))# 214 | refine_lists.append(n.outputs) 215 | 216 | n = PadLayer(n, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='uf/pad1')# 217 | n = Conv2d(n, 64, (3, 3), (1, 1), act=None, padding='VALID', W_init=w_init_relu, name='uf/c1')# 218 | n = BatchNormLayer(n, act=lrelu, is_train = is_train, gamma_init = g_init, name='uf/b1')# 219 | n = PadLayer(n, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='uf/pad2')# 220 | n = Conv2d(n, 32, (3, 3), (1, 1), act=None, padding='VALID', W_init=w_init_relu, name='uf/c2')# 221 | n = BatchNormLayer(n, act=lrelu, is_train = is_train, gamma_init = g_init, name='uf/b2')# 222 | n = PadLayer(n, [[0, 0], [1, 1], [1, 1], [0, 0]], "Symmetric", name='uf/pad3')#pad1 223 | n = Conv2d(n, 1, (3, 3), (1, 1), act=None, padding='VALID', W_init=w_init_sigmoid, name='uf/c3')#c1 224 | 225 | return tf.nn.sigmoid(n.outputs), [u4, u3, u2, u1, u0], gan_feat, refine_lists 226 | 227 | def feature_discriminator(feats, is_train=True, reuse=False, scope = 'feature_discriminator'): 228 | w_init = tf.contrib.layers.variance_scaling_initializer() 229 | w_init_sigmoid = tf.contrib.layers.xavier_initializer() 230 | b_init = None 231 | g_init = None 232 | 233 | lrelu = lambda x: tf.nn.leaky_relu(x, 0.2) 234 | with tf.variable_scope(scope, reuse=reuse): 235 | n = InputLayer(feats, name='input_feature') 236 | 237 | n = Conv2d(n, 64, (4, 4), (2, 2), act=None, padding='SAME', W_init=w_init, b_init=b_init, name='h0/c1') 238 | n = BatchNormLayer(n, act=lrelu, is_train = is_train, gamma_init = g_init, name='h0/b1')# 239 | n = Conv2d(n, 128, (4, 4), (2, 2), act=None, padding='SAME', W_init=w_init, b_init=b_init, name='h1/c1') 240 | n = BatchNormLayer(n, act=lrelu, is_train = is_train, gamma_init = g_init, name='h1/b1')# 241 | n = Conv2d(n, 256, (4, 4), (2, 2), act=None, padding='SAME', W_init=w_init, b_init=b_init, name='h2/c1') 242 | n = BatchNormLayer(n, act=lrelu, is_train = is_train, gamma_init = g_init, name='h2/b1')# 243 | n = Conv2d(n, 512, (4, 4), (2, 2), act=None, padding='SAME', W_init=w_init, b_init=b_init, name='h3/c1') 244 | n = BatchNormLayer(n, act=lrelu, is_train = is_train, gamma_init = g_init, name='h3/b1')# 245 | n = Conv2d(n, 1, (4, 4), (2, 2), act=None, padding='SAME', W_init=w_init_sigmoid, b_init=b_init, name='h4/c1') 246 | 247 | logits = n.outputs 248 | 249 | return logits, tf.nn.sigmoid(logits) 250 | 251 | def Binary_Net(input_defocus, is_train=False, reuse=False, scope = 'Binary_Net'): 252 | w_init_relu = tf.contrib.layers.variance_scaling_initializer() 253 | w_init_sigmoid = tf.contrib.layers.xavier_initializer() 254 | b_init = None 255 | g_init = None 256 | lrelu = lambda x: tf.nn.leaky_relu(x, 0.2) 257 | with tf.variable_scope(scope, reuse=reuse): 258 | n = InputLayer(input_defocus, name='input_defocus') 259 | 260 | n = Conv2d(n, 64, (1, 1), (1, 1), act=None, padding='VALID', W_init=w_init_relu, name='l1/c1') 261 | n = BatchNormLayer(n, act=lrelu, is_train = is_train, gamma_init = g_init, name='l1/b1') 262 | n = Conv2d(n, 64, (1, 1), (1, 1), act=None, padding='VALID', W_init=w_init_relu, name='l1/c2') 263 | n = BatchNormLayer(n, act=lrelu, is_train = is_train, gamma_init = g_init, name='l1/b2') 264 | n = Conv2d(n, 64, (1, 1), (1, 1), act=None, padding='VALID', W_init=w_init_relu, name='l1/c3') 265 | n = BatchNormLayer(n, act=lrelu, is_train = is_train, gamma_init = g_init, name='l1/b3') 266 | 267 | n = Conv2d(n, 32, (1, 1), (1, 1), act=None, padding='VALID', W_init=w_init_relu, name='l2/c1') 268 | n = BatchNormLayer(n, act=lrelu, is_train = is_train, gamma_init = g_init, name='l2/b1') 269 | n = Conv2d(n, 32, (1, 1), (1, 1), act=None, padding='VALID', W_init=w_init_relu, name='l2/c2') 270 | n = BatchNormLayer(n, act=lrelu, is_train = is_train, gamma_init = g_init, name='l2/b2') 271 | n = Conv2d(n, 32, (1, 1), (1, 1), act=None, padding='VALID', W_init=w_init_relu, name='l2/c3') 272 | n = BatchNormLayer(n, act=lrelu, is_train = is_train, gamma_init = g_init, name='l2/b3') 273 | 274 | n = Conv2d(n, 16, (1, 1), (1, 1), act=None, padding='VALID', W_init=w_init_relu, name='l3/c1') 275 | n = BatchNormLayer(n, act=lrelu, is_train = is_train, gamma_init = g_init, name='l3/b1') 276 | n = Conv2d(n, 16, (1, 1), (1, 1), act=None, padding='VALID', W_init=w_init_relu, name='l3/c2') 277 | n = BatchNormLayer(n, act=lrelu, is_train = is_train, gamma_init = g_init, name='l3/b2') 278 | n = Conv2d(n, 16, (1, 1), (1, 1), act=None, padding='VALID', W_init=w_init_relu, name='l3/c3') 279 | n = BatchNormLayer(n, act=lrelu, is_train = is_train, gamma_init = g_init, name='l3/b3') 280 | 281 | n = Conv2d(n, 1, (1, 1), (1, 1), act=None, padding='VALID', W_init=w_init_sigmoid, name='l4/c1') 282 | logits = n.outputs 283 | 284 | return logits, tf.nn.sigmoid(n.outputs) 285 | 286 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | easydict==1.9 2 | opencv-python==4.5.1.48 3 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import tensorlayer as tl 3 | from tensorlayer.prepro import * 4 | from config import config, log_config 5 | from skimage import feature 6 | from skimage import color 7 | from scipy.ndimage.filters import gaussian_filter 8 | 9 | import scipy 10 | import numpy as np 11 | import cv2 12 | import math 13 | import random 14 | 15 | import os 16 | import fnmatch 17 | 18 | def read_all_imgs(file_name_list, path = '', mode = 'RGB'): 19 | imgs = [] 20 | for idx in range(0, len(file_name_list)): 21 | imgs.append(get_images(file_name_list[idx], path, mode)) 22 | 23 | return imgs 24 | 25 | def get_images(file_name, path, mode): 26 | """ Input an image path and name, return an image array """ 27 | # return scipy.misc.imread(path + file_name).astype(np.float) 28 | if mode is 'RGB': 29 | image = (scipy.misc.imread(path + file_name, mode='RGB')/255.).astype(np.float32) 30 | elif mode is 'GRAY': 31 | image = (scipy.misc.imread(path + file_name, mode='P')/255.).astype(np.float32) 32 | image = np.expand_dims(image, axis = 2) 33 | elif mode is 'NPY': 34 | image = np.load(path + file_name) 35 | image = image / 3.275 36 | image = np.expand_dims(image, axis = 2) 37 | elif mode is 'DEPTH': 38 | image = (np.float32(cv2.imread(path + file_name, cv2.IMREAD_UNCHANGED))/10.)[:, :, 1] 39 | ## If you train the network with the SYNDOF dataset (this is the original SYNDOF dataset) shared in this repository. 40 | ## The SYNDOF datasets's maximum COC value is 15 and we saved the defocus map with the COC value. 41 | ## (The paper say that maximum COC value is 28, becuase the blur kernel of orignal SYNDOF dataset visually had the maximaum coc value of 28 when it was generated with max_coc=15.) 42 | 43 | image = image / 15 44 | 45 | ## If you train the network with the new SYNDOF dataset generated with the codes in "https://github.com/codeslake/SYNDOF". 46 | ## We save the sigma value (max=7) in the code, where 47 | ## sigma = (max_coc-1)/4, when max_coc = 29, max_sigma = 7 48 | 49 | # image = image / 7 50 | 51 | image = np.expand_dims(image, axis = 2) 52 | 53 | return image 54 | 55 | def t_or_f(arg): 56 | ua = str(arg).upper() 57 | if 'TRUE'.startswith(ua): 58 | return True 59 | elif 'FALSE'.startswith(ua): 60 | return False 61 | else: 62 | pass 63 | 64 | def _tf_fspecial_gauss(size, sigma): 65 | """Function to mimic the 'fspecial' gaussian MATLAB function 66 | """ 67 | x_data, y_data = np.mgrid[-size//2 + 1:size//2 + 1, -size//2 + 1:size//2 + 1] 68 | 69 | x_data = np.expand_dims(x_data, axis=-1) 70 | x_data = np.expand_dims(x_data, axis=-1) 71 | 72 | y_data = np.expand_dims(y_data, axis=-1) 73 | y_data = np.expand_dims(y_data, axis=-1) 74 | 75 | x = tf.constant(x_data, dtype=tf.float32) 76 | y = tf.constant(y_data, dtype=tf.float32) 77 | 78 | g = tf.exp(-((x**2 + y**2)/(2.0*sigma**2))) 79 | return g / tf.reduce_sum(g) 80 | 81 | def refine_image(img): 82 | h, w = img.shape[:2] 83 | 84 | return img[0 : h - h % 16, 0 : w - w % 16] 85 | 86 | def random_crop(images, resize_shape, is_gaussian_noise = False): 87 | images_list = None 88 | h, w = resize_shape[:2] 89 | max_size_limit = 800 90 | 91 | for i in np.arange(len(images)): 92 | image = np.copy(images[i]) 93 | shape = np.array(image.shape[:2]) 94 | 95 | if shape.min() <= h: 96 | ratio = resize_shape[shape.argmin()]/float(shape.min()) 97 | resize_w = int(math.floor(shape[1] * ratio)) + 1 98 | resize_h = int(math.floor(shape[0] * ratio)) + 1 99 | image = cv2.resize(image, (resize_w, resize_h)) 100 | 101 | if shape.min() > max_size_limit: 102 | ratio = max_size_limit/float(shape.min()) 103 | resize_w = int(math.floor(shape[1] * ratio)) + 1 104 | resize_h = int(math.floor(shape[0] * ratio)) + 1 105 | image = cv2.resize(image, (resize_w, resize_h)) 106 | 107 | if is_gaussian_noise: 108 | image = add_gaussian_noise(image) 109 | 110 | cropped_image = tl.prepro.crop(image, wrg=w, hrg=h, is_random=True) 111 | augmented_image = _random_flip(cropped_image) 112 | angles = np.array([1, 2, 3, 4]) 113 | angle = np.random.choice(angles) 114 | augmented_image = _random_rotation(augmented_image, angle) 115 | image = np.expand_dims(augmented_image, axis=0) 116 | 117 | images_list = np.copy(image) if i == 0 else np.concatenate((images_list, image), axis = 0) 118 | 119 | return images_list 120 | 121 | def crop_pair_with_different_shape_images(images, labels, resize_shape, is_gaussian_noise = False): 122 | images_list = None 123 | labels_list = None 124 | h, w = resize_shape[:2] 125 | max_size_limit = 800 126 | 127 | for i in np.arange(len(images)): 128 | image = np.copy(images[i]) 129 | label = np.copy(labels[i]) 130 | shape = np.array(image.shape[:2]) 131 | 132 | if shape.min() <= h: 133 | ratio = resize_shape[shape.argmin()]/float(shape.min()) 134 | resize_w = int(math.floor(shape[1] * ratio)) + 1 135 | resize_h = int(math.floor(shape[0] * ratio)) + 1 136 | image = cv2.resize(image, (resize_w, resize_h)) 137 | label = np.expand_dims(cv2.resize(label[:, :, 0], (resize_w, resize_h)), axis = 2) 138 | 139 | if shape.min() > max_size_limit: 140 | ratio = max_size_limit/float(shape.min()) 141 | resize_w = int(math.floor(shape[1] * ratio)) + 1 142 | resize_h = int(math.floor(shape[0] * ratio)) + 1 143 | image = cv2.resize(image, (resize_w, resize_h)) 144 | label = np.expand_dims(cv2.resize(label[:, :, 0], (resize_w, resize_h)), axis = 2) 145 | 146 | if is_gaussian_noise: 147 | image = add_gaussian_noise(image) 148 | 149 | concatenated_images = np.concatenate((image, label), axis = 2) 150 | cropped_images = tl.prepro.crop(concatenated_images, wrg=w, hrg=h, is_random=True) 151 | augmented_images = _random_flip(cropped_images) 152 | angles = np.array([1, 2, 3, 4]) 153 | angle = np.random.choice(angles) 154 | augmented_images = _random_rotation(augmented_images, angle) 155 | 156 | image = np.expand_dims(augmented_images[:, :, 0:3], axis=0) 157 | label = np.expand_dims(np.expand_dims(augmented_images[:, :, 3], axis=3), axis=0) 158 | 159 | images_list = np.copy(image) if i == 0 else np.concatenate((images_list, image), axis = 0) 160 | labels_list = np.copy(label) if i == 0 else np.concatenate((labels_list, label), axis = 0) 161 | 162 | return images_list, labels_list 163 | 164 | def add_gaussian_noise(image): 165 | image = image.astype(np.float32) 166 | shape = image.shape[:2] 167 | 168 | mean = 0 169 | var = random.uniform(0,0.1) 170 | sigma = var ** 0.5 171 | gamma = 0.25 172 | alpha = 0.75 173 | beta = 1 - alpha 174 | 175 | gaussian = np.random.normal(loc=mean, scale = sigma, size = (shape[0], shape[1], 1)).astype(np.float32) 176 | gaussian = np.concatenate((gaussian, gaussian, gaussian), axis = 2) 177 | #gaussian_img = image * 0.75 + 0.25 * gaussian + 0.25 178 | gaussian_img = cv2.addWeighted(image, alpha, beta * gaussian, beta, gamma) 179 | 180 | return gaussian_img 181 | 182 | # noise_sigma = 0.01 183 | # h = image.shape[0] 184 | # w = image.shape[1] 185 | # noise = np.random.randn(h, w) * noise_sigma 186 | 187 | # noisy_image = np.zeros(image.shape, np.float64) 188 | # if len(image.shape) == 2: 189 | # noisy_image = image + noise 190 | # else: 191 | # noisy_image[:,:,0] = image[:,:,0] + noise 192 | # noisy_image[:,:,1] = image[:,:,1] + noise 193 | # noisy_image[:,:,2] = image[:,:,2] + noise 194 | 195 | # """ 196 | # print('min,max = ', np.min(noisy_image), np.max(noisy_image)) 197 | # print('type = ', type(noisy_image[0][0][0])) 198 | # """ 199 | 200 | # return noisy_image 201 | 202 | def _random_flip(images): 203 | flipped_images = tl.prepro.flip_axis(images, axis=0, is_random=True) 204 | 205 | return flipped_images 206 | 207 | def _random_rotation(images, angle): 208 | if angle != 4: 209 | rotated_images = np.rot90(images, angle) 210 | else: 211 | rotated_images = images 212 | 213 | return rotated_images 214 | 215 | def _get_file_path(path, regex): 216 | file_path = [] 217 | for root, dirnames, filenames in os.walk(path): 218 | for i in np.arange(len(regex)): 219 | for filename in fnmatch.filter(filenames, regex[i]): 220 | file_path.append(os.path.join(root, filename)) 221 | 222 | return file_path 223 | 224 | def remove_file_end_with(path, regex): 225 | file_paths = _get_file_path(path, [regex]) 226 | 227 | for i in np.arange(len(file_paths)): 228 | os.remove(file_paths[i]) 229 | 230 | def save_images(images, size, image_path='_temp.png'): 231 | if len(images.shape) == 3: # Greyscale [batch, h, w] --> [batch, h, w, 1] 232 | images = images[:, :, :, np.newaxis] 233 | 234 | def merge(images, size): 235 | h, w = images.shape[1], images.shape[2] 236 | img = np.zeros((h * size[0], w * size[1], 3)) 237 | for idx, image in enumerate(images): 238 | i = idx % size[1] 239 | j = idx // size[1] 240 | img[j * h:j * h + h, i * w:i * w + w, :] = image 241 | return img 242 | 243 | def imsave(images, size, path): 244 | return scipy.misc.toimage(merge(images, size), cmin = 0., cmax = 1.).save(path) 245 | 246 | assert len(images) <= size[0] * size[1], "number of images should be equal or less than size[0] * size[1] {}".format(len(images)) 247 | 248 | return imsave(images, size, image_path) 249 | 250 | def fix_image_tf(image, norm_value): 251 | return tf.cast(image / norm_value * 255., tf.uint8) 252 | 253 | def norm_image_tf(image): 254 | image = image - tf.reduce_min(image, axis = [1, 2, 3], keepdims=True) 255 | image = image / tf.reduce_max(image, axis = [1, 2, 3], keepdims=True) 256 | return tf.cast(image * 255., tf.uint8) 257 | 258 | def norm_image(image, axis = (1, 2, 3)): 259 | image = image - np.amin(image, axis = axis, keepdims=True) 260 | image = image / np.amax(image, axis = axis, keepdims=True) 261 | return image 262 | 263 | def get_disc_accuracy(logits, labels): 264 | acc = 0. 265 | for i in np.arange(len(logits)): 266 | tp = 0 267 | logits[i] = np.round(np.squeeze(logits[i])).astype(int) 268 | temp = logits[i] 269 | tp = tp + len(temp[np.where(temp == labels[i])]) 270 | acc = acc + (tp / float(len(logits[i]))) 271 | return acc / float(len(labels)) 272 | 273 | --------------------------------------------------------------------------------