├── .gitignore
├── LICENSE
├── Supplymental_material.pdf
├── dataset
├── DND_sRGB.py
├── SIDD_sRGB.py
├── __init__.py
└── base.py
├── image_denoising.yaml
├── model
├── __init__.py
├── base.py
├── bnn.py
└── three_stage.py
├── network
├── __init__.py
├── bnn.py
├── lan.py
└── unet.py
├── option
├── bnn.json
└── three_stage.json
├── pretrained_models
├── BNN.pth
├── LAN.pth
└── UNet.pth
├── readme.md
├── submit_test
├── ensemble_wrapper.py
├── test_DND.py
└── test_SIDD.py
├── utils
├── build.py
├── io.py
└── option.py
└── validate
└── validate_SIDD.py
/.gitignore:
--------------------------------------------------------------------------------
1 | .xml
2 | .idea
3 | .idea/workspace.xml
4 | .DS_Store
5 | */__pycache__git
6 | .pyc
7 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Supplymental_material.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nagejacob/SpatiallyAdaptiveSSID/7e94712f2b38fd926b0b6e879e9d85f09e942cc4/Supplymental_material.pdf
--------------------------------------------------------------------------------
/dataset/DND_sRGB.py:
--------------------------------------------------------------------------------
1 | from dataset.base import dataset_path
2 | import h5py
3 | import glob
4 | import numpy as np
5 | import os
6 | import scipy.io as sio
7 | from torch.utils.data import Dataset
8 |
9 | dnd_path = os.path.join(dataset_path, 'DND')
10 |
11 | class DNDSrgbBenchmarkDataset(Dataset):
12 | def __init__(self):
13 | super(DNDSrgbBenchmarkDataset, self).__init__()
14 | self.imgs = []
15 | infos = h5py.File(os.path.join(dnd_path, 'info.mat'), 'r')
16 | info = infos['info']
17 | bb = info['boundingboxes']
18 | for i in range(50):
19 | filename = os.path.join(dnd_path, 'images_srgb', '%04d.mat' % (i + 1))
20 | img = h5py.File(filename, 'r')
21 | Inoisy = np.float32(np.array(img['InoisySRGB']).T)
22 | ref = bb[0][i]
23 | boxes = np.array(info[ref]).T
24 | for k in range(20):
25 | idx = [int(boxes[k, 0] - 1), int(boxes[k, 2]), int(boxes[k, 1] - 1), int(boxes[k, 3])]
26 | Inoisy_crop = Inoisy[idx[0]:idx[1], idx[2]:idx[3], :].copy()
27 | Inoisy_crop = np.transpose(Inoisy_crop, (2, 0, 1)) * 255.
28 |
29 | self.imgs.append({'L':Inoisy_crop})
30 |
31 | def __getitem__(self, index):
32 | return self.imgs[index]
33 |
34 | def __len__(self):
35 | return 1000
--------------------------------------------------------------------------------
/dataset/SIDD_sRGB.py:
--------------------------------------------------------------------------------
1 | '''
2 | We observe slightly better performance with training inputs in [0, 255] range than that in [0, 1],
3 | so we follow AP-BSN that do not normalize the input image from [0, 255] to [0, 1].
4 | '''
5 | from dataset.base import BaseTrainDataset, dataset_path
6 | import glob
7 | import numpy as np
8 | import os
9 | from PIL import Image
10 | import scipy.io as sio
11 | from torch.utils.data import Dataset
12 |
13 | sidd_path = os.path.join(dataset_path, 'SIDD')
14 |
15 | class SIDDSrgbTrainDataset(BaseTrainDataset):
16 | def __init__(self, patch_size, pin_memory):
17 | super(SIDDSrgbTrainDataset, self).__init__(sidd_path, patch_size, pin_memory)
18 |
19 | def __getitem__(self, index):
20 | index = index % len(self.img_paths)
21 |
22 | if self.pin_memory:
23 | img_L = self.imgs[index]['L']
24 | img_H = self.imgs[index]['H']
25 | else:
26 | img_path = self.img_paths[index]
27 | img_L = self._open_image(img_path['L'])
28 | img_H = self._open_image(img_path['H'])
29 |
30 | img_L, img_H = self.crop(img_L, img_H)
31 | img_L, img_H = self.augment(img_L, img_H)
32 |
33 | img_L, img_H = np.float32(img_L), np.float32(img_H)
34 | return {'L': img_L, 'H': img_H}
35 |
36 | def _get_img_paths(self, path):
37 | self.img_paths = []
38 | L_pattern = os.path.join(path, 'SIDD_Medium_Srgb/Data/*/*_NOISY_SRGB_*.PNG')
39 | L_paths = sorted(glob.glob(L_pattern))
40 | for L_path in L_paths:
41 | self.img_paths.append({'L': L_path, 'H': L_path.replace('NOISY', 'GT')})
42 |
43 | def _open_images(self):
44 | self.imgs = []
45 | for img_path in self.img_paths:
46 | img_L = self._open_image(img_path['L'])
47 | img_H = self._open_image(img_path['H'])
48 | self.imgs.append({'L': img_L, 'H': img_H})
49 |
50 | def _open_image(self, path):
51 | img = Image.open(path)
52 | img = np.asarray(img)
53 | img = np.transpose(img, (2, 0, 1))
54 | return img
55 |
56 |
57 | class SIDDSrgbValidationDataset(Dataset):
58 | def __init__(self):
59 | super(SIDDSrgbValidationDataset, self).__init__()
60 | self._open_images(sidd_path)
61 | self.n = self.noisy_block.shape[0]
62 | self.k = self.noisy_block.shape[1]
63 |
64 | def __getitem__(self, index):
65 | index_n = index // self.k
66 | index_k = index % self.k
67 |
68 | img_H = self.gt_block[index_n, index_k]
69 | img_H = np.float32(img_H)
70 | img_H = np.transpose(img_H, (2, 0, 1))
71 |
72 | img_L = self.noisy_block[index_n, index_k]
73 | img_L = np.float32(img_L)
74 | img_L = np.transpose(img_L, (2, 0, 1))
75 |
76 | return {'H':img_H, 'L':img_L}
77 |
78 | def __len__(self):
79 | return self.n * self.k
80 |
81 | def _open_images(self, path):
82 | mat = sio.loadmat(os.path.join(path, 'SIDD_Validation/ValidationNoisyBlocksSrgb.mat'))
83 | self.noisy_block = mat['ValidationNoisyBlocksSrgb']
84 | mat = sio.loadmat(os.path.join(path, 'SIDD_Validation/ValidationGtBlocksSrgb.mat'))
85 | self.gt_block = mat['ValidationGtBlocksSrgb']
86 |
87 |
88 | class SIDDSrgbBenchmarkDataset(Dataset):
89 | def __init__(self):
90 | super(SIDDSrgbBenchmarkDataset, self).__init__()
91 | self._open_images(sidd_path)
92 | self.n = self.noisy_block.shape[0]
93 | self.k = self.noisy_block.shape[1]
94 |
95 | def __getitem__(self, index):
96 | index_n = index // self.k
97 | index_k = index % self.k
98 |
99 | img_L = self.noisy_block[index_n, index_k]
100 | img_L = np.float32(img_L)
101 | img_L = np.transpose(img_L, (2, 0, 1))
102 |
103 | return {'L':img_L}
104 |
105 | def __len__(self):
106 | return self.n * self.k
107 |
108 | def _open_images(self, path):
109 | mat = sio.loadmat(os.path.join(path, 'SIDD_Benchmark/BenchmarkNoisyBlocksSrgb.mat'))
110 | self.noisy_block = mat['BenchmarkNoisyBlocksSrgb']
--------------------------------------------------------------------------------
/dataset/__init__.py:
--------------------------------------------------------------------------------
1 | from dataset.SIDD_sRGB import SIDDSrgbTrainDataset, SIDDSrgbValidationDataset, SIDDSrgbBenchmarkDataset
2 | from dataset.DND_sRGB import DNDSrgbBenchmarkDataset
--------------------------------------------------------------------------------
/dataset/base.py:
--------------------------------------------------------------------------------
1 | from abc import abstractmethod
2 | import numpy as np
3 | import random
4 | import socket
5 | import torch.utils.data as data
6 |
7 | hostname = socket.gethostname()
8 | if 'lijunyis-ubuntu' == hostname:
9 | dataset_path = '/home/nagejacob/Documents/datasets'
10 | else:
11 | raise OSError # dataset_path = 'path_to_dataset'
12 |
13 | # c, h, w numpy
14 | def aug_np3(img, flip_h, flip_w, transpose):
15 | if flip_h:
16 | img = img[:, ::-1, :]
17 | if flip_w:
18 | img = img[:, :, ::-1]
19 | if transpose:
20 | img = np.transpose(img, (0, 2, 1))
21 |
22 | return img
23 |
24 | def crop_np3(img, patch_size, position_h, position_w):
25 | return img[:, position_h:position_h+patch_size, position_w:position_w+patch_size]
26 |
27 | class BaseTrainDataset(data.Dataset):
28 | def __init__(self, path, patch_size, pin_memory):
29 | super(BaseTrainDataset, self).__init__()
30 | self.patch_size = patch_size
31 | self.pin_memory = pin_memory
32 | self._get_img_paths(path)
33 | if self.pin_memory:
34 | self._open_images()
35 |
36 | @abstractmethod
37 | def __getitem__(self, index):
38 | pass
39 |
40 | def __len__(self):
41 | return 100000
42 |
43 | @abstractmethod
44 | def _get_img_paths(self, path):
45 | pass
46 |
47 | @abstractmethod
48 | def _open_images(self):
49 | pass
50 |
51 | @abstractmethod
52 | def _open_image(self, path):
53 | pass
54 |
55 | def crop(self, img_L, img_H=None):
56 | C, H, W = img_L.shape
57 | position_H = random.randint(0, H - self.patch_size)
58 | position_W = random.randint(0, W - self.patch_size)
59 |
60 | patch_L = crop_np3(img_L, self.patch_size, position_H, position_W)
61 | if img_H is not None:
62 | patch_H = crop_np3(img_H, self.patch_size, position_H, position_W)
63 | return patch_L, patch_H
64 | else:
65 | return patch_L
66 |
67 | def augment(self, img_L, img_H=None):
68 | flip_h = random.random() > 0.5
69 | flip_w = random.random() > 0.5
70 | transpose = random.random() > 0.5
71 | img_L = aug_np3(img_L, flip_h, flip_w, transpose)
72 | if img_H is not None:
73 | img_H = aug_np3(img_H, flip_h, flip_w, transpose)
74 | return img_L, img_H
75 | else:
76 | return img_L
--------------------------------------------------------------------------------
/image_denoising.yaml:
--------------------------------------------------------------------------------
1 | name: /hdd/Documents/anaconda/image_denoising
2 | channels:
3 | - https://mirrors.hit.edu.cn/anaconda/cloud/pytorch
4 | - anaconda
5 | - https://mirrors.hit.edu.cn/anaconda/cloud/conda-forge
6 | - defaults
7 | dependencies:
8 | - _libgcc_mutex=0.1=main
9 | - _openmp_mutex=4.5=1_gnu
10 | - absl-py=1.0.0=pyhd8ed1ab_0
11 | - aiohttp=3.7.4.post0=py38h7f8727e_2
12 | - alsa-lib=1.2.3=h516909a_0
13 | - appdirs=1.4.4=pyh9f0ad1d_0
14 | - argon2-cffi=21.3.0=pyhd8ed1ab_0
15 | - argon2-cffi-bindings=21.2.0=py38h0a891b7_2
16 | - asttokens=2.0.8=pyhd8ed1ab_0
17 | - async-timeout=3.0.1=py_1000
18 | - attrs=21.4.0=pyhd8ed1ab_0
19 | - backcall=0.2.0=pyh9f0ad1d_0
20 | - backports=1.0=py_2
21 | - backports.functools_lru_cache=1.6.4=pyhd8ed1ab_0
22 | - beautifulsoup4=4.11.1=pyha770c72_0
23 | - blas=1.0=mkl
24 | - bleach=5.0.1=pyhd8ed1ab_0
25 | - blinker=1.4=py_1
26 | - blosc=1.21.0=h8c45485_0
27 | - bottleneck=1.3.4=py38hce1f21e_0
28 | - brotli=1.0.9=he6710b0_2
29 | - brotlipy=0.7.0=py38h27cfd23_1003
30 | - brunsli=0.1=h2531618_0
31 | - bzip2=1.0.8=h7b6447c_0
32 | - c-ares=1.17.1=h7f98852_1
33 | - ca-certificates=2022.12.7=ha878542_0
34 | - cachetools=5.0.0=pyhd8ed1ab_0
35 | - cairo=1.16.0=h6cf1ce9_1008
36 | - certifi=2022.12.7=pyhd8ed1ab_0
37 | - cffi=1.15.0=py38hd667e15_1
38 | - cfitsio=3.470=hf0d0db6_6
39 | - chardet=4.0.0=py38h578d9bd_3
40 | - charls=2.2.0=h2531618_0
41 | - charset-normalizer=2.0.4=pyhd3eb1b0_0
42 | - click=8.1.2=py38h578d9bd_0
43 | - cloudpickle=2.0.0=pyhd3eb1b0_0
44 | - colorama=0.4.4=pyhd3eb1b0_0
45 | - cryptography=36.0.0=py38h9ce1e76_0
46 | - cudatoolkit=11.3.1=h2bc3f7f_2
47 | - cycler=0.11.0=pyhd8ed1ab_0
48 | - cython=0.29.28=py38h295c915_0
49 | - cytoolz=0.11.0=py38h7b6447c_0
50 | - dask-core=2022.2.1=pyhd3eb1b0_0
51 | - dbus=1.13.6=h48d8840_2
52 | - decorator=5.1.1=pyhd8ed1ab_0
53 | - defusedxml=0.7.1=pyhd8ed1ab_0
54 | - docker-pycreds=0.4.0=py_0
55 | - einops=0.6.0=pyhd8ed1ab_0
56 | - entrypoints=0.4=pyhd8ed1ab_0
57 | - executing=1.1.0=pyhd8ed1ab_0
58 | - exifread=3.0.0=pyhd8ed1ab_0
59 | - expat=2.4.1=h9c3ff4c_0
60 | - ffmpeg=4.3=hf484d3e_0
61 | - flit-core=3.7.1=pyhd8ed1ab_0
62 | - fontconfig=2.13.1=hba837de_1005
63 | - fonttools=4.25.0=pyhd3eb1b0_0
64 | - freetype=2.11.0=h70c0345_0
65 | - fsspec=2022.2.0=pyhd3eb1b0_0
66 | - gettext=0.19.8.1=h0b5b191_1005
67 | - giflib=5.2.1=h7b6447c_0
68 | - gitdb=4.0.10=pyhd8ed1ab_0
69 | - gitpython=3.1.31=pyhd8ed1ab_0
70 | - glib=2.68.3=h9c3ff4c_0
71 | - glib-tools=2.68.3=h9c3ff4c_0
72 | - gmp=6.2.1=h2531618_2
73 | - gnutls=3.6.15=he1e5248_0
74 | - google-auth=2.6.5=pyh6c4a22f_0
75 | - google-auth-oauthlib=0.4.6=pyhd8ed1ab_0
76 | - graphite2=1.3.13=h58526e2_1001
77 | - grpcio=1.42.0=py38hce63b2e_0
78 | - gst-plugins-base=1.18.4=hf529b03_2
79 | - gstreamer=1.18.4=h76c114f_2
80 | - h5py=3.6.0=py38ha0f2276_0
81 | - harfbuzz=2.8.2=h83ec7ef_0
82 | - hdf5=1.10.6=hb1b8bf9_0
83 | - icu=68.1=h58526e2_0
84 | - idna=3.3=pyhd3eb1b0_0
85 | - imagecodecs=2021.8.26=py38h4cda21f_0
86 | - imageio=2.9.0=pyhd3eb1b0_0
87 | - importlib-metadata=4.11.3=py38h578d9bd_1
88 | - importlib_resources=5.9.0=pyhd8ed1ab_0
89 | - intel-openmp=2021.4.0=h06a4308_3561
90 | - ipykernel=5.5.5=py38hd0cf306_0
91 | - ipython=8.5.0=pyh41d4057_1
92 | - ipython_genutils=0.2.0=py_1
93 | - ipywidgets=8.0.2=pyhd8ed1ab_1
94 | - jasper=1.900.1=h07fcdf6_1006
95 | - jedi=0.18.1=pyhd8ed1ab_2
96 | - jinja2=3.1.2=pyhd8ed1ab_1
97 | - joblib=1.1.0=pyhd3eb1b0_0
98 | - jpeg=9d=h7f8727e_0
99 | - jsonschema=4.16.0=pyhd8ed1ab_0
100 | - jupyter=1.0.0=py38h578d9bd_7
101 | - jupyter_client=7.0.6=pyhd8ed1ab_0
102 | - jupyter_console=6.4.4=pyhd8ed1ab_0
103 | - jupyter_core=4.11.1=py38h578d9bd_0
104 | - jupyterlab_pygments=0.2.2=pyhd8ed1ab_0
105 | - jupyterlab_widgets=3.0.3=pyhd8ed1ab_0
106 | - jxrlib=1.1=h7b6447c_2
107 | - kiwisolver=1.4.2=py38h295c915_0
108 | - krb5=1.19.2=hcc1bbae_0
109 | - lame=3.100=h7b6447c_0
110 | - lcms2=2.12=h3be6417_0
111 | - ld_impl_linux-64=2.35.1=h7274673_9
112 | - lerc=3.0=h295c915_0
113 | - libaec=1.0.4=he6710b0_1
114 | - libblas=3.9.0=12_linux64_mkl
115 | - libcblas=3.9.0=12_linux64_mkl
116 | - libcurl=7.78.0=h2574ce0_0
117 | - libdeflate=1.8=h7f8727e_5
118 | - libedit=3.1.20191231=he28a2e2_2
119 | - libev=4.33=h516909a_1
120 | - libevent=2.1.10=hcdb4288_3
121 | - libffi=3.3=he6710b0_2
122 | - libgcc-ng=11.2.0=h1234567_0
123 | - libgfortran-ng=7.5.0=ha8ba4b0_17
124 | - libgfortran4=7.5.0=ha8ba4b0_17
125 | - libglib=2.68.3=h3e27bee_0
126 | - libgomp=11.2.0=h1234567_0
127 | - libiconv=1.16=h516909a_0
128 | - libidn2=2.3.2=h7f8727e_0
129 | - liblapack=3.9.0=12_linux64_mkl
130 | - liblapacke=3.9.0=12_linux64_mkl
131 | - libllvm11=11.1.0=hf817b99_2
132 | - libnghttp2=1.43.0=h812cca2_0
133 | - libogg=1.3.4=h7f98852_1
134 | - libopencv=4.4.0=py38_2
135 | - libopus=1.3.1=h7f98852_1
136 | - libpng=1.6.37=hbc83047_0
137 | - libpq=13.3=hd57d9b9_0
138 | - libprotobuf=3.20.3=he621ea3_0
139 | - libsodium=1.0.18=h36c2ea0_1
140 | - libssh2=1.9.0=ha56f1ee_6
141 | - libstdcxx-ng=12.1.0=ha89aaad_16
142 | - libtasn1=4.16.0=h27cfd23_0
143 | - libtiff=4.2.0=h85742a9_0
144 | - libunistring=0.9.10=h27cfd23_0
145 | - libuuid=2.32.1=h7f98852_1000
146 | - libuv=1.40.0=h7b6447c_0
147 | - libvorbis=1.3.7=h9c3ff4c_0
148 | - libwebp=1.2.2=h55f646e_0
149 | - libwebp-base=1.2.2=h7f8727e_0
150 | - libxcb=1.13=h7f98852_1003
151 | - libxkbcommon=1.0.3=he3ba5ed_0
152 | - libxml2=2.9.12=h72842e0_0
153 | - libzopfli=1.0.3=he6710b0_0
154 | - locket=0.2.1=py38h06a4308_2
155 | - lpips=0.1.3=pyhd8ed1ab_0
156 | - lz4-c=1.9.3=h295c915_1
157 | - mako=1.2.0=pyhd8ed1ab_1
158 | - markdown=3.3.6=pyhd8ed1ab_0
159 | - markupsafe=2.1.1=py38h0a891b7_1
160 | - matplotlib=3.5.1=py38h06a4308_1
161 | - matplotlib-base=3.5.1=py38ha18d171_1
162 | - matplotlib-inline=0.1.6=pyhd8ed1ab_0
163 | - mistune=0.8.4=py38h497a2fe_1005
164 | - mkl=2021.4.0=h06a4308_640
165 | - mkl-service=2.4.0=py38h7f8727e_0
166 | - mkl_fft=1.3.1=py38hd3c417c_0
167 | - mkl_random=1.2.2=py38h51133e4_0
168 | - multidict=5.2.0=py38h7f8727e_2
169 | - munkres=1.1.4=pyh9f0ad1d_0
170 | - mysql-common=8.0.25=ha770c72_0
171 | - mysql-libs=8.0.25=h935591d_0
172 | - natsort=7.1.1=pyhd3eb1b0_0
173 | - nbclient=0.5.13=pyhd8ed1ab_0
174 | - nbconvert=6.4.5=py38h578d9bd_0
175 | - nbformat=5.6.1=pyhd8ed1ab_0
176 | - ncurses=6.3=h7f8727e_2
177 | - nest-asyncio=1.5.5=pyhd8ed1ab_0
178 | - nettle=3.7.3=hbbd107a_1
179 | - networkx=2.7.1=pyhd3eb1b0_0
180 | - notebook=6.4.12=pyha770c72_0
181 | - nspr=4.30=h9c3ff4c_0
182 | - nss=3.67=hb5efdd6_0
183 | - numexpr=2.8.1=py38h807cd23_2
184 | - numpy=1.21.5=py38he7a7128_1
185 | - numpy-base=1.21.5=py38hf524024_1
186 | - oauthlib=3.2.0=pyhd8ed1ab_0
187 | - ocl-icd=2.3.1=h7f98852_0
188 | - ocl-icd-system=1.0.0=1
189 | - opencv=4.4.0=py38_2
190 | - openh264=2.1.1=h4ff587b_0
191 | - openjpeg=2.4.0=h3ad879b_0
192 | - openssl=1.1.1t=h7f8727e_0
193 | - packaging=21.3=pyhd3eb1b0_0
194 | - pandas=1.4.2=py38h295c915_0
195 | - pandoc=2.19.2=ha770c72_0
196 | - pandocfilters=1.5.0=pyhd8ed1ab_0
197 | - parso=0.8.3=pyhd8ed1ab_0
198 | - partd=1.2.0=pyhd3eb1b0_1
199 | - pathtools=0.1.2=py_1
200 | - pcre=8.45=h9c3ff4c_0
201 | - pexpect=4.8.0=pyh9f0ad1d_2
202 | - pickleshare=0.7.5=py_1003
203 | - pillow=9.0.1=py38h22f2fdc_0
204 | - pixman=0.40.0=h36c2ea0_0
205 | - pkgutil-resolve-name=1.3.10=pyhd8ed1ab_0
206 | - platformdirs=2.5.1=pyhd8ed1ab_0
207 | - prometheus_client=0.14.1=pyhd8ed1ab_0
208 | - prompt-toolkit=3.0.31=pyha770c72_0
209 | - prompt_toolkit=3.0.31=hd8ed1ab_0
210 | - protobuf=3.20.3=py38h6a678d5_0
211 | - psutil=5.9.0=py38h5eee18b_0
212 | - pthread-stubs=0.4=h36c2ea0_1001
213 | - ptyprocess=0.7.0=pyhd3deb0d_0
214 | - pure_eval=0.2.2=pyhd8ed1ab_0
215 | - py-opencv=4.4.0=py38h23f93f0_2
216 | - pyasn1=0.4.8=py_0
217 | - pyasn1-modules=0.2.7=py_0
218 | - pycparser=2.21=pyhd3eb1b0_0
219 | - pygments=2.13.0=pyhd8ed1ab_0
220 | - pyjwt=2.3.0=pyhd8ed1ab_1
221 | - pynvml=11.4.1=pyhd8ed1ab_0
222 | - pyopencl=2022.1.5=py38h514daf8_0
223 | - pyopenssl=22.0.0=pyhd3eb1b0_0
224 | - pyparsing=3.0.4=pyhd3eb1b0_0
225 | - pyqt=5.12.3=py38ha8c2ead_4
226 | - pyrsistent=0.18.1=py38h0a891b7_1
227 | - pysocks=1.7.1=py38h06a4308_0
228 | - python=3.8.13=h12debd9_0
229 | - python-dateutil=2.8.2=pyhd8ed1ab_0
230 | - python-fastjsonschema=2.16.2=pyhd8ed1ab_0
231 | - python_abi=3.8=2_cp38
232 | - pytools=2022.1.9=pyhd8ed1ab_0
233 | - pytorch=1.11.0=py3.8_cuda11.3_cudnn8.2.0_0
234 | - pytorch-mutex=1.0=cuda
235 | - pytz=2022.1=py38h06a4308_0
236 | - pyu2f=0.1.5=pyhd8ed1ab_0
237 | - pywavelets=1.3.0=py38h7f8727e_0
238 | - pyzmq=19.0.2=py38ha71036d_2
239 | - qt=5.12.9=hda022c4_4
240 | - qtconsole=5.3.2=pyhd8ed1ab_0
241 | - qtconsole-base=5.3.2=pyha770c72_0
242 | - qtpy=2.2.0=pyhd8ed1ab_0
243 | - readline=8.1.2=h7f8727e_1
244 | - requests=2.27.1=pyhd3eb1b0_0
245 | - requests-oauthlib=1.3.1=pyhd8ed1ab_0
246 | - rsa=4.8=pyhd8ed1ab_0
247 | - scikit-image=0.19.2=py38h51133e4_0
248 | - scikit-learn=1.1.1=py38h6a678d5_0
249 | - scipy=1.7.3=py38hc147768_0
250 | - send2trash=1.8.0=pyhd8ed1ab_0
251 | - sentry-sdk=1.19.1=pyhd8ed1ab_0
252 | - setproctitle=1.2.2=py38h0a891b7_2
253 | - setuptools=61.2.0=py38h06a4308_0
254 | - six=1.16.0=pyhd3eb1b0_1
255 | - smmap=3.0.5=pyh44b312d_0
256 | - snappy=1.1.8=he6710b0_0
257 | - soupsieve=2.3.2.post1=pyhd8ed1ab_0
258 | - sqlite=3.38.2=hc218d9a_0
259 | - stack_data=0.5.1=pyhd8ed1ab_0
260 | - tensorboard-data-server=0.6.0=py38h2b97feb_0
261 | - tensorboard-plugin-wit=1.8.1=pyhd8ed1ab_0
262 | - terminado=0.16.0=pyh41d4057_0
263 | - testpath=0.6.0=pyhd8ed1ab_0
264 | - threadpoolctl=2.2.0=pyh0d69192_0
265 | - tifffile=2021.7.2=pyhd3eb1b0_2
266 | - tk=8.6.11=h1ccaba5_0
267 | - toolz=0.11.2=pyhd3eb1b0_0
268 | - torchaudio=0.11.0=py38_cu113
269 | - torchvision=0.12.0=py38_cu113
270 | - tornado=6.1=py38h0a891b7_3
271 | - tqdm=4.63.0=pyhd3eb1b0_0
272 | - traitlets=5.4.0=pyhd8ed1ab_0
273 | - typing-extensions=4.1.1=hd3eb1b0_0
274 | - typing_extensions=4.1.1=pyh06a4308_0
275 | - urllib3=1.26.8=pyhd3eb1b0_0
276 | - wandb=0.14.2=pyhd8ed1ab_0
277 | - wcwidth=0.2.5=pyh9f0ad1d_2
278 | - webencodings=0.5.1=py_1
279 | - werkzeug=2.1.1=pyhd8ed1ab_0
280 | - wheel=0.37.1=pyhd3eb1b0_0
281 | - widgetsnbextension=4.0.3=pyhd8ed1ab_0
282 | - xorg-kbproto=1.0.7=h7f98852_1002
283 | - xorg-libice=1.0.10=h7f98852_0
284 | - xorg-libsm=1.2.3=hd9c2040_1000
285 | - xorg-libx11=1.7.2=h7f98852_0
286 | - xorg-libxau=1.0.9=h7f98852_0
287 | - xorg-libxdmcp=1.1.3=h7f98852_0
288 | - xorg-libxext=1.3.4=h7f98852_1
289 | - xorg-libxrender=0.9.10=h7f98852_1003
290 | - xorg-renderproto=0.11.1=h7f98852_1002
291 | - xorg-xextproto=7.3.0=h7f98852_1002
292 | - xorg-xproto=7.0.31=h7f98852_1007
293 | - xz=5.2.5=h7b6447c_0
294 | - yaml=0.2.5=h7b6447c_0
295 | - yarl=1.6.3=py38h27cfd23_0
296 | - zeromq=4.3.4=h9c3ff4c_1
297 | - zfp=0.5.5=h295c915_6
298 | - zipp=3.8.0=pyhd8ed1ab_0
299 | - zlib=1.2.13=h5eee18b_0
300 | - zstd=1.4.9=haebb681_0
301 | - pip:
302 | - astunparse==1.6.3
303 | - colour-demosaicing==0.2.1
304 | - colour-science==0.4.1
305 | - cupy-cuda113==10.4.0
306 | - fastrlock==0.8
307 | - flatbuffers==1.12
308 | - gast==0.4.0
309 | - google-pasta==0.2.0
310 | - guided-filter-pytorch==3.7.5
311 | - keras==2.9.0
312 | - keras-preprocessing==1.1.2
313 | - libclang==14.0.1
314 | - mat73==0.60
315 | - opt-einsum==3.3.0
316 | - pip==22.1.1
317 | - ptflops==0.6.9
318 | - pyqt5-sip==4.19.18
319 | - pyqtchart==5.12
320 | - pyqtwebengine==5.12.1
321 | - pyyaml==6.0
322 | - rawpy==0.17.1
323 | - tensorboard==2.9.1
324 | - tensorflow==2.9.1
325 | - tensorflow-estimator==2.9.0
326 | - tensorflow-io-gcs-filesystem==0.26.0
327 | - termcolor==1.1.0
328 | - thop==0.0.31-2005241907
329 | - timm==0.3.2
330 | - wrapt==1.14.1
331 | prefix: /hdd/Documents/anaconda/image_denoising
332 |
--------------------------------------------------------------------------------
/model/__init__.py:
--------------------------------------------------------------------------------
1 | from model.bnn import BNNModel
2 | from model.three_stage import ThreeStageModel
--------------------------------------------------------------------------------
/model/base.py:
--------------------------------------------------------------------------------
1 | from abc import abstractmethod
2 | import os
3 | import torch
4 | from torch.nn.parallel import DataParallel
5 | from utils.build import build
6 | from utils.io import log
7 |
8 | class BaseModel():
9 | def __init__(self, opt):
10 | self.opt = opt
11 | self.iter = 0 if 'iter' not in opt else opt['iter']
12 | self.networks = {}
13 | for network_opt in opt['networks']:
14 | Net = getattr(__import__('network'), network_opt['type'])
15 | net = build(Net, network_opt['args'])
16 | if 'path' in network_opt.keys():
17 | self.load_net(net, network_opt['path'])
18 | self.networks[network_opt['name']] = net
19 |
20 | @abstractmethod
21 | def train_step(self, data):
22 | pass
23 |
24 | @abstractmethod
25 | def validation_step(self, data):
26 | pass
27 |
28 | def data_parallel(self):
29 | for name in self.networks.keys():
30 | net = self.networks[name]
31 | net = net.cuda()
32 | net = DataParallel(net)
33 | self.networks[name] = net
34 |
35 | def save_net(self):
36 | for name, net in self.networks.items():
37 | if isinstance(net, DataParallel):
38 | net = net.module
39 | torch.save(net.state_dict(), os.path.join(self.opt['log_dir'], '%s_iter_%08d.pth' % (name, self.iter)))
40 |
41 | def load_net(self, net, path):
42 | state_dict = torch.load(path)
43 | net.load_state_dict(state_dict)
44 |
45 | @abstractmethod
46 | def save_model(self):
47 | pass
48 |
49 | @abstractmethod
50 | def load_model(self, path):
51 | pass
52 |
53 | def log(self):
54 | log(self.opt['log_file'], 'iter: %d, loss: %f\n' % (self.iter, self.loss.item()))
--------------------------------------------------------------------------------
/model/bnn.py:
--------------------------------------------------------------------------------
1 | from model.base import BaseModel
2 | import os
3 | import torch
4 | import torch.nn as nn
5 |
6 | class BNNModel(BaseModel):
7 | def __init__(self, opt):
8 | super(BNNModel, self).__init__(opt)
9 | self.criteron = nn.L1Loss(reduction='mean')
10 | self.optimizer = torch.optim.Adam(self.networks['BNN'].parameters(), lr=opt['lr'])
11 | self.scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(self.optimizer, opt['num_iters'])
12 |
13 | def train_step(self, data):
14 | input = data['L']
15 | self.networks['BNN'].train()
16 | output = self.networks['BNN'](input)
17 |
18 | self.loss = self.criteron(output, input)
19 | self.optimizer.zero_grad()
20 | self.loss.backward()
21 | self.optimizer.step()
22 | self.scheduler.step()
23 | self.iter += 1
24 |
25 | def validation_step(self, data):
26 | input = data['L']
27 | self.networks['BNN'].eval()
28 | with torch.no_grad():
29 | output = self.networks['BNN'](input)
30 |
31 | return output
32 |
33 | def save_model(self):
34 | save_dict = {'iter': self.iter,
35 | 'optimizer': self.optimizer.state_dict(),
36 | 'scheduler': self.scheduler.state_dict(),
37 | 'BNN': self.networks['BNN'].state_dict()}
38 | torch.save(save_dict, os.path.join(self.opt['log_dir'], 'model_iter_%08d.pth' % self.iter))
39 |
40 | def load_model(self, path):
41 | load_dict = torch.load(path)
42 | self.iter = load_dict['iter']
43 | self.optimizer.load_state_dict(load_dict['optimizer'])
44 | self.scheduler.load_state_dict(load_dict['scheduler'])
45 | self.networks['BNN'].load_state_dict(load_dict['BNN'])
46 |
47 |
48 |
--------------------------------------------------------------------------------
/model/three_stage.py:
--------------------------------------------------------------------------------
1 | from model.base import BaseModel
2 | import os
3 | import torch
4 | import torch.nn as nn
5 | from torch.nn.parallel import DataParallel
6 |
7 | def std(img, window_size=7):
8 | assert window_size % 2 == 1
9 | pad = window_size // 2
10 |
11 | # calculate std on the mean image of the color channels
12 | img = torch.mean(img, dim=1, keepdim=True)
13 | N, C, H, W = img.shape
14 | img = nn.functional.pad(img, [pad] * 4, mode='reflect')
15 | img = nn.functional.unfold(img, kernel_size=window_size)
16 | img = img.view(N, C, window_size * window_size, H, W)
17 | img = img - torch.mean(img, dim=2, keepdim=True)
18 | img = img * img
19 | img = torch.mean(img, dim=2, keepdim=True)
20 | img = torch.sqrt(img)
21 | img = img.squeeze(2)
22 | return img
23 |
24 | def generate_alpha(input, lower=1, upper=5):
25 | N, C, H, W = input.shape
26 | ratio = input.new_ones((N, 1, H, W)) * 0.5
27 | input_std = std(input)
28 | ratio[input_std < lower] = torch.sigmoid((input_std - lower))[input_std < lower]
29 | ratio[input_std > upper] = torch.sigmoid((input_std - upper))[input_std > upper]
30 | ratio = ratio.detach()
31 |
32 | return ratio
33 |
34 | class ThreeStageModel(BaseModel):
35 | def __init__(self, opt):
36 | super(ThreeStageModel, self).__init__(opt)
37 | self.stage = None
38 | self.criteron = nn.L1Loss(reduction='mean')
39 | self.optimizer_BNN = torch.optim.Adam(self.networks['BNN'].parameters(), lr=opt['lr'])
40 | self.scheduler_BNN = torch.optim.lr_scheduler.CosineAnnealingLR(self.optimizer_BNN, opt['BNN_iters'])
41 | self.optimizer_LAN = torch.optim.Adam(self.networks['LAN'].parameters(), lr=opt['lr'])
42 | self.scheduler_LAN = torch.optim.lr_scheduler.CosineAnnealingLR(self.optimizer_LAN, opt['LAN_iters'])
43 | self.optimizer_UNet = torch.optim.Adam(self.networks['UNet'].parameters(), lr=opt['lr'])
44 | self.scheduler_UNet = torch.optim.lr_scheduler.CosineAnnealingLR(self.optimizer_UNet, opt['UNet_iters'])
45 |
46 | def train_step(self, data):
47 | self.iter += 1
48 | self.update_stage()
49 |
50 | input = data['L']
51 |
52 | if self.stage == 'BNN':
53 | self.networks['BNN'].train()
54 | BNN = self.networks['BNN'](input)
55 | self.loss = self.criteron(BNN, input)
56 | self.optimizer_BNN.zero_grad()
57 | self.loss.backward()
58 | self.optimizer_BNN.step()
59 | self.scheduler_BNN.step()
60 |
61 | elif self.stage == 'LAN':
62 | self.networks['BNN'].eval()
63 | self.networks['LAN'].train()
64 | with torch.no_grad():
65 | BNN = self.networks['BNN'](input)
66 | LAN = self.networks['LAN'](input)
67 |
68 | # alpha = generate_alpha(BNN)
69 | # self.loss = self.criteron(BNN.detach() * (1 - alpha), LAN * (1 - alpha))
70 | self.loss = self.criteron(BNN, LAN)
71 | self.optimizer_LAN.zero_grad()
72 | self.loss.backward()
73 | self.optimizer_LAN.step()
74 | self.scheduler_LAN.step()
75 |
76 | elif self.stage == 'UNet':
77 | self.networks['BNN'].eval()
78 | self.networks['LAN'].eval()
79 | self.networks['UNet'].train()
80 | with torch.no_grad():
81 | BNN = self.networks['BNN'](input)
82 | LAN = self.networks['LAN'](input)
83 | UNet = self.networks['UNet'](input)
84 |
85 | alpha = generate_alpha(BNN)
86 | self.loss = self.criteron(BNN * (1 - alpha), UNet * (1 - alpha)) + self.criteron(LAN * alpha, UNet * alpha)
87 | self.optimizer_UNet.zero_grad()
88 | self.loss.backward()
89 | self.optimizer_UNet.step()
90 | self.scheduler_UNet.step()
91 |
92 |
93 | def validation_step(self, data):
94 | self.update_stage()
95 | input = data['L']
96 |
97 | if self.stage == 'BNN':
98 | self.networks['BNN'].eval()
99 | with torch.no_grad():
100 | output = self.networks['BNN'](input)
101 | elif self.stage == 'LAN':
102 | self.networks['LAN'].eval()
103 | with torch.no_grad():
104 | output = self.networks['LAN'](input)
105 | elif self.stage == 'UNet':
106 | self.networks['UNet'].eval()
107 | with torch.no_grad():
108 | output = self.networks['UNet'](input)
109 |
110 | return output
111 |
112 | def save_net(self):
113 | if self.stage == 'BNN':
114 | net = self.networks['BNN']
115 | elif self.stage == 'LAN':
116 | net = self.networks['LAN']
117 | elif self.stage == 'UNet':
118 | net = self.networks['UNet']
119 |
120 | if isinstance(net, DataParallel):
121 | net = net.module
122 | torch.save(net.state_dict(), os.path.join(self.opt['log_dir'], 'net_iter_%08d.pth' % self.iter))
123 |
124 | def save_model(self):
125 | if self.stage == 'BNN':
126 | save_dict = {'iter': self.iter,
127 | 'optimizer_BNN': self.optimizer_BNN.state_dict(),
128 | 'scheduler_BNN': self.scheduler_BNN.state_dict(),
129 | 'BNN': self.networks['BNN'].state_dict()}
130 | elif self.stage == 'LAN':
131 | save_dict = {'iter': self.iter,
132 | 'optimizer_LAN': self.optimizer_LAN.state_dict(),
133 | 'scheduler_LAN': self.scheduler_LAN.state_dict(),
134 | 'BNN': self.networks['BNN'].state_dict(),
135 | 'LAN': self.networks['LAN'].state_dict()}
136 | elif self.stage == 'UNet':
137 | save_dict = {'iter': self.iter,
138 | 'optimizer_UNet': self.optimizer_UNet.state_dict(),
139 | 'scheduler_UNet': self.scheduler_UNet.state_dict(),
140 | 'BNN': self.networks['BNN'].state_dict(),
141 | 'LAN': self.networks['LAN'].state_dict(),
142 | 'UNet': self.networks['UNet'].state_dict()}
143 | torch.save(save_dict, os.path.join(self.opt['log_dir'], 'model_iter_%08d.pth' % self.iter))
144 |
145 | def load_model(self, path):
146 | load_dict = torch.load(path)
147 | self.iter = load_dict['iter']
148 | self.update_stage()
149 | if self.stage == 'BNN':
150 | self.optimizer_BNN.load_state_dict(load_dict['optimizer_BNN'])
151 | self.scheduler_BNN.load_state_dict(load_dict['scheduler_BNN'])
152 | self.networks['BNN'].load_state_dict(load_dict['BNN'])
153 | elif self.stage == 'LAN':
154 | self.optimizer_LAN.load_state_dict(load_dict['optimizer_LAN'])
155 | self.scheduler_LAN.load_state_dict(load_dict['scheduler_LAN'])
156 | self.networks['BNN'].load_state_dict(load_dict['BNN'])
157 | self.networks['LAN'].load_state_dict(load_dict['LAN'])
158 | elif self.stage == 'UNet':
159 | self.optimizer_UNet.load_state_dict(load_dict['optimizer_UNet'])
160 | self.scheduler_UNet.load_state_dict(load_dict['scheduler_UNet'])
161 | self.networks['BNN'].load_state_dict(load_dict['BNN'])
162 | self.networks['LAN'].load_state_dict(load_dict['LAN'])
163 | self.networks['UNet'].load_state_dict(load_dict['UNet'])
164 | else:
165 | raise NotImplementedError
166 |
167 | def update_stage(self):
168 | if self.iter <= self.opt['BNN_iters']:
169 | self.stage = 'BNN'
170 | elif self.iter <= self.opt['BNN_iters'] + self.opt['LAN_iters']:
171 | self.stage = 'LAN'
172 | else:
173 | self.stage = 'UNet'
174 |
--------------------------------------------------------------------------------
/network/__init__.py:
--------------------------------------------------------------------------------
1 | from network.bnn import BNN
2 | from network.lan import LAN
3 | from network.unet import UNet
--------------------------------------------------------------------------------
/network/bnn.py:
--------------------------------------------------------------------------------
1 | '''
2 | The code of BNN is modified from https://github.com/COMP6248-Reproducability-Challenge/selfsupervised-denoising/blob/master-with-report/ssdn/ssdn/models/noise_network.py
3 | '''
4 | import torch
5 | import torch.nn as nn
6 | from typing import Tuple
7 |
8 | def rotate(x, angle):
9 | """Rotate images by 90 degrees clockwise. Can handle any 2D data format.
10 | Args:
11 | x (Tensor): Image or batch of images.
12 | angle (int): Clockwise rotation angle in multiples of 90.
13 | data_format (str, optional): Format of input image data, e.g. BCHW,
14 | HWC. Defaults to BCHW.
15 | Returns:
16 | Tensor: Copy of tensor with rotation applied.
17 | """
18 | h_dim, w_dim = 2, 3
19 |
20 | if angle == 0:
21 | return x
22 | elif angle == 90:
23 | return x.flip(w_dim).transpose(h_dim, w_dim)
24 | elif angle == 180:
25 | return x.flip(w_dim).flip(h_dim)
26 | elif angle == 270:
27 | return x.flip(h_dim).transpose(h_dim, w_dim)
28 | else:
29 | raise NotImplementedError("Must be rotation divisible by 90 degrees")
30 |
31 | class Crop2d(nn.Module):
32 | """Crop input using slicing. Assumes BCHW data.
33 |
34 | Args:
35 | crop (Tuple[int, int, int, int]): Amounts to crop from each side of the image.
36 | Tuple is treated as [left, right, top, bottom]/
37 | """
38 |
39 | def __init__(self, crop: Tuple[int, int, int, int]):
40 | super().__init__()
41 | self.crop = crop
42 | assert len(crop) == 4
43 |
44 | def forward(self, x):
45 | (left, right, top, bottom) = self.crop
46 | x0, x1 = left, x.shape[-1] - right
47 | y0, y1 = top, x.shape[-2] - bottom
48 | return x[:, :, y0:y1, x0:x1]
49 |
50 |
51 | class Shift2d(nn.Module):
52 | """Shift an image in either or both of the vertical and horizontal axis by first
53 | zero padding on the opposite side that the image is shifting towards before
54 | cropping the side being shifted towards.
55 |
56 | Args:
57 | shift (Tuple[int, int]): Tuple of vertical and horizontal shift. Positive values
58 | shift towards right and bottom, negative values shift towards left and top.
59 | """
60 |
61 | def __init__(self, shift: Tuple[int, int]):
62 | super().__init__()
63 | self.shift = shift
64 | vert, horz = self.shift
65 | y_a, y_b = abs(vert), 0
66 | x_a, x_b = abs(horz), 0
67 | if vert < 0:
68 | y_a, y_b = y_b, y_a
69 | if horz < 0:
70 | x_a, x_b = x_b, x_a
71 | # Order : Left, Right, Top Bottom
72 | self.pad = nn.ZeroPad2d((x_a, x_b, y_a, y_b))
73 | self.crop = Crop2d((x_b, x_a, y_b, y_a))
74 | self.shift_block = nn.Sequential(self.pad, self.crop)
75 |
76 | def forward(self, x):
77 | return self.shift_block(x)
78 |
79 | class ShiftConv2d(nn.Conv2d):
80 | def __init__(self, *args, **kwargs):
81 | """Custom convolution layer as defined by Laine et al. for restricting the
82 | receptive field of a convolution layer to only be upwards. For a h × w kernel,
83 | a downwards offset of k = [h/2] pixels is used. This is applied as a k sized pad
84 | to the top of the input before applying the convolution. The bottom k rows are
85 | cropped out for output.
86 | """
87 | super().__init__(*args, **kwargs)
88 | self.shift_size = (self.kernel_size[0] // 2, 0)
89 | # Use individual layers of shift for wrapping conv with shift
90 | shift = Shift2d(self.shift_size)
91 | self.pad = shift.pad
92 | self.crop = shift.crop
93 |
94 | def forward(self, x):
95 | x = self.pad(x)
96 | x = super().forward(x)
97 | x = self.crop(x)
98 | return x
99 |
100 |
101 | class BNN(nn.Module):
102 | def __init__(self, blindspot, in_ch=3, out_ch=3, dim=48):
103 | super(BNN, self).__init__()
104 | in_channels = in_ch
105 | out_channels = out_ch
106 | self.blindspot = blindspot
107 |
108 | ####################################
109 | # Encode Blocks
110 | ####################################
111 |
112 | # Layers: enc_conv0, enc_conv1, pool1
113 | self.encode_block_1 = nn.Sequential(
114 | ShiftConv2d(in_channels, dim, 3, stride=1, padding=1),
115 | nn.LeakyReLU(negative_slope=0.1, inplace=True),
116 | ShiftConv2d(dim, dim, 3, padding=1),
117 | nn.LeakyReLU(negative_slope=0.1, inplace=True),
118 | Shift2d((1, 0)),
119 | nn.MaxPool2d(2)
120 | )
121 |
122 | # Layers: enc_conv(i), pool(i); i=2..5
123 | def _encode_block_2_3_4_5() -> nn.Module:
124 | return nn.Sequential(
125 | ShiftConv2d(dim, dim, 3, stride=1, padding=1),
126 | nn.LeakyReLU(negative_slope=0.1, inplace=True),
127 | Shift2d((1, 0)),
128 | nn.MaxPool2d(2)
129 | )
130 |
131 | # Separate instances of same encode module definition created
132 | self.encode_block_2 = _encode_block_2_3_4_5()
133 | self.encode_block_3 = _encode_block_2_3_4_5()
134 | self.encode_block_4 = _encode_block_2_3_4_5()
135 | self.encode_block_5 = _encode_block_2_3_4_5()
136 |
137 | # Layers: enc_conv6
138 | self.encode_block_6 = nn.Sequential(
139 | ShiftConv2d(dim, dim, 3, stride=1, padding=1),
140 | nn.LeakyReLU(negative_slope=0.1, inplace=True),
141 | )
142 |
143 | ####################################
144 | # Decode Blocks
145 | ####################################
146 | # Layers: upsample5
147 | self.decode_block_6 = nn.Sequential(nn.Upsample(scale_factor=2, mode="nearest"))
148 |
149 | # Layers: dec_conv5a, dec_conv5b, upsample4
150 | self.decode_block_5 = nn.Sequential(
151 | ShiftConv2d(2 * dim, 2 * dim, 3, stride=1, padding=1),
152 | nn.LeakyReLU(negative_slope=0.1, inplace=True),
153 | ShiftConv2d(2 * dim, 2 * dim, 3, stride=1, padding=1),
154 | nn.LeakyReLU(negative_slope=0.1, inplace=True),
155 | nn.Upsample(scale_factor=2, mode="nearest"),
156 | )
157 |
158 | # Layers: dec_deconv(i)a, dec_deconv(i)b, upsample(i-1); i=4..2
159 | def _decode_block_4_3_2() -> nn.Module:
160 | return nn.Sequential(
161 | ShiftConv2d(3 * dim, 2 * dim, 3, stride=1, padding=1),
162 | nn.LeakyReLU(negative_slope=0.1, inplace=True),
163 | ShiftConv2d(2 * dim, 2 * dim, 3, stride=1, padding=1),
164 | nn.LeakyReLU(negative_slope=0.1, inplace=True),
165 | nn.Upsample(scale_factor=2, mode="nearest"),
166 | )
167 |
168 | # Separate instances of same decode module definition created
169 | self.decode_block_4 = _decode_block_4_3_2()
170 | self.decode_block_3 = _decode_block_4_3_2()
171 | self.decode_block_2 = _decode_block_4_3_2()
172 |
173 | # Layers: dec_conv1a, dec_conv1b, dec_conv1c,
174 | self.decode_block_1 = nn.Sequential(
175 | ShiftConv2d(2 * dim + in_channels, 2 * dim, 3, stride=1, padding=1),
176 | nn.LeakyReLU(negative_slope=0.1, inplace=True),
177 | ShiftConv2d(2 * dim, 2 * dim, 3, stride=1, padding=1),
178 | nn.LeakyReLU(negative_slope=0.1, inplace=True),
179 | )
180 |
181 | ####################################
182 | # Output Block
183 | ####################################
184 |
185 | # Shift blindspot pixel down
186 | self.shift = Shift2d(((self.blindspot + 1) // 2, 0))
187 |
188 | # nin_a,b,c, linear_act
189 | self.output_conv = ShiftConv2d(2 * dim, out_channels, 1)
190 | self.output_block = nn.Sequential(
191 | ShiftConv2d(8 * dim, 8 * dim, 1),
192 | nn.LeakyReLU(negative_slope=0.1, inplace=True),
193 | ShiftConv2d(8 * dim, 2 * dim, 1),
194 | nn.LeakyReLU(negative_slope=0.1, inplace=True),
195 | self.output_conv,
196 | )
197 |
198 | # Initialize weights
199 | self.init_weights()
200 |
201 | def init_weights(self):
202 | """Initializes weights using Kaiming He et al. (2015).
203 |
204 | Only convolution layers have learnable weights. All convolutions use a leaky
205 | relu activation function (negative_slope = 0.1) except the last which is just
206 | a linear output.
207 | """
208 | with torch.no_grad():
209 | self._init_weights()
210 |
211 | def _init_weights(self):
212 | for m in self.modules():
213 | if isinstance(m, nn.Conv2d):
214 | nn.init.kaiming_normal_(m.weight.data, a=0.1)
215 | m.bias.data.zero_()
216 | # Initialise last output layer
217 | nn.init.kaiming_normal_(self.output_conv.weight.data, nonlinearity="linear")
218 |
219 | def forward(self, x, shift=None):
220 | if shift is not None:
221 | self.shift = Shift2d((shift, 0))
222 | else:
223 | self.shift = Shift2d(((self.blindspot + 1) // 2, 0))
224 |
225 | rotated = [rotate(x, rot) for rot in (0, 90, 180, 270)]
226 | x = torch.cat((rotated), dim=0)
227 |
228 | # Encoder
229 | pool1 = self.encode_block_1(x)
230 | pool2 = self.encode_block_2(pool1)
231 | pool3 = self.encode_block_3(pool2)
232 | pool4 = self.encode_block_4(pool3)
233 | pool5 = self.encode_block_5(pool4)
234 | encoded = self.encode_block_6(pool5)
235 |
236 | # Decoder
237 | upsample5 = self.decode_block_6(encoded)
238 | concat5 = torch.cat((upsample5, pool4), dim=1)
239 | upsample4 = self.decode_block_5(concat5)
240 | concat4 = torch.cat((upsample4, pool3), dim=1)
241 | upsample3 = self.decode_block_4(concat4)
242 | concat3 = torch.cat((upsample3, pool2), dim=1)
243 | upsample2 = self.decode_block_3(concat3)
244 | concat2 = torch.cat((upsample2, pool1), dim=1)
245 | upsample1 = self.decode_block_2(concat2)
246 | concat1 = torch.cat((upsample1, x), dim=1)
247 | x = self.decode_block_1(concat1)
248 |
249 | # Apply shift
250 | shifted = self.shift(x)
251 | # Unstack, rotate and combine
252 | rotated_batch = torch.chunk(shifted, 4, dim=0)
253 | aligned = [
254 | rotate(rotated, rot)
255 | for rotated, rot in zip(rotated_batch, (0, 270, 180, 90))
256 | ]
257 | x = torch.cat(aligned, dim=1)
258 |
259 | x = self.output_block(x)
260 |
261 | return x
262 |
263 | @staticmethod
264 | def input_wh_mul() -> int:
265 | """Multiple that both the width and height dimensions of an input must be to be
266 | processed by the network. This is devised from the number of pooling layers that
267 | reduce the input size.
268 |
269 | Returns:
270 | int: Dimension multiplier
271 | """
272 | max_pool_layers = 5
273 | return 2 ** max_pool_layers
--------------------------------------------------------------------------------
/network/lan.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 |
4 | class CALayer(nn.Module):
5 | def __init__(self, channel=64, reduction=16):
6 | super(CALayer, self).__init__()
7 |
8 | self.avg_pool = nn.AdaptiveAvgPool2d(1)
9 | self.conv_du = nn.Sequential(
10 | nn.Conv2d(channel, channel // reduction, 1, padding=0, bias=True),
11 | nn.ReLU(inplace=True),
12 | nn.Conv2d(channel // reduction, channel, 1, padding=0, bias=True),
13 | nn.Sigmoid()
14 | )
15 |
16 | def forward(self, x):
17 | y = self.avg_pool(x)
18 | y = self.conv_du(y)
19 | return x * y
20 |
21 | class RB(nn.Module):
22 | def __init__(self, filters):
23 | super(RB, self).__init__()
24 | self.conv1 = nn.Conv2d(filters, filters, 1)
25 | self.act = nn.ReLU()
26 | self.conv2 = nn.Conv2d(filters, filters, 1)
27 | self.cuca = CALayer(channel=filters)
28 |
29 | def forward(self, x):
30 | c0 = x
31 | x = self.conv1(x)
32 | x = self.act(x)
33 | x = self.conv2(x)
34 | out = self.cuca(x)
35 | return out + c0
36 |
37 | class NRB(nn.Module):
38 | def __init__(self, n, filters):
39 | super(NRB, self).__init__()
40 | nets = []
41 | for i in range(n):
42 | nets.append(RB(filters))
43 | self.body = nn.Sequential(*nets)
44 | self.tail = nn.Conv2d(filters, filters, 1)
45 |
46 | def forward(self, x):
47 | return x + self.tail(self.body(x))
48 |
49 |
50 | class LAN(nn.Module):
51 | def __init__(self, blindspot, in_ch=3, out_ch=None, rbs=6):
52 | super(LAN, self).__init__()
53 | self.receptive_feild = blindspot
54 | assert self.receptive_feild % 2 == 1
55 | self.in_ch = in_ch
56 | self.out_ch = self.in_ch if out_ch is None else out_ch
57 | self.mid_ch = 64
58 | self.rbs = rbs
59 |
60 | layers = []
61 | layers.append(nn.Conv2d(self.in_ch, self.mid_ch, 1))
62 | layers.append(nn.ReLU())
63 |
64 | for i in range(self.receptive_feild // 2):
65 | layers.append(nn.Conv2d(self.mid_ch, self.mid_ch, 3, 1, 1))
66 | layers.append(nn.ReLU())
67 |
68 | layers.append(NRB(self.rbs, self.mid_ch))
69 | layers.append(nn.Conv2d(self.mid_ch, self.out_ch, 1))
70 |
71 | self.conv = nn.Sequential(*layers)
72 |
73 | def forward(self, x):
74 | return self.conv(x)
75 |
--------------------------------------------------------------------------------
/network/unet.py:
--------------------------------------------------------------------------------
1 | '''
2 | U-Net is also modified from https://github.com/COMP6248-Reproducability-Challenge/selfsupervised-denoising/blob/master-with-report/ssdn/ssdn/models/noise_network.py
3 | '''
4 | import torch
5 | import torch.nn as nn
6 | from typing import Tuple
7 |
8 | class UNet(nn.Module):
9 | def __init__(self, in_ch=3, out_ch=3, zero_output=False, dim=48):
10 | super(UNet, self).__init__()
11 | self.zero_output = zero_output
12 | in_channels = in_ch
13 | out_channels = out_ch
14 |
15 | ####################################
16 | # Encode Blocks
17 | ####################################
18 |
19 | # Layers: enc_conv0, enc_conv1, pool1
20 | self.encode_block_1 = nn.Sequential(
21 | nn.Conv2d(in_channels, dim, 3, stride=1, padding=1),
22 | nn.LeakyReLU(negative_slope=0.1, inplace=True),
23 | nn.Conv2d(dim, dim, 3, padding=1),
24 | nn.LeakyReLU(negative_slope=0.1, inplace=True),
25 | nn.MaxPool2d(2)
26 | )
27 |
28 | # Layers: enc_conv(i), pool(i); i=2..5
29 | def _encode_block_2_3_4_5() -> nn.Module:
30 | return nn.Sequential(
31 | nn.Conv2d(dim, dim, 3, stride=1, padding=1),
32 | nn.LeakyReLU(negative_slope=0.1, inplace=True),
33 | nn.MaxPool2d(2)
34 | )
35 |
36 | # Separate instances of same encode module definition created
37 | self.encode_block_2 = _encode_block_2_3_4_5()
38 | self.encode_block_3 = _encode_block_2_3_4_5()
39 | self.encode_block_4 = _encode_block_2_3_4_5()
40 | self.encode_block_5 = _encode_block_2_3_4_5()
41 |
42 | # Layers: enc_conv6
43 | self.encode_block_6 = nn.Sequential(
44 | nn.Conv2d(dim, dim, 3, stride=1, padding=1),
45 | nn.LeakyReLU(negative_slope=0.1, inplace=True),
46 | )
47 |
48 | ####################################
49 | # Decode Blocks
50 | ####################################
51 | # Layers: upsample5
52 | self.decode_block_6 = nn.Sequential(nn.Upsample(scale_factor=2, mode="nearest"))
53 |
54 | # Layers: dec_conv5a, dec_conv5b, upsample4
55 | self.decode_block_5 = nn.Sequential(
56 | nn.Conv2d(dim * 2, dim * 2, 3, stride=1, padding=1),
57 | nn.LeakyReLU(negative_slope=0.1, inplace=True),
58 | nn.Conv2d(dim * 2, dim * 2, 3, stride=1, padding=1),
59 | nn.LeakyReLU(negative_slope=0.1, inplace=True),
60 | nn.Upsample(scale_factor=2, mode="nearest"),
61 | )
62 |
63 | # Layers: dec_deconv(i)a, dec_deconv(i)b, upsample(i-1); i=4..2
64 | def _decode_block_4_3_2() -> nn.Module:
65 | return nn.Sequential(
66 | nn.Conv2d(dim * 3, dim * 2, 3, stride=1, padding=1),
67 | nn.LeakyReLU(negative_slope=0.1, inplace=True),
68 | nn.Conv2d(dim * 2, dim * 2, 3, stride=1, padding=1),
69 | nn.LeakyReLU(negative_slope=0.1, inplace=True),
70 | nn.Upsample(scale_factor=2, mode="nearest"),
71 | )
72 |
73 | # Separate instances of same decode module definition created
74 | self.decode_block_4 = _decode_block_4_3_2()
75 | self.decode_block_3 = _decode_block_4_3_2()
76 | self.decode_block_2 = _decode_block_4_3_2()
77 |
78 | # Layers: dec_conv1a, dec_conv1b, dec_conv1c,
79 | self.decode_block_1 = nn.Sequential(
80 | nn.Conv2d(dim * 2 + in_channels, dim * 2, 3, stride=1, padding=1),
81 | nn.LeakyReLU(negative_slope=0.1, inplace=True),
82 | nn.Conv2d(dim * 2, dim * 2, 3, stride=1, padding=1),
83 | nn.LeakyReLU(negative_slope=0.1, inplace=True),
84 | )
85 |
86 | ####################################
87 | # Output Block
88 | ####################################
89 |
90 |
91 | # nin_a,b,c, linear_act
92 | self.output_conv = nn.Conv2d(dim * 2, out_channels, 1)
93 |
94 | # Initialize weights
95 | self.init_weights()
96 |
97 | def init_weights(self):
98 | """Initializes weights using Kaiming He et al. (2015).
99 |
100 | Only convolution layers have learnable weights. All convolutions use a leaky
101 | relu activation function (negative_slope = 0.1) except the last which is just
102 | a linear output.
103 | """
104 | with torch.no_grad():
105 | self._init_weights()
106 |
107 | def _init_weights(self):
108 | for m in self.modules():
109 | if isinstance(m, nn.Conv2d):
110 | nn.init.kaiming_normal_(m.weight.data, a=0.1)
111 | m.bias.data.zero_()
112 |
113 | # Initialise last output layer
114 | if self.zero_output:
115 | self.output_conv.weight.zero_()
116 | else:
117 | nn.init.kaiming_normal_(self.output_conv.weight.data, nonlinearity="linear")
118 |
119 | def forward(self, x):
120 |
121 | # Encoder
122 | pool1 = self.encode_block_1(x)
123 | pool2 = self.encode_block_2(pool1)
124 | pool3 = self.encode_block_3(pool2)
125 | pool4 = self.encode_block_4(pool3)
126 | pool5 = self.encode_block_5(pool4)
127 | encoded = self.encode_block_6(pool5)
128 |
129 | # Decoder
130 | upsample5 = self.decode_block_6(encoded)
131 | concat5 = torch.cat((upsample5, pool4), dim=1)
132 | upsample4 = self.decode_block_5(concat5)
133 | concat4 = torch.cat((upsample4, pool3), dim=1)
134 | upsample3 = self.decode_block_4(concat4)
135 | concat3 = torch.cat((upsample3, pool2), dim=1)
136 | upsample2 = self.decode_block_3(concat3)
137 | concat2 = torch.cat((upsample2, pool1), dim=1)
138 | upsample1 = self.decode_block_2(concat2)
139 | concat1 = torch.cat((upsample1, x), dim=1)
140 | x = self.decode_block_1(concat1)
141 |
142 | x = self.output_conv(x)
143 |
144 | return x
145 |
146 | @staticmethod
147 | def input_wh_mul() -> int:
148 | """Multiple that both the width and height dimensions of an input must be to be
149 | processed by the network. This is devised from the number of pooling layers that
150 | reduce the input size.
151 |
152 | Returns:
153 | int: Dimension multiplier
154 | """
155 | max_pool_layers = 5
156 | return 2 ** max_pool_layers
--------------------------------------------------------------------------------
/option/bnn.json:
--------------------------------------------------------------------------------
1 | {
2 | // model
3 | "model": "BNNModel",
4 | // net
5 | "networks": [{
6 | "name": "BNN",
7 | "type": "BNN",
8 | "args": {
9 | "blindspot": 9
10 | }
11 | ,"path": "/home/nagejacob/Documents/codes/SpatiallyAdaptiveSSID/pretrained_models/BNN.pth"
12 | }],
13 | // datasets
14 | "train_datasets": [{
15 | "type": "SIDDSrgbTrainDataset",
16 | "args": {
17 | "patch_size": 256,
18 | "pin_memory": true
19 | },
20 | "batch_size": 8
21 | }],
22 | "validation_datasets": [{
23 | "type": "SIDDSrgbValidationDataset",
24 | "args": {}
25 | }],
26 | // training parameters
27 | "lr": 3e-4,
28 | "print_every": 1000000,
29 | "save_every": 10000,
30 | "validate_every": 10000,
31 | "num_iters": 400000,
32 | "log_dir": "logs",
33 | "log_file": "logs/log.out"
34 | // , "resume_from": ""
35 | }
36 |
--------------------------------------------------------------------------------
/option/three_stage.json:
--------------------------------------------------------------------------------
1 | {
2 | // model
3 | "model": "ThreeStageModel",
4 | "iter": 1200000,
5 | // net
6 | "networks":[{
7 | "name": "BNN",
8 | "type": "BNN",
9 | "args": {
10 | "blindspot": 9
11 | }
12 | // , "path": "/home/nagejacob/Documents/codes/SpatiallyAdaptiveSSID/pretrained_models/BNN.pth"
13 | }, {
14 | "name": "LAN",
15 | "type": "LAN",
16 | "args": {
17 | "blindspot": 3
18 | }
19 | // , "path": "/home/nagejacob/Documents/codes/SpatiallyAdaptiveSSID/pretrained_models/LAN.pth"
20 | }, {
21 | "name": "UNet",
22 | "type": "UNet",
23 | "args": {}
24 | , "path": "/home/nagejacob/Documents/codes/SpatiallyAdaptiveSSID/pretrained_models/UNet.pth"
25 | }],
26 | // datasets
27 | "train_datasets": [{
28 | "type": "SIDDSrgbTrainDataset",
29 | "args": {
30 | "patch_size": 256,
31 | "pin_memory": true
32 | },
33 | "batch_size": 8
34 | }],
35 | "validation_datasets": [{
36 | "type": "SIDDSrgbValidationDataset",
37 | "args": {}
38 | }],
39 | // training parameters
40 | "lr": 3e-4,
41 | "print_every": 10000000,
42 | "save_every": 10000,
43 | "validate_every": 10000,
44 | "BNN_iters": 400000,
45 | "LAN_iters": 400000,
46 | "UNet_iters": 400000,
47 | "num_iters": 1200000,
48 | "log_dir": "logs",
49 | "log_file": "logs/log.out"
50 | // , "resume_from": ""
51 | }
52 |
--------------------------------------------------------------------------------
/pretrained_models/BNN.pth:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nagejacob/SpatiallyAdaptiveSSID/7e94712f2b38fd926b0b6e879e9d85f09e942cc4/pretrained_models/BNN.pth
--------------------------------------------------------------------------------
/pretrained_models/LAN.pth:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nagejacob/SpatiallyAdaptiveSSID/7e94712f2b38fd926b0b6e879e9d85f09e942cc4/pretrained_models/LAN.pth
--------------------------------------------------------------------------------
/pretrained_models/UNet.pth:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nagejacob/SpatiallyAdaptiveSSID/7e94712f2b38fd926b0b6e879e9d85f09e942cc4/pretrained_models/UNet.pth
--------------------------------------------------------------------------------
/readme.md:
--------------------------------------------------------------------------------
1 | # Spatially Adaptive Self-Supervised Learning for Real-World Image Denoising
2 | The source code for paper "[Spatially Adaptive Self-Supervised Learning for Real-World Image Denoising](https://arxiv.org/pdf/2303.14934.pdf)" (CVPR 2023)
3 |
4 | ## Usage
5 | ### Datasets
6 | Download [SIDD](https://www.eecs.yorku.ca/~kamel/sidd/dataset.php) and [DND](https://noise.visinf.tu-darmstadt.de/) datasets, and modify `dataset_path` in `dataset/base.py` accordingly.
7 | ```
8 | |- dataset_path
9 | |- SIDD
10 | |- SIDD_Medium_Srgb
11 | |- Data
12 | |- 0001_001_S6_00100_00060_3200_L
13 | |- 0002_001_S6_00100_00020_3200_N
14 | |- ...
15 | |- SIDD_Validation
16 | |- ValidationNoisyBlocksSrgb.mat
17 | |- ValidationGtBlocksSrgb.mat
18 | |- SIDD_Benchmark
19 | |- BenchmarkNoisyBlocksSrgb.mat
20 | |- DND
21 | |- info.mat
22 | |- images_srgb
23 | ```
24 |
25 | ### Validation
26 | Validate on SIDD Validation dataset,
27 | ```
28 | cd validate
29 | python validate_SIDD.py
30 | ```
31 |
32 | ### Training (removed due to confidentiality agreement, see [here](https://github.com/nagejacob/SpatiallyAdaptiveSSID/tree/731adb9b5dcc3a860d207436f5fee6f794b2e5f4))
33 | Training on SIDD Medium dataset,
34 | ```
35 | sh train.sh
36 | ```
37 |
38 | ## Citation
39 | If you find our work useful in your research or publication, please cite:
40 | ```
41 | @inproceedings{li2023spatially,
42 | title={Spatially Adaptive Self-Supervised Learning for Real-World Image Denoising},
43 | author={Li, Junyi and Zhang, Zhilu and Liu, Xiaoyu and Feng, Chaoyu and Wang, Xiaotao and Lei, Lei and Zuo, Wangmeng},
44 | booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition},
45 | year={2023}
46 | }
47 | ```
48 |
--------------------------------------------------------------------------------
/submit_test/ensemble_wrapper.py:
--------------------------------------------------------------------------------
1 | import torch
2 |
3 | class EnsembleWrapper():
4 | def __init__(self, model):
5 | self.model = model
6 |
7 | def validation_step(self, data):
8 | input = data['L']
9 | outputs = []
10 | for i in range(8):
11 | aug_input = input.clone()
12 | if i >= 4:
13 | aug_input = torch.flip(aug_input, [2])
14 | if i % 4 > 1:
15 | aug_input = torch.flip(aug_input, [3])
16 | if (i % 4) % 2 == 1:
17 | aug_input = torch.rot90(aug_input, 1, [2, 3])
18 |
19 | aug_output = self.model.validation_step({'L': aug_input})
20 |
21 | if (i % 4) % 2 == 1:
22 | aug_output = torch.rot90(aug_output, 3, [2, 3])
23 | if i % 4 > 1:
24 | aug_output = torch.flip(aug_output, [3])
25 | if i >= 4:
26 | aug_output = torch.flip(aug_output, [2])
27 | outputs.append(aug_output)
28 | output = torch.stack(outputs, dim=0)
29 | output = torch.mean(output, dim=0, keepdim=False)
30 | return output
--------------------------------------------------------------------------------
/submit_test/test_DND.py:
--------------------------------------------------------------------------------
1 | import sys
2 | sys.path.append('..')
3 | import argparse
4 | from dataset.DND_sRGB import dnd_path
5 | import h5py
6 | import numpy as np
7 | import os
8 | import scipy.io as sio
9 | import shutil
10 | from submit_test.ensemble_wrapper import EnsembleWrapper
11 | import torch
12 | from tqdm import tqdm
13 | from utils.option import parse, recursive_print
14 |
15 | def bundle_submissions_srgb(submission_folder):
16 | '''
17 | Bundles submission data for sRGB denoising
18 |
19 | submission_folder Folder where denoised images reside
20 |
21 | Output is written to /bundled/. Please submit
22 | the content of this folder.
23 | '''
24 | out_folder = os.path.join(submission_folder, "bundled/")
25 | try:
26 | os.mkdir(out_folder)
27 | except:
28 | pass
29 | israw = False
30 | eval_version = "1.0"
31 |
32 | for i in range(50):
33 | Idenoised = np.zeros((20,), dtype=np.object)
34 | for bb in range(20):
35 | filename = '%04d_%02d.mat' % (i + 1, bb + 1)
36 | s = sio.loadmat(os.path.join(submission_folder, filename))
37 | Idenoised_crop = s["Idenoised_crop"]
38 | Idenoised[bb] = Idenoised_crop
39 | filename = '%04d.mat' % (i + 1)
40 | sio.savemat(os.path.join(out_folder, filename),
41 | {"Idenoised": Idenoised,
42 | "israw": israw,
43 | "eval_version": eval_version},
44 | )
45 |
46 | max_margin = 80
47 |
48 | def main(opt):
49 | if opt['save_mat']:
50 | if os.path.exists(opt['mat_dir']):
51 | shutil.rmtree(opt['mat_dir'])
52 | os.makedirs(opt['mat_dir'])
53 |
54 | Model = getattr(__import__('model'), opt['model'])
55 | model = Model(opt)
56 | model.data_parallel()
57 | if 'resume_from' in opt:
58 | model.load_model(opt['resume_from'])
59 | if opt['ensemble']:
60 | model = EnsembleWrapper(model)
61 |
62 | infos = h5py.File(os.path.join(dnd_path, 'info.mat'), 'r')
63 | info = infos['info']
64 | bb = info['boundingboxes']
65 | for i in tqdm(range(50)):
66 | filename = os.path.join(dnd_path, 'images_srgb', '%04d.mat' % (i + 1))
67 | img = h5py.File(filename, 'r')
68 | Inoisy = np.float32(np.array(img['InoisySRGB']).T)
69 | # bounding box
70 | ref = bb[0][i]
71 | boxes = np.array(info[ref]).T
72 | for k in range(20):
73 | idx = [int(boxes[k, 0] - 1), int(boxes[k, 2]), int(boxes[k, 1] - 1), int(boxes[k, 3])]
74 |
75 | # Crop margin for better boundary process
76 | h_min_margin = max_margin
77 | h_max_margin = max_margin
78 | w_min_margin = max_margin
79 | w_max_margin = max_margin
80 |
81 | if 0 > idx[0] - max_margin:
82 | h_min_margin = idx[0]
83 | if Inoisy.shape[0] < idx[1] + max_margin:
84 | h_max_margin = Inoisy.shape[0] - idx[1]
85 | if 0 > idx[2] - max_margin:
86 | w_min_margin = idx[2]
87 | if Inoisy.shape[1] < idx[3] + max_margin:
88 | w_max_margin = Inoisy.shape[1] - idx[3]
89 |
90 | h_min_margin = h_min_margin // 32 * 32
91 | h_max_margin = h_max_margin // 32 * 32
92 | w_min_margin = w_min_margin // 32 * 32
93 | w_max_margin = w_max_margin // 32 * 32
94 |
95 | Inoisy_crop = Inoisy[idx[0] - h_min_margin:idx[1] + h_max_margin,
96 | idx[2] - w_min_margin:idx[3] + w_max_margin, :].copy()
97 | H = Inoisy_crop.shape[0]
98 | W = Inoisy_crop.shape[1]
99 |
100 | Inoisy_crop = torch.from_numpy(Inoisy_crop).permute(2, 0, 1).unsqueeze(0).cuda()
101 | Inoisy_crop = Inoisy_crop * 255.
102 |
103 | Idenoised_crop = model.validation_step({'L': Inoisy_crop})
104 |
105 | Idenoised_crop = torch.clamp(Idenoised_crop / 255., 0., 1.)
106 | Idenoised_crop = Idenoised_crop.permute(0, 2, 3, 1)[:, h_min_margin:H-h_max_margin, w_min_margin:W-w_max_margin, :].cpu()
107 | Idenoised_crop = Idenoised_crop.numpy()
108 |
109 |
110 | if opt['save_mat']:
111 | # save denoised data
112 | Idenoised_crop = np.float32(Idenoised_crop)
113 | save_file = os.path.join(opt['mat_dir'], '%04d_%02d.mat' % (i + 1, k + 1))
114 | sio.savemat(save_file, {'Idenoised_crop': Idenoised_crop})
115 |
116 |
117 | if __name__ == '__main__':
118 | parser = argparse.ArgumentParser(description="Train the denoiser")
119 | parser.add_argument("--config_file", type=str, default='../option/three_stage.json')
120 | argspar = parser.parse_args()
121 |
122 | opt = parse(argspar.config_file)
123 | opt['mat_dir'] = 'dnd_mat'
124 | opt['save_mat'] = True
125 | opt['ensemble'] = True
126 | recursive_print(opt)
127 |
128 | main(opt)
129 | if opt['save_mat']:
130 | bundle_submissions_srgb(opt['mat_dir'])
--------------------------------------------------------------------------------
/submit_test/test_SIDD.py:
--------------------------------------------------------------------------------
1 | import sys
2 | sys.path.append('..')
3 | import argparse
4 | from dataset.SIDD_sRGB import SIDDSrgbBenchmarkDataset
5 | import numpy as np
6 | import os
7 | import scipy.io as sio
8 | from submit_test.ensemble_wrapper import EnsembleWrapper
9 | import torch
10 | from torch.utils.data import DataLoader
11 | from tqdm import tqdm
12 | from utils.option import parse, recursive_print
13 |
14 | def main(opt):
15 | test_set = SIDDSrgbBenchmarkDataset()
16 | test_loader = DataLoader(test_set, batch_size=1)
17 |
18 | if os.path.exists(opt['mat_path']):
19 | os.remove(opt['mat_path'])
20 |
21 | Model = getattr(__import__('model'), opt['model'])
22 | model = Model(opt)
23 | model.data_parallel()
24 | if 'resume_from' in opt:
25 | model.load_model(opt['resume_from'])
26 | if opt['ensemble']:
27 | model = EnsembleWrapper(model)
28 |
29 | count = 0
30 | denoised_block = np.zeros_like(test_set.noisy_block)
31 | for data in tqdm(test_loader):
32 | output = model.validation_step(data)
33 | output = torch.floor(output + 0.5)
34 | output = torch.clamp(output, 0, 255)
35 | output = output.cpu().squeeze(0).permute(1, 2, 0).numpy()
36 |
37 | index_n = count // test_set.noisy_block.shape[1]
38 | index_k = count % test_set.noisy_block.shape[1]
39 | output = np.uint8(output)
40 | denoised_block[index_n, index_k] = output
41 | count += 1
42 |
43 | save_dict = {}
44 | save_dict['__header__'] = b'MATLAB 5.0 MAT-file, Platform: PCWIN64, Created on: Thu Jan 10 13:08:11 2019'
45 | save_dict['__version__'] = 1.0
46 | save_dict['__globals__'] = []
47 | save_dict['DenoisedBlocksSrgb'] = denoised_block
48 | sio.savemat(opt['mat_path'], save_dict)
49 |
50 |
51 | if __name__ == '__main__':
52 | parser = argparse.ArgumentParser(description="Train the denoiser")
53 | parser.add_argument("--config_file", type=str, default='../option/three_stage.json')
54 | argspar = parser.parse_args()
55 |
56 | opt = parse(argspar.config_file)
57 | opt['mat_path'] = 'SubmitSrgb.mat'
58 | opt['ensemble'] = True
59 | recursive_print(opt)
60 |
61 | main(opt)
--------------------------------------------------------------------------------
/utils/build.py:
--------------------------------------------------------------------------------
1 | def build(obj_type, args):
2 | return obj_type(**args)
--------------------------------------------------------------------------------
/utils/io.py:
--------------------------------------------------------------------------------
1 | import datetime
2 | import imageio
3 | import numpy as np
4 | import torch
5 |
6 | def date_time():
7 | now = datetime.datetime.now()
8 | date_time = now.strftime("%Y-%m-%d, %H:%M:%S")
9 | return date_time
10 |
11 | def log(log_file, str, also_print=True, with_time=True):
12 | with open(log_file, 'a+') as F:
13 | if with_time:
14 | F.write(date_time() + ' ')
15 | F.write(str)
16 | if also_print:
17 | if with_time:
18 | print(date_time(), end=' ')
19 | print(str, end='')
20 |
21 | # save numpy image in shape 3xHxW
22 | def np2image(image, image_file):
23 | image = np.transpose(image, (1, 2, 0))
24 | image = np.clip(image, 0., 1.)
25 | image = image * 255.
26 | image = image.astype(np.uint8)
27 | imageio.imwrite(image_file, image)
28 |
29 | # save tensor image in shape 1x3xHxW
30 | def tensor2image(image, image_file):
31 | image = image.detach().cpu().squeeze(0).numpy()
32 | np2image(image, image_file)
33 |
34 | # return pytorch image in shape 1x3xHxW
35 | def image2tensor(image_file):
36 | image = imageio.imread(image_file).astype(np.float32) / np.float32(255.0)
37 | if len(image.shape) == 3:
38 | image = np.transpose(image, (2, 0, 1))
39 | elif len(image.shape) == 2:
40 | image = np.expand_dims(image, 0)
41 | image = np.asarray(image, dtype=np.float32)
42 | image = torch.from_numpy(image).unsqueeze(0)
43 | return image
44 |
--------------------------------------------------------------------------------
/utils/option.py:
--------------------------------------------------------------------------------
1 | from collections import OrderedDict
2 | import json
3 | from utils.io import log
4 |
5 | def parse(opt_path):
6 | # ----------------------------------------
7 | # remove comments starting with '//'
8 | # ----------------------------------------
9 | json_str = ''
10 | with open(opt_path, 'r') as f:
11 | for line in f:
12 | line = line.split('//')[0] + '\n'
13 | json_str += line
14 |
15 | # ----------------------------------------
16 | # initialize opt
17 | # ----------------------------------------
18 | opt = json.loads(json_str, object_pairs_hook=OrderedDict)
19 |
20 | return opt
21 |
22 |
23 | def recursive_print(src, dpth=0, key=None):
24 | """ Recursively prints nested elements."""
25 | tabs = lambda n: ' ' * n * 4 # or 2 or 8 or...
26 |
27 | if isinstance(src, dict):
28 | if key is not None:
29 | print(tabs(dpth) + '%s: ' % (key))
30 | for key, value in src.items():
31 | recursive_print(value, dpth + 1, key)
32 | elif isinstance(src, list):
33 | if key is not None:
34 | print(tabs(dpth) + '%s: ' % (key))
35 | for litem in src:
36 | recursive_print(litem, dpth)
37 | else:
38 | if key is not None:
39 | print(tabs(dpth) + '%s: %s' % (key, src))
40 |
41 |
42 | def recursive_log(log_file, src, dpth=0, key=None):
43 | """ Recursively prints nested elements."""
44 | tabs = lambda n: ' ' * n * 4 # or 2 or 8 or...
45 |
46 | if isinstance(src, dict):
47 | if key is not None:
48 | log(log_file, tabs(dpth) + '%s: \n' % (key), with_time=False)
49 | for key, value in src.items():
50 | recursive_log(log_file, value, dpth + 1, key)
51 | elif isinstance(src, list):
52 | if key is not None:
53 | log(log_file, tabs(dpth) + '%s: \n' % (key), with_time=False)
54 | for litem in src:
55 | recursive_log(log_file, litem, dpth)
56 | else:
57 | if key is not None:
58 | log(log_file, tabs(dpth) + '%s: %s\n' % (key, src), with_time=False)
--------------------------------------------------------------------------------
/validate/validate_SIDD.py:
--------------------------------------------------------------------------------
1 | import sys
2 | sys.path.append('..')
3 | import argparse
4 | from skimage.metrics import peak_signal_noise_ratio
5 | import torch
6 | from torch.utils.data import DataLoader
7 | from utils.option import parse, recursive_print
8 | from utils.build import build
9 |
10 | def validate_sidd(model, sidd_loader):
11 | psnrs, count = 0, 0
12 | for data in sidd_loader:
13 | output = model.validation_step(data)
14 | output = torch.floor(output + 0.5)
15 | output = torch.clamp(output, 0, 255)
16 | output = output.cpu().squeeze(0).permute(1, 2, 0).numpy()
17 | gt = data['H'].squeeze(0).permute(1, 2, 0).numpy()
18 | psnr = peak_signal_noise_ratio(output, gt, data_range=255)
19 | psnrs += psnr
20 | count += 1
21 | return psnrs / count
22 |
23 |
24 | def main(opt):
25 | validation_loaders = []
26 | for validation_dataset_opt in opt['validation_datasets']:
27 | ValidationDataset = getattr(__import__('dataset'), validation_dataset_opt['type'])
28 | validation_set = build(ValidationDataset, validation_dataset_opt['args'])
29 | validation_loader = DataLoader(validation_set, batch_size=1)
30 | validation_loaders.append(validation_loader)
31 |
32 | Model = getattr(__import__('model'), opt['model'])
33 | model = Model(opt)
34 | model.data_parallel()
35 | if 'resume_from' in opt:
36 | model.load_model(opt['resume_from'])
37 |
38 | for validation_loader in validation_loaders:
39 | psnr = validate_sidd(model, validation_loader)
40 | print('%s, psnr: %6.4f' % (validation_loader.dataset.__class__.__name__, psnr))
41 |
42 |
43 | if __name__ == '__main__':
44 | parser = argparse.ArgumentParser(description="Validate the denoiser")
45 | parser.add_argument("--config_file", type=str, default='../option/three_stage.json')
46 | argspar = parser.parse_args()
47 |
48 | opt = parse(argspar.config_file)
49 | recursive_print(opt)
50 |
51 | main(opt)
--------------------------------------------------------------------------------