├── .gitignore
├── LICENSE
├── README.rst
├── docker-cpu.df
├── docker-gpu.df
├── docs
├── BankLobby_example.gif
├── EnhanceCSI_example.png
├── Faces_example.png
├── OldStation_example.gif
└── StreetView_example.gif
├── enhance.py
├── requirements.txt
└── train
├── ne1x-photo-repair.sh
└── ne2x-photo-default.sh
/.gitignore:
--------------------------------------------------------------------------------
1 | # NeuralEnhance
2 | train/
3 | valid/
4 | *.pkl.bz2
5 |
6 | # Byte-compiled / optimized / DLL files
7 | __pycache__/
8 | *.py[cod]
9 | *$py.class
10 |
11 | # C extensions
12 | *.so
13 |
14 | # Distribution / packaging
15 | .Python
16 | env/
17 | build/
18 | develop-eggs/
19 | dist/
20 | downloads/
21 | eggs/
22 | .eggs/
23 | lib/
24 | lib64/
25 | parts/
26 | sdist/
27 | var/
28 | *.egg-info/
29 | .installed.cfg
30 | *.egg
31 |
32 | # PyInstaller
33 | # Usually these files are written by a python script from a template
34 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
35 | *.manifest
36 | *.spec
37 |
38 | # Installer logs
39 | pip-log.txt
40 | pip-delete-this-directory.txt
41 |
42 | # Unit test / coverage reports
43 | htmlcov/
44 | .tox/
45 | .coverage
46 | .coverage.*
47 | .cache
48 | nosetests.xml
49 | coverage.xml
50 | *,cover
51 | .hypothesis/
52 |
53 | # Translations
54 | *.mo
55 | *.pot
56 |
57 | # Django stuff:
58 | *.log
59 | local_settings.py
60 |
61 | # Flask stuff:
62 | instance/
63 | .webassets-cache
64 |
65 | # Scrapy stuff:
66 | .scrapy
67 |
68 | # Sphinx documentation
69 | docs/_build/
70 |
71 | # PyBuilder
72 | target/
73 |
74 | # IPython Notebook
75 | .ipynb_checkpoints
76 |
77 | # pyenv
78 | .python-version
79 |
80 | # celery beat schedule file
81 | celerybeat-schedule
82 |
83 | # dotenv
84 | .env
85 |
86 | # virtualenv
87 | venv/
88 | ENV/
89 |
90 | # Spyder project settings
91 | .spyderproject
92 |
93 | # Rope project settings
94 | .ropeproject
95 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/README.rst:
--------------------------------------------------------------------------------
1 | Neural Enhance
2 | ==============
3 |
4 | .. image:: docs/OldStation_example.gif
5 |
6 | **Example #1** — Old Station: `view comparison `_ in 24-bit HD, `original photo `_ CC-BY-SA @siv-athens.
7 |
8 | ----
9 |
10 | `As seen on TV! `_ What if you could increase the resolution of your photos using technology from CSI laboratories? Thanks to deep learning and ``#NeuralEnhance``, it's now possible to train a neural network to zoom in to your images at 2x or even 4x. You'll get even better results by increasing the number of neurons or training with a dataset similar to your low resolution image.
11 |
12 | The catch? The neural network is hallucinating details based on its training from example images. It's not reconstructing your photo exactly as it would have been if it was HD. That's only possible in Hollywood — but using deep learning as "Creative AI" works and it is just as cool! Here's how you can get started...
13 |
14 | 1. `Examples & Usage <#1-examples--usage>`_
15 | 2. `Installation <#2-installation--setup>`_
16 | 3. `Background & Research <#3-background--research>`_
17 | 4. `Troubleshooting <#4-troubleshooting-problems>`_
18 | 5. `Frequent Questions <#5-frequent-questions>`_
19 |
20 | |Python Version| |License Type| |Project Stars|
21 |
22 | .. image:: docs/EnhanceCSI_example.png
23 | :target: http://enhance.nucl.ai/w/8581db92-9d61-11e6-990b-c86000be451f/view
24 |
25 | 1. Examples & Usage
26 | ===================
27 |
28 | The main script is called ``enhance.py``, which you can run with Python 3.4+ once it's `setup <#2-installation--setup>`_ as below. The ``--device`` argument that lets you specify which GPU or CPU to use. For the samples above, here are the performance results:
29 |
30 | * **GPU Rendering HQ** — Assuming you have CUDA setup and enough on-board RAM to fit the image and neural network, generating 1080p output should complete in 5 seconds, or 2s per image if multiple at the same time.
31 | * **CPU Rendering HQ** — This will take roughly 20 to 60 seconds for 1080p output, however on most machines you can run 4-8 processes simultaneously given enough system RAM. Runtime depends on the neural network size.
32 |
33 | The default is to use ``--device=cpu``, if you have NVIDIA card setup with CUDA already try ``--device=gpu0``. On the CPU, you can also set environment variable to ``OMP_NUM_THREADS=4``, which is most useful when running the script multiple times in parallel.
34 |
35 | 1.a) Enhancing Images
36 | ---------------------
37 |
38 | A list of example command lines you can use with the pre-trained models provided in the GitHub releases:
39 |
40 | .. code:: bash
41 |
42 | # Run the super-resolution script to repair JPEG artefacts, zoom factor 1:1.
43 | python3 enhance.py --type=photo --model=repair --zoom=1 broken.jpg
44 |
45 | # Process multiple good quality images with a single run, zoom factor 2:1.
46 | python3 enhance.py --type=photo --zoom=2 file1.jpg file2.jpg
47 |
48 | # Display output images that were given `_ne?x.png` suffix.
49 | open *_ne?x.png
50 |
51 | Here's a list of currently supported models, image types, and zoom levels in one table.
52 |
53 | ================== ===================== ==================== ===================== ====================
54 | FEATURES ``--model=default`` ``--model=repair`` ``--model=denoise`` ``--model=deblur``
55 | ================== ===================== ==================== ===================== ====================
56 | ``--type=photo`` 2x 1x … …
57 | ================== ===================== ==================== ===================== ====================
58 |
59 |
60 | 1.b) Training Super-Resolution
61 | ------------------------------
62 |
63 | Pre-trained models are provided in the GitHub releases. Training your own is a delicate process that may require you to pick parameters based on your image dataset.
64 |
65 | .. code:: bash
66 |
67 | # Remove the model file as don't want to reload the data to fine-tune it.
68 | rm -f ne?x*.pkl.bz2
69 |
70 | # Pre-train the model using perceptual loss from paper [1] below.
71 | python3.4 enhance.py --train "data/*.jpg" --model custom --scales=2 --epochs=50 \
72 | --perceptual-layer=conv2_2 --smoothness-weight=1e7 --adversary-weight=0.0 \
73 | --generator-blocks=4 --generator-filters=64
74 |
75 | # Train the model using an adversarial setup based on [4] below.
76 | python3.4 enhance.py --train "data/*.jpg" --model custom --scales=2 --epochs=250 \
77 | --perceptual-layer=conv5_2 --smoothness-weight=2e4 --adversary-weight=1e3 \
78 | --generator-start=5 --discriminator-start=0 --adversarial-start=5 \
79 | --discriminator-size=64
80 |
81 | # The newly trained model is output into this file...
82 | ls ne?x-custom-*.pkl.bz2
83 |
84 |
85 | .. image:: docs/BankLobby_example.gif
86 |
87 | **Example #2** — Bank Lobby: `view comparison `_ in 24-bit HD, `original photo `_ CC-BY-SA @benarent.
88 |
89 | 2. Installation & Setup
90 | =======================
91 |
92 | 2.a) Using Docker Image [recommended]
93 | -------------------------------------
94 |
95 | The easiest way to get up-and-running is to `install Docker `_. Then, you should be able to download and run the pre-built image using the ``docker`` command line tool. Find out more about the ``alexjc/neural-enhance`` image on its `Docker Hub `_ page.
96 |
97 | Here's the simplest way you can call the script using ``docker``, assuming you're familiar with using ``-v`` argument to mount folders you can use this directly to specify files to enhance:
98 |
99 | .. code:: bash
100 |
101 | # Download the Docker image and show the help text to make sure it works.
102 | docker run --rm -v `pwd`:/ne/input -it alexjc/neural-enhance --help
103 |
104 | **Single Image** — In practice, we suggest you setup an alias called ``enhance`` to automatically expose the folder containing your specified image, so the script can read it and store results where you can access them. This is how you can do it in your terminal console on OSX or Linux:
105 |
106 | .. code:: bash
107 |
108 | # Setup the alias. Put this in your .bashrc or .zshrc file so it's available at startup.
109 | alias enhance='function ne() { docker run --rm -v "$(pwd)/`dirname ${@:$#}`":/ne/input -it alexjc/neural-enhance ${@:1:$#-1} "input/`basename ${@:$#}`"; }; ne'
110 |
111 | # Now run any of the examples above using this alias, without the `.py` extension.
112 | enhance --zoom=1 --model=repair images/broken.jpg
113 |
114 | **Multiple Images** — To enhance multiple images in a row (faster) from a folder or wildcard specification, make sure to quote the argument to the alias command:
115 |
116 | .. code:: bash
117 |
118 | # Process multiple images, make sure to quote the argument!
119 | enhance --zoom=2 "images/*.jpg"
120 |
121 | If you want to run on your NVIDIA GPU, you can instead change the alias to use the image ``alexjc/neural-enhance:gpu`` which comes with CUDA and CUDNN pre-installed. Then run it within `nvidia-docker `_ and it should use your physical hardware!
122 |
123 |
124 | 2.b) Manual Installation [developers]
125 | -------------------------------------
126 |
127 | This project requires Python 3.4+ and you'll also need ``numpy`` and ``scipy`` (numerical computing libraries) as well as ``python3-dev`` installed system-wide. If you want more detailed instructions, follow these:
128 |
129 | 1. `Linux Installation of Lasagne `_ **(intermediate)**
130 | 2. `Mac OSX Installation of Lasagne `_ **(advanced)**
131 | 3. `Windows Installation of Lasagne `_ **(expert)**
132 |
133 | Afterward fetching the repository, you can run the following commands from your terminal to setup a local environment:
134 |
135 | .. code:: bash
136 |
137 | # Create a local environment for Python 3.x to install dependencies here.
138 | python3 -m venv pyvenv --system-site-packages
139 |
140 | # If you're using bash, make this the active version of Python.
141 | source pyvenv/bin/activate
142 |
143 | # Setup the required dependencies simply using the PIP module.
144 | python3 -m pip install --ignore-installed -r requirements.txt
145 |
146 | After this, you should have ``pillow``, ``theano`` and ``lasagne`` installed in your virtual environment. You'll also need to download this `pre-trained neural network `_ (VGG19, 80Mb) and put it in the same folder as the script to run. To de-install everything, you can just delete the ``#/pyvenv/`` folder.
147 |
148 | .. image:: docs/Faces_example.png
149 |
150 | **Example #3** — Specialized super-resolution for faces, trained on HD examples of celebrity faces only. The quality is significantly higher when narrowing the domain from "photos" in general.
151 |
152 | 3. Background & Research
153 | ========================
154 |
155 | This code uses a combination of techniques from the following papers, as well as some minor improvements yet to be documented (watch this repository for updates):
156 |
157 | 1. `Perceptual Losses for Real-Time Style Transfer and Super-Resolution `_
158 | 2. `Real-Time Super-Resolution Using Efficient Sub-Pixel Convolution `_
159 | 3. `Deeply-Recursive Convolutional Network for Image Super-Resolution `_
160 | 4. `Photo-Realistic Super-Resolution Using a Generative Adversarial Network `_
161 |
162 | Special thanks for their help and support in various ways:
163 |
164 | * Eder Santana — Discussions, encouragement, and his ideas on `sub-pixel deconvolution `_.
165 | * Andrew Brock — This sub-pixel layer code is based on `his project repository `_ using Lasagne.
166 | * Casper Kaae Sønderby — For suggesting a more stable alternative to sigmoid + log as GAN loss functions.
167 |
168 |
169 | 4. Troubleshooting Problems
170 | ===========================
171 |
172 | Can't install or Unable to find pgen, not compiling formal grammar.
173 | -------------------------------------------------------------------
174 |
175 | There's a Python extension compiler called Cython, and it's missing or improperly installed. Try getting it directly from the system package manager rather than PIP.
176 |
177 | **FIX:** ``sudo apt-get install cython3``
178 |
179 |
180 | NotImplementedError: AbstractConv2d theano optimization failed.
181 | ---------------------------------------------------------------
182 |
183 | This happens when you're running without a GPU, and the CPU libraries were not found (e.g. ``libblas``). The neural network expressions cannot be evaluated by Theano and it's raising an exception.
184 |
185 | **FIX:** ``sudo apt-get install libblas-dev libopenblas-dev``
186 |
187 |
188 | TypeError: max_pool_2d() got an unexpected keyword argument 'mode'
189 | ------------------------------------------------------------------
190 |
191 | You need to install Lasagne and Theano directly from the versions specified in ``requirements.txt``, rather than from the PIP versions. These alternatives are older and don't have the required features.
192 |
193 | **FIX:** ``python3 -m pip install -r requirements.txt``
194 |
195 |
196 | ValueError: unknown locale: UTF-8
197 | ---------------------------------
198 |
199 | It seems your terminal is misconfigured and not compatible with the way Python treats locales. You may need to change this in your ``.bashrc`` or other startup script. Alternatively, this command will fix it once for this shell instance.
200 |
201 | **FIX:** ``export LC_ALL=en_US.UTF-8``
202 |
203 | .. image:: docs/StreetView_example.gif
204 |
205 | **Example #4** — Street View: `view comparison `_ in 24-bit HD, `original photo `_ CC-BY-SA @cyalex.
206 |
207 | ----
208 |
209 | |Python Version| |License Type| |Project Stars|
210 |
211 | .. |Python Version| image:: http://aigamedev.github.io/scikit-neuralnetwork/badge_python.svg
212 | :target: https://www.python.org/
213 |
214 | .. |License Type| image:: https://img.shields.io/badge/license-AGPL-blue.svg
215 | :target: https://github.com/alexjc/neural-enhance/blob/master/LICENSE
216 |
217 | .. |Project Stars| image:: https://img.shields.io/github/stars/alexjc/neural-enhance.svg?style=flat
218 | :target: https://github.com/alexjc/neural-enhance/stargazers
219 |
--------------------------------------------------------------------------------
/docker-cpu.df:
--------------------------------------------------------------------------------
1 | FROM ubuntu:14.04
2 |
3 | # Install dependencies
4 | RUN apt-get -qq update && \
5 | apt-get -qq install --assume-yes \
6 | "build-essential" \
7 | "git" \
8 | "wget" \
9 | "libopenblas-dev" \
10 | "liblapack-dev" \
11 | "pkg-config" && \
12 | rm -rf /var/lib/apt/lists/*
13 |
14 | # Miniconda.
15 | RUN wget --quiet https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh -O ~/miniconda.sh && \
16 | /bin/bash ~/miniconda.sh -b -p /opt/conda && \
17 | rm ~/miniconda.sh
18 |
19 | # Install requirements before copying project files
20 | WORKDIR /ne
21 | COPY requirements.txt .
22 | RUN /opt/conda/bin/conda install -q -y conda numpy scipy pip pillow
23 | RUN /opt/conda/bin/python3.5 -m pip install -q -r "requirements.txt"
24 |
25 | # Copy only required project files
26 | COPY enhance.py .
27 |
28 | # Get a pre-trained neural networks, non-commercial & attribution.
29 | RUN wget -q "https://github.com/alexjc/neural-enhance/releases/download/v0.3/ne1x-photo-deblur-0.3.pkl.bz2"
30 | RUN wget -q "https://github.com/alexjc/neural-enhance/releases/download/v0.3/ne1x-photo-repair-0.3.pkl.bz2"
31 | RUN wget -q "https://github.com/alexjc/neural-enhance/releases/download/v0.3/ne2x-photo-default-0.3.pkl.bz2"
32 | RUN wget -q "https://github.com/alexjc/neural-enhance/releases/download/v0.3/ne4x-photo-default-0.3.pkl.bz2"
33 | # Set an entrypoint to the main enhance.py script
34 | ENTRYPOINT ["/opt/conda/bin/python3.5", "enhance.py", "--device=cpu"]
35 |
--------------------------------------------------------------------------------
/docker-gpu.df:
--------------------------------------------------------------------------------
1 | FROM nvidia/cuda:8.0-cudnn5-devel
2 |
3 | # Install dependencies
4 | RUN apt-get -qq update && \
5 | apt-get -qq install --assume-yes \
6 | "build-essential" \
7 | "git" \
8 | "wget" \
9 | "pkg-config" && \
10 | rm -rf /var/lib/apt/lists/*
11 |
12 | # Miniconda.
13 | RUN wget --quiet https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh -O ~/miniconda.sh && \
14 | /bin/bash ~/miniconda.sh -b -p /opt/conda && \
15 | rm ~/miniconda.sh
16 |
17 | # Install requirements before copying project files
18 | WORKDIR /ne
19 | COPY requirements.txt .
20 | RUN /opt/conda/bin/conda install -q -y conda numpy scipy pip pillow
21 | RUN /opt/conda/bin/python3.5 -m pip install -q -r "requirements.txt"
22 |
23 | # Copy only required project files
24 | COPY enhance.py .
25 |
26 | # Get a pre-trained neural networks, non-commercial & attribution.
27 | RUN wget -q "https://github.com/alexjc/neural-enhance/releases/download/v0.3/ne1x-photo-deblur-0.3.pkl.bz2"
28 | RUN wget -q "https://github.com/alexjc/neural-enhance/releases/download/v0.3/ne1x-photo-repair-0.3.pkl.bz2"
29 | RUN wget -q "https://github.com/alexjc/neural-enhance/releases/download/v0.3/ne2x-photo-default-0.3.pkl.bz2"
30 | RUN wget -q "https://github.com/alexjc/neural-enhance/releases/download/v0.3/ne4x-photo-default-0.3.pkl.bz2"
31 |
32 | # Set an entrypoint to the main enhance.py script
33 | ENTRYPOINT ["/opt/conda/bin/python3.5", "enhance.py", "--device=gpu"]
34 |
--------------------------------------------------------------------------------
/docs/BankLobby_example.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexjc/neural-enhance/2fd67de7eddae3e8dc48f8abdc791ddbcc867112/docs/BankLobby_example.gif
--------------------------------------------------------------------------------
/docs/EnhanceCSI_example.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexjc/neural-enhance/2fd67de7eddae3e8dc48f8abdc791ddbcc867112/docs/EnhanceCSI_example.png
--------------------------------------------------------------------------------
/docs/Faces_example.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexjc/neural-enhance/2fd67de7eddae3e8dc48f8abdc791ddbcc867112/docs/Faces_example.png
--------------------------------------------------------------------------------
/docs/OldStation_example.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexjc/neural-enhance/2fd67de7eddae3e8dc48f8abdc791ddbcc867112/docs/OldStation_example.gif
--------------------------------------------------------------------------------
/docs/StreetView_example.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexjc/neural-enhance/2fd67de7eddae3e8dc48f8abdc791ddbcc867112/docs/StreetView_example.gif
--------------------------------------------------------------------------------
/enhance.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | """ _ _
3 | _ __ ___ _ _ _ __ __ _| | ___ _ __ | |__ __ _ _ __ ___ ___
4 | | '_ \ / _ \ | | | '__/ _` | | / _ \ '_ \| '_ \ / _` | '_ \ / __/ _ \
5 | | | | | __/ |_| | | | (_| | | | __/ | | | | | | (_| | | | | (_| __/
6 | |_| |_|\___|\__,_|_| \__,_|_| \___|_| |_|_| |_|\__,_|_| |_|\___\___|
7 |
8 | """
9 | #
10 | # Copyright (c) 2016, Alex J. Champandard.
11 | #
12 | # Neural Enhance is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
13 | # Public License version 3. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
14 | # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15 | #
16 |
17 | __version__ = '0.3'
18 |
19 | import io
20 | import os
21 | import sys
22 | import bz2
23 | import glob
24 | import math
25 | import time
26 | import pickle
27 | import random
28 | import argparse
29 | import itertools
30 | import threading
31 | import collections
32 |
33 |
34 | # Configure all options first so we can later custom-load other libraries (Theano) based on device specified by user.
35 | parser = argparse.ArgumentParser(description='Generate a new image by applying style onto a content image.',
36 | formatter_class=argparse.ArgumentDefaultsHelpFormatter)
37 | add_arg = parser.add_argument
38 | add_arg('files', nargs='*', default=[])
39 | add_arg('--zoom', default=2, type=int, help='Resolution increase factor for inference.')
40 | add_arg('--rendering-tile', default=80, type=int, help='Size of tiles used for rendering images.')
41 | add_arg('--rendering-overlap', default=24, type=int, help='Number of pixels padding around each tile.')
42 | add_arg('--rendering-histogram',default=False, action='store_true', help='Match color histogram of output to input.')
43 | add_arg('--type', default='photo', type=str, help='Name of the neural network to load/save.')
44 | add_arg('--model', default='default', type=str, help='Specific trained version of the model.')
45 | add_arg('--train', default=False, type=str, help='File pattern to load for training.')
46 | add_arg('--train-scales', default=0, type=int, help='Randomly resize images this many times.')
47 | add_arg('--train-blur', default=None, type=int, help='Sigma value for gaussian blur preprocess.')
48 | add_arg('--train-noise', default=None, type=float, help='Radius for preprocessing gaussian blur.')
49 | add_arg('--train-jpeg', default=[], nargs='+', type=int, help='JPEG compression level & range in preproc.')
50 | add_arg('--epochs', default=10, type=int, help='Total number of iterations in training.')
51 | add_arg('--epoch-size', default=72, type=int, help='Number of batches trained in an epoch.')
52 | add_arg('--save-every', default=10, type=int, help='Save generator after every training epoch.')
53 | add_arg('--batch-shape', default=192, type=int, help='Resolution of images in training batch.')
54 | add_arg('--batch-size', default=15, type=int, help='Number of images per training batch.')
55 | add_arg('--buffer-size', default=1500, type=int, help='Total image fragments kept in cache.')
56 | add_arg('--buffer-fraction', default=5, type=int, help='Fragments cached for each image loaded.')
57 | add_arg('--learning-rate', default=1E-4, type=float, help='Parameter for the ADAM optimizer.')
58 | add_arg('--learning-period', default=75, type=int, help='How often to decay the learning rate.')
59 | add_arg('--learning-decay', default=0.5, type=float, help='How much to decay the learning rate.')
60 | add_arg('--generator-upscale', default=2, type=int, help='Steps of 2x up-sampling as post-process.')
61 | add_arg('--generator-downscale',default=0, type=int, help='Steps of 2x down-sampling as preprocess.')
62 | add_arg('--generator-filters', default=[64], nargs='+', type=int, help='Number of convolution units in network.')
63 | add_arg('--generator-blocks', default=4, type=int, help='Number of residual blocks per iteration.')
64 | add_arg('--generator-residual', default=2, type=int, help='Number of layers in a residual block.')
65 | add_arg('--perceptual-layer', default='conv2_2', type=str, help='Which VGG layer to use as loss component.')
66 | add_arg('--perceptual-weight', default=1e0, type=float, help='Weight for VGG-layer perceptual loss.')
67 | add_arg('--discriminator-size', default=32, type=int, help='Multiplier for number of filters in D.')
68 | add_arg('--smoothness-weight', default=2e5, type=float, help='Weight of the total-variation loss.')
69 | add_arg('--adversary-weight', default=5e2, type=float, help='Weight of adversarial loss compoment.')
70 | add_arg('--generator-start', default=0, type=int, help='Epoch count to start training generator.')
71 | add_arg('--discriminator-start',default=1, type=int, help='Epoch count to update the discriminator.')
72 | add_arg('--adversarial-start', default=2, type=int, help='Epoch for generator to use discriminator.')
73 | add_arg('--device', default='cpu', type=str, help='Name of the CPU/GPU to use, for Theano.')
74 | args = parser.parse_args()
75 |
76 |
77 | #----------------------------------------------------------------------------------------------------------------------
78 |
79 | # Color coded output helps visualize the information a little better, plus it looks cool!
80 | class ansi:
81 | WHITE = '\033[0;97m'
82 | WHITE_B = '\033[1;97m'
83 | YELLOW = '\033[0;33m'
84 | YELLOW_B = '\033[1;33m'
85 | RED = '\033[0;31m'
86 | RED_B = '\033[1;31m'
87 | BLUE = '\033[0;94m'
88 | BLUE_B = '\033[1;94m'
89 | CYAN = '\033[0;36m'
90 | CYAN_B = '\033[1;36m'
91 | ENDC = '\033[0m'
92 |
93 | def error(message, *lines):
94 | string = "\n{}ERROR: " + message + "{}\n" + "\n".join(lines) + ("{}\n" if lines else "{}")
95 | print(string.format(ansi.RED_B, ansi.RED, ansi.ENDC))
96 | sys.exit(-1)
97 |
98 | def warn(message, *lines):
99 | string = "\n{}WARNING: " + message + "{}\n" + "\n".join(lines) + "{}\n"
100 | print(string.format(ansi.YELLOW_B, ansi.YELLOW, ansi.ENDC))
101 |
102 | def extend(lst): return itertools.chain(lst, itertools.repeat(lst[-1]))
103 |
104 | print("""{} {}Super Resolution for images and videos powered by Deep Learning!{}
105 | - Code licensed as AGPLv3, models under CC BY-NC-SA.{}""".format(ansi.CYAN_B, __doc__, ansi.CYAN, ansi.ENDC))
106 |
107 | # Load the underlying deep learning libraries based on the device specified. If you specify THEANO_FLAGS manually,
108 | # the code assumes you know what you are doing and they are not overriden!
109 | os.environ.setdefault('THEANO_FLAGS', 'floatX=float32,device={},force_device=True,allow_gc=True,'\
110 | 'print_active_device=False'.format(args.device))
111 |
112 | # Scientific & Imaging Libraries
113 | import numpy as np
114 | import scipy.ndimage, scipy.misc, PIL.Image
115 |
116 | # Numeric Computing (GPU)
117 | import theano, theano.tensor as T
118 | T.nnet.softminus = lambda x: x - T.nnet.softplus(x)
119 |
120 | # Support ansi colors in Windows too.
121 | if sys.platform == 'win32':
122 | import colorama
123 |
124 | # Deep Learning Framework
125 | import lasagne
126 | from lasagne.layers import Conv2DLayer as ConvLayer, Deconv2DLayer as DeconvLayer, Pool2DLayer as PoolLayer
127 | from lasagne.layers import InputLayer, ConcatLayer, ElemwiseSumLayer, batch_norm
128 |
129 | print('{} - Using the device `{}` for neural computation.{}\n'.format(ansi.CYAN, theano.config.device, ansi.ENDC))
130 |
131 |
132 | #======================================================================================================================
133 | # Image Processing
134 | #======================================================================================================================
135 | class DataLoader(threading.Thread):
136 |
137 | def __init__(self):
138 | super(DataLoader, self).__init__(daemon=True)
139 | self.data_ready = threading.Event()
140 | self.data_copied = threading.Event()
141 |
142 | self.orig_shape, self.seed_shape = args.batch_shape, args.batch_shape // args.zoom
143 |
144 | self.orig_buffer = np.zeros((args.buffer_size, 3, self.orig_shape, self.orig_shape), dtype=np.float32)
145 | self.seed_buffer = np.zeros((args.buffer_size, 3, self.seed_shape, self.seed_shape), dtype=np.float32)
146 | self.files = glob.glob(args.train)
147 | if len(self.files) == 0:
148 | error("There were no files found to train from searching for `{}`".format(args.train),
149 | " - Try putting all your images in one folder and using `--train=data/*.jpg`")
150 |
151 | self.available = set(range(args.buffer_size))
152 | self.ready = set()
153 |
154 | self.cwd = os.getcwd()
155 | self.start()
156 |
157 | def run(self):
158 | while True:
159 | random.shuffle(self.files)
160 | for f in self.files:
161 | self.add_to_buffer(f)
162 |
163 | def add_to_buffer(self, f):
164 | filename = os.path.join(self.cwd, f)
165 | try:
166 | orig = PIL.Image.open(filename).convert('RGB')
167 | scale = 2 ** random.randint(0, args.train_scales)
168 | if scale > 1 and all(s//scale >= args.batch_shape for s in orig.size):
169 | orig = orig.resize((orig.size[0]//scale, orig.size[1]//scale), resample=PIL.Image.LANCZOS)
170 | if any(s < args.batch_shape for s in orig.size):
171 | raise ValueError('Image is too small for training with size {}'.format(orig.size))
172 | except Exception as e:
173 | warn('Could not load `{}` as image.'.format(filename),
174 | ' - Try fixing or removing the file before next run.')
175 | self.files.remove(f)
176 | return
177 |
178 | seed = orig
179 | if args.train_blur is not None:
180 | seed = seed.filter(PIL.ImageFilter.GaussianBlur(radius=random.randint(0, args.train_blur*2)))
181 | if args.zoom > 1:
182 | seed = seed.resize((orig.size[0]//args.zoom, orig.size[1]//args.zoom), resample=PIL.Image.LANCZOS)
183 | if len(args.train_jpeg) > 0:
184 | buffer, rng = io.BytesIO(), args.train_jpeg[-1] if len(args.train_jpeg) > 1 else 15
185 | seed.save(buffer, format='jpeg', quality=args.train_jpeg[0]+random.randrange(-rng, +rng))
186 | seed = PIL.Image.open(buffer)
187 |
188 | orig = scipy.misc.fromimage(orig).astype(np.float32)
189 | seed = scipy.misc.fromimage(seed).astype(np.float32)
190 |
191 | if args.train_noise is not None:
192 | seed += scipy.random.normal(scale=args.train_noise, size=(seed.shape[0], seed.shape[1], 1))
193 |
194 | for _ in range(seed.shape[0] * seed.shape[1] // (args.buffer_fraction * self.seed_shape ** 2)):
195 | h = random.randint(0, seed.shape[0] - self.seed_shape)
196 | w = random.randint(0, seed.shape[1] - self.seed_shape)
197 | seed_chunk = seed[h:h+self.seed_shape, w:w+self.seed_shape]
198 | h, w = h * args.zoom, w * args.zoom
199 | orig_chunk = orig[h:h+self.orig_shape, w:w+self.orig_shape]
200 |
201 | while len(self.available) == 0:
202 | self.data_copied.wait()
203 | self.data_copied.clear()
204 |
205 | i = self.available.pop()
206 | self.orig_buffer[i] = np.transpose(orig_chunk.astype(np.float32) / 255.0 - 0.5, (2, 0, 1))
207 | self.seed_buffer[i] = np.transpose(seed_chunk.astype(np.float32) / 255.0 - 0.5, (2, 0, 1))
208 | self.ready.add(i)
209 |
210 | if len(self.ready) >= args.batch_size:
211 | self.data_ready.set()
212 |
213 | def copy(self, origs_out, seeds_out):
214 | self.data_ready.wait()
215 | self.data_ready.clear()
216 |
217 | for i, j in enumerate(random.sample(self.ready, args.batch_size)):
218 | origs_out[i] = self.orig_buffer[j]
219 | seeds_out[i] = self.seed_buffer[j]
220 | self.available.add(j)
221 | self.data_copied.set()
222 |
223 |
224 | #======================================================================================================================
225 | # Convolution Networks
226 | #======================================================================================================================
227 |
228 | class SubpixelReshuffleLayer(lasagne.layers.Layer):
229 | """Based on the code by ajbrock: https://github.com/ajbrock/Neural-Photo-Editor/
230 | """
231 |
232 | def __init__(self, incoming, channels, upscale, **kwargs):
233 | super(SubpixelReshuffleLayer, self).__init__(incoming, **kwargs)
234 | self.upscale = upscale
235 | self.channels = channels
236 |
237 | def get_output_shape_for(self, input_shape):
238 | def up(d): return self.upscale * d if d else d
239 | return (input_shape[0], self.channels, up(input_shape[2]), up(input_shape[3]))
240 |
241 | def get_output_for(self, input, deterministic=False, **kwargs):
242 | out, r = T.zeros(self.get_output_shape_for(input.shape)), self.upscale
243 | for y, x in itertools.product(range(r), repeat=2):
244 | out=T.inc_subtensor(out[:,:,y::r,x::r], input[:,r*y+x::r*r,:,:])
245 | return out
246 |
247 |
248 | class Model(object):
249 |
250 | def __init__(self):
251 | self.network = collections.OrderedDict()
252 | self.network['img'] = InputLayer((None, 3, None, None))
253 | self.network['seed'] = InputLayer((None, 3, None, None))
254 |
255 | config, params = self.load_model()
256 | self.setup_generator(self.last_layer(), config)
257 |
258 | if args.train:
259 | concatenated = lasagne.layers.ConcatLayer([self.network['img'], self.network['out']], axis=0)
260 | self.setup_perceptual(concatenated)
261 | self.load_perceptual()
262 | self.setup_discriminator()
263 | self.load_generator(params)
264 | self.compile()
265 |
266 | #------------------------------------------------------------------------------------------------------------------
267 | # Network Configuration
268 | #------------------------------------------------------------------------------------------------------------------
269 |
270 | def last_layer(self):
271 | return list(self.network.values())[-1]
272 |
273 | def make_layer(self, name, input, units, filter_size=(3,3), stride=(1,1), pad=(1,1), alpha=0.25):
274 | conv = ConvLayer(input, units, filter_size, stride=stride, pad=pad, nonlinearity=None)
275 | prelu = lasagne.layers.ParametricRectifierLayer(conv, alpha=lasagne.init.Constant(alpha))
276 | self.network[name+'x'] = conv
277 | self.network[name+'>'] = prelu
278 | return prelu
279 |
280 | def make_block(self, name, input, units):
281 | self.make_layer(name+'-A', input, units, alpha=0.1)
282 | # self.make_layer(name+'-B', self.last_layer(), units, alpha=1.0)
283 | return ElemwiseSumLayer([input, self.last_layer()]) if args.generator_residual else self.last_layer()
284 |
285 | def setup_generator(self, input, config):
286 | for k, v in config.items(): setattr(args, k, v)
287 | args.zoom = 2**(args.generator_upscale - args.generator_downscale)
288 |
289 | units_iter = extend(args.generator_filters)
290 | units = next(units_iter)
291 | self.make_layer('iter.0', input, units, filter_size=(7,7), pad=(3,3))
292 |
293 | for i in range(0, args.generator_downscale):
294 | self.make_layer('downscale%i'%i, self.last_layer(), next(units_iter), filter_size=(4,4), stride=(2,2))
295 |
296 | units = next(units_iter)
297 | for i in range(0, args.generator_blocks):
298 | self.make_block('iter.%i'%(i+1), self.last_layer(), units)
299 |
300 | for i in range(0, args.generator_upscale):
301 | u = next(units_iter)
302 | self.make_layer('upscale%i.2'%i, self.last_layer(), u*4)
303 | self.network['upscale%i.1'%i] = SubpixelReshuffleLayer(self.last_layer(), u, 2)
304 |
305 | self.network['out'] = ConvLayer(self.last_layer(), 3, filter_size=(7,7), pad=(3,3), nonlinearity=None)
306 |
307 | def setup_perceptual(self, input):
308 | """Use lasagne to create a network of convolution layers using pre-trained VGG19 weights.
309 | """
310 | offset = np.array([103.939, 116.779, 123.680], dtype=np.float32).reshape((1,3,1,1))
311 | self.network['percept'] = lasagne.layers.NonlinearityLayer(input, lambda x: ((x+0.5)*255.0) - offset)
312 |
313 | self.network['mse'] = self.network['percept']
314 | self.network['conv1_1'] = ConvLayer(self.network['percept'], 64, 3, pad=1)
315 | self.network['conv1_2'] = ConvLayer(self.network['conv1_1'], 64, 3, pad=1)
316 | self.network['pool1'] = PoolLayer(self.network['conv1_2'], 2, mode='max')
317 | self.network['conv2_1'] = ConvLayer(self.network['pool1'], 128, 3, pad=1)
318 | self.network['conv2_2'] = ConvLayer(self.network['conv2_1'], 128, 3, pad=1)
319 | self.network['pool2'] = PoolLayer(self.network['conv2_2'], 2, mode='max')
320 | self.network['conv3_1'] = ConvLayer(self.network['pool2'], 256, 3, pad=1)
321 | self.network['conv3_2'] = ConvLayer(self.network['conv3_1'], 256, 3, pad=1)
322 | self.network['conv3_3'] = ConvLayer(self.network['conv3_2'], 256, 3, pad=1)
323 | self.network['conv3_4'] = ConvLayer(self.network['conv3_3'], 256, 3, pad=1)
324 | self.network['pool3'] = PoolLayer(self.network['conv3_4'], 2, mode='max')
325 | self.network['conv4_1'] = ConvLayer(self.network['pool3'], 512, 3, pad=1)
326 | self.network['conv4_2'] = ConvLayer(self.network['conv4_1'], 512, 3, pad=1)
327 | self.network['conv4_3'] = ConvLayer(self.network['conv4_2'], 512, 3, pad=1)
328 | self.network['conv4_4'] = ConvLayer(self.network['conv4_3'], 512, 3, pad=1)
329 | self.network['pool4'] = PoolLayer(self.network['conv4_4'], 2, mode='max')
330 | self.network['conv5_1'] = ConvLayer(self.network['pool4'], 512, 3, pad=1)
331 | self.network['conv5_2'] = ConvLayer(self.network['conv5_1'], 512, 3, pad=1)
332 | self.network['conv5_3'] = ConvLayer(self.network['conv5_2'], 512, 3, pad=1)
333 | self.network['conv5_4'] = ConvLayer(self.network['conv5_3'], 512, 3, pad=1)
334 |
335 | def setup_discriminator(self):
336 | c = args.discriminator_size
337 | self.make_layer('disc1.1', batch_norm(self.network['conv1_2']), 1*c, filter_size=(5,5), stride=(2,2), pad=(2,2))
338 | self.make_layer('disc1.2', self.last_layer(), 1*c, filter_size=(5,5), stride=(2,2), pad=(2,2))
339 | self.make_layer('disc2', batch_norm(self.network['conv2_2']), 2*c, filter_size=(5,5), stride=(2,2), pad=(2,2))
340 | self.make_layer('disc3', batch_norm(self.network['conv3_2']), 3*c, filter_size=(3,3), stride=(1,1), pad=(1,1))
341 | hypercolumn = ConcatLayer([self.network['disc1.2>'], self.network['disc2>'], self.network['disc3>']])
342 | self.make_layer('disc4', hypercolumn, 4*c, filter_size=(1,1), stride=(1,1), pad=(0,0))
343 | self.make_layer('disc5', self.last_layer(), 3*c, filter_size=(3,3), stride=(2,2))
344 | self.make_layer('disc6', self.last_layer(), 2*c, filter_size=(1,1), stride=(1,1), pad=(0,0))
345 | self.network['disc'] = batch_norm(ConvLayer(self.last_layer(), 1, filter_size=(1,1),
346 | nonlinearity=lasagne.nonlinearities.linear))
347 |
348 |
349 | #------------------------------------------------------------------------------------------------------------------
350 | # Input / Output
351 | #------------------------------------------------------------------------------------------------------------------
352 |
353 | def load_perceptual(self):
354 | """Open the serialized parameters from a pre-trained network, and load them into the model created.
355 | """
356 | vgg19_file = os.path.join(os.path.dirname(__file__), 'vgg19_conv.pkl.bz2')
357 | if not os.path.exists(vgg19_file):
358 | error("Model file with pre-trained convolution layers not found. Download here...",
359 | "https://github.com/alexjc/neural-doodle/releases/download/v0.0/vgg19_conv.pkl.bz2")
360 |
361 | data = pickle.load(bz2.open(vgg19_file, 'rb'))
362 | layers = lasagne.layers.get_all_layers(self.last_layer(), treat_as_input=[self.network['percept']])
363 | for p, d in zip(itertools.chain(*[l.get_params() for l in layers]), data): p.set_value(d)
364 |
365 | def list_generator_layers(self):
366 | for l in lasagne.layers.get_all_layers(self.network['out'], treat_as_input=[self.network['img']]):
367 | if not l.get_params(): continue
368 | name = list(self.network.keys())[list(self.network.values()).index(l)]
369 | yield (name, l)
370 |
371 | def get_filename(self, absolute=False):
372 | filename = 'ne%ix-%s-%s-%s.pkl.bz2' % (args.zoom, args.type, args.model, __version__)
373 | return os.path.join(os.path.dirname(__file__), filename) if absolute else filename
374 |
375 | def save_generator(self):
376 | def cast(p): return p.get_value().astype(np.float16)
377 | params = {k: [cast(p) for p in l.get_params()] for (k, l) in self.list_generator_layers()}
378 | config = {k: getattr(args, k) for k in ['generator_blocks', 'generator_residual', 'generator_filters'] + \
379 | ['generator_upscale', 'generator_downscale']}
380 |
381 | pickle.dump((config, params), bz2.open(self.get_filename(absolute=True), 'wb'))
382 | print(' - Saved model as `{}` after training.'.format(self.get_filename()))
383 |
384 | def load_model(self):
385 | if not os.path.exists(self.get_filename(absolute=True)):
386 | if args.train: return {}, {}
387 | error("Model file with pre-trained convolution layers not found. Download it here...",
388 | "https://github.com/alexjc/neural-enhance/releases/download/v%s/%s"%(__version__, self.get_filename()))
389 | print(' - Loaded file `{}` with trained model.'.format(self.get_filename()))
390 | return pickle.load(bz2.open(self.get_filename(absolute=True), 'rb'))
391 |
392 | def load_generator(self, params):
393 | if len(params) == 0: return
394 | for k, l in self.list_generator_layers():
395 | assert k in params, "Couldn't find layer `%s` in loaded model.'" % k
396 | assert len(l.get_params()) == len(params[k]), "Mismatch in types of layers."
397 | for p, v in zip(l.get_params(), params[k]):
398 | assert v.shape == p.get_value().shape, "Mismatch in number of parameters for layer {}.".format(k)
399 | p.set_value(v.astype(np.float32))
400 |
401 | #------------------------------------------------------------------------------------------------------------------
402 | # Training & Loss Functions
403 | #------------------------------------------------------------------------------------------------------------------
404 |
405 | def loss_perceptual(self, p):
406 | return lasagne.objectives.squared_error(p[:args.batch_size], p[args.batch_size:]).mean()
407 |
408 | def loss_total_variation(self, x):
409 | return T.mean(((x[:,:,:-1,:-1] - x[:,:,1:,:-1])**2 + (x[:,:,:-1,:-1] - x[:,:,:-1,1:])**2)**1.25)
410 |
411 | def loss_adversarial(self, d):
412 | return T.mean(1.0 - T.nnet.softminus(d[args.batch_size:]))
413 |
414 | def loss_discriminator(self, d):
415 | return T.mean(T.nnet.softminus(d[args.batch_size:]) - T.nnet.softplus(d[:args.batch_size]))
416 |
417 | def compile(self):
418 | # Helper function for rendering test images during training, or standalone inference mode.
419 | input_tensor, seed_tensor = T.tensor4(), T.tensor4()
420 | input_layers = {self.network['img']: input_tensor, self.network['seed']: seed_tensor}
421 | output = lasagne.layers.get_output([self.network[k] for k in ['seed','out']], input_layers, deterministic=True)
422 | self.predict = theano.function([seed_tensor], output)
423 |
424 | if not args.train: return
425 |
426 | output_layers = [self.network['out'], self.network[args.perceptual_layer], self.network['disc']]
427 | gen_out, percept_out, disc_out = lasagne.layers.get_output(output_layers, input_layers, deterministic=False)
428 |
429 | # Generator loss function, parameters and updates.
430 | self.gen_lr = theano.shared(np.array(0.0, dtype=theano.config.floatX))
431 | self.adversary_weight = theano.shared(np.array(0.0, dtype=theano.config.floatX))
432 | gen_losses = [self.loss_perceptual(percept_out) * args.perceptual_weight,
433 | self.loss_total_variation(gen_out) * args.smoothness_weight,
434 | self.loss_adversarial(disc_out) * self.adversary_weight]
435 | gen_params = lasagne.layers.get_all_params(self.network['out'], trainable=True)
436 | print(' - {} tensors learned for generator.'.format(len(gen_params)))
437 | gen_updates = lasagne.updates.adam(sum(gen_losses, 0.0), gen_params, learning_rate=self.gen_lr)
438 |
439 | # Discriminator loss function, parameters and updates.
440 | self.disc_lr = theano.shared(np.array(0.0, dtype=theano.config.floatX))
441 | disc_losses = [self.loss_discriminator(disc_out)]
442 | disc_params = list(itertools.chain(*[l.get_params() for k, l in self.network.items() if 'disc' in k]))
443 | print(' - {} tensors learned for discriminator.'.format(len(disc_params)))
444 | grads = [g.clip(-5.0, +5.0) for g in T.grad(sum(disc_losses, 0.0), disc_params)]
445 | disc_updates = lasagne.updates.adam(grads, disc_params, learning_rate=self.disc_lr)
446 |
447 | # Combined Theano function for updating both generator and discriminator at the same time.
448 | updates = collections.OrderedDict(list(gen_updates.items()) + list(disc_updates.items()))
449 | self.fit = theano.function([input_tensor, seed_tensor], gen_losses + [disc_out.mean(axis=(1,2,3))], updates=updates)
450 |
451 |
452 |
453 | class NeuralEnhancer(object):
454 |
455 | def __init__(self, loader):
456 | if args.train:
457 | print('{}Training {} epochs on random image sections with batch size {}.{}'\
458 | .format(ansi.BLUE_B, args.epochs, args.batch_size, ansi.BLUE))
459 | else:
460 | if len(args.files) == 0: error("Specify the image(s) to enhance on the command-line.")
461 | print('{}Enhancing {} image(s) specified on the command-line.{}'\
462 | .format(ansi.BLUE_B, len(args.files), ansi.BLUE))
463 |
464 | self.thread = DataLoader() if loader else None
465 | self.model = Model()
466 |
467 | print('{}'.format(ansi.ENDC))
468 |
469 | def imsave(self, fn, img):
470 | scipy.misc.toimage(np.transpose(img + 0.5, (1, 2, 0)).clip(0.0, 1.0) * 255.0, cmin=0, cmax=255).save(fn)
471 |
472 | def show_progress(self, orign, scald, repro):
473 | os.makedirs('valid', exist_ok=True)
474 | for i in range(args.batch_size):
475 | self.imsave('valid/%s_%03i_origin.png' % (args.model, i), orign[i])
476 | self.imsave('valid/%s_%03i_pixels.png' % (args.model, i), scald[i])
477 | self.imsave('valid/%s_%03i_reprod.png' % (args.model, i), repro[i])
478 |
479 | def decay_learning_rate(self):
480 | l_r, t_cur = args.learning_rate, 0
481 |
482 | while True:
483 | yield l_r
484 | t_cur += 1
485 | if t_cur % args.learning_period == 0: l_r *= args.learning_decay
486 |
487 | def train(self):
488 | seed_size = args.batch_shape // args.zoom
489 | images = np.zeros((args.batch_size, 3, args.batch_shape, args.batch_shape), dtype=np.float32)
490 | seeds = np.zeros((args.batch_size, 3, seed_size, seed_size), dtype=np.float32)
491 | learning_rate = self.decay_learning_rate()
492 | try:
493 | average, start = None, time.time()
494 | for epoch in range(args.epochs):
495 | total, stats = None, None
496 | l_r = next(learning_rate)
497 | if epoch >= args.generator_start: self.model.gen_lr.set_value(l_r)
498 | if epoch >= args.discriminator_start: self.model.disc_lr.set_value(l_r)
499 |
500 | for _ in range(args.epoch_size):
501 | self.thread.copy(images, seeds)
502 | output = self.model.fit(images, seeds)
503 | losses = np.array(output[:3], dtype=np.float32)
504 | stats = (stats + output[3]) if stats is not None else output[3]
505 | total = total + losses if total is not None else losses
506 | l = np.sum(losses)
507 | assert not np.isnan(losses).any()
508 | average = l if average is None else average * 0.95 + 0.05 * l
509 | print('↑' if l > average else '↓', end='', flush=True)
510 |
511 | scald, repro = self.model.predict(seeds)
512 | self.show_progress(images, scald, repro)
513 | total /= args.epoch_size
514 | stats /= args.epoch_size
515 | totals, labels = [sum(total)] + list(total), ['total', 'prcpt', 'smthn', 'advrs']
516 | gen_info = ['{}{}{}={:4.2e}'.format(ansi.WHITE_B, k, ansi.ENDC, v) for k, v in zip(labels, totals)]
517 | print('\rEpoch #{} at {:4.1f}s, lr={:4.2e}{}'.format(epoch+1, time.time()-start, l_r, ' '*(args.epoch_size-30)))
518 | print(' - generator {}'.format(' '.join(gen_info)))
519 |
520 | real, fake = stats[:args.batch_size], stats[args.batch_size:]
521 | print(' - discriminator', real.mean(), len(np.where(real > 0.5)[0]),
522 | fake.mean(), len(np.where(fake < -0.5)[0]))
523 | if epoch == args.adversarial_start-1:
524 | print(' - generator now optimizing against discriminator.')
525 | self.model.adversary_weight.set_value(args.adversary_weight)
526 | running = None
527 | if (epoch+1) % args.save_every == 0:
528 | print(' - saving current generator layers to disk...')
529 | self.model.save_generator()
530 |
531 | except KeyboardInterrupt:
532 | pass
533 |
534 | print('\n{}Trained {}x super-resolution for {} epochs.{}'\
535 | .format(ansi.CYAN_B, args.zoom, epoch+1, ansi.CYAN))
536 | self.model.save_generator()
537 | print(ansi.ENDC)
538 |
539 | def match_histograms(self, A, B, rng=(0.0, 255.0), bins=64):
540 | (Ha, Xa), (Hb, Xb) = [np.histogram(i, bins=bins, range=rng, density=True) for i in [A, B]]
541 | X = np.linspace(rng[0], rng[1], bins, endpoint=True)
542 | Hpa, Hpb = [np.cumsum(i) * (rng[1] - rng[0]) ** 2 / float(bins) for i in [Ha, Hb]]
543 | inv_Ha = scipy.interpolate.interp1d(X, Hpa, bounds_error=False, fill_value='extrapolate')
544 | map_Hb = scipy.interpolate.interp1d(Hpb, X, bounds_error=False, fill_value='extrapolate')
545 | return map_Hb(inv_Ha(A).clip(0.0, 255.0))
546 |
547 | def process(self, original):
548 | # Snap the image to a shape that's compatible with the generator (2x, 4x)
549 | s = 2 ** max(args.generator_upscale, args.generator_downscale)
550 | by, bx = original.shape[0] % s, original.shape[1] % s
551 | original = original[by-by//2:original.shape[0]-by//2,bx-bx//2:original.shape[1]-bx//2,:]
552 |
553 | # Prepare paded input image as well as output buffer of zoomed size.
554 | s, p, z = args.rendering_tile, args.rendering_overlap, args.zoom
555 | image = np.pad(original, ((p, p), (p, p), (0, 0)), mode='reflect')
556 | output = np.zeros((original.shape[0] * z, original.shape[1] * z, 3), dtype=np.float32)
557 |
558 | # Iterate through the tile coordinates and pass them through the network.
559 | for y, x in itertools.product(range(0, original.shape[0], s), range(0, original.shape[1], s)):
560 | img = np.transpose(image[y:y+p*2+s,x:x+p*2+s,:] / 255.0 - 0.5, (2, 0, 1))[np.newaxis].astype(np.float32)
561 | *_, repro = self.model.predict(img)
562 | output[y*z:(y+s)*z,x*z:(x+s)*z,:] = np.transpose(repro[0] + 0.5, (1, 2, 0))[p*z:-p*z,p*z:-p*z,:]
563 | print('.', end='', flush=True)
564 | output = output.clip(0.0, 1.0) * 255.0
565 |
566 | # Match color histograms if the user specified this option.
567 | if args.rendering_histogram:
568 | for i in range(3):
569 | output[:,:,i] = self.match_histograms(output[:,:,i], original[:,:,i])
570 |
571 | return scipy.misc.toimage(output, cmin=0, cmax=255)
572 |
573 |
574 | if __name__ == "__main__":
575 | if args.train:
576 | args.zoom = 2**(args.generator_upscale - args.generator_downscale)
577 | enhancer = NeuralEnhancer(loader=True)
578 | enhancer.train()
579 | else:
580 | enhancer = NeuralEnhancer(loader=False)
581 | for filename in args.files:
582 | print(filename, end=' ')
583 | img = scipy.ndimage.imread(filename, mode='RGB')
584 | out = enhancer.process(img)
585 | out.save(os.path.splitext(filename)[0]+'_ne%ix.png' % args.zoom)
586 | print(flush=True)
587 | print(ansi.ENDC)
588 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | colorama
2 | pillow>=3.2.0
3 | Theano==0.8.2
4 | git+https://github.com/Lasagne/Lasagne.git@61b1ad1#egg=Lasagne==0.2-dev
--------------------------------------------------------------------------------
/train/ne1x-photo-repair.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | python3.4 enhance.py \
4 | --train "$OPEN_IMAGES_PATH/*/*.jpg" --type photo --model repair \
5 | --epochs=50 --batch-shape=256 --device=gpu1 \
6 | --generator-downscale=2 --generator-upscale=2 \
7 | --generator-blocks=8 --generator-filters=128 --generator-residual=0 \
8 | --perceptual-layer=conv2_2 --smoothness-weight=1e7 --adversary-weight=0.0 \
9 | --train-noise=2.0 --train-jpeg=30
10 |
11 | python3.4 enhance.py \
12 | --train "$OPEN_IMAGES_PATH/*/*.jpg" --type photo --model repair \
13 | --epochs=500 --batch-shape=240 --device=gpu1 \
14 | --generator-downscale=2 --generator-upscale=2 \
15 | --perceptual-layer=conv5_2 --smoothness-weight=5e3 --adversary-weight=5e1 \
16 | --generator-start=10 --discriminator-start=0 --adversarial-start=10 \
17 | --discriminator-size=48 \
18 | --train-noise=2.0 --train-jpeg=30
19 |
--------------------------------------------------------------------------------
/train/ne2x-photo-default.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | python3.4 enhance.py \
4 | --train "$OPEN_IMAGES_PATH/*/*.jpg" --type photo --model default \
5 | --epochs=50 --batch-shape=256 --device=gpu0 \
6 | --generator-downscale=0 --generator-upscale=1 \
7 | --generator-blocks=8 --generator-filters=128 --generator-residual=0 \
8 | --perceptual-layer=conv2_2 --smoothness-weight=1e7 --adversary-weight=0.0 \
9 | --train-noise=1.0
10 |
11 | python3.4 enhance.py \
12 | --train "$OPEN_IMAGES_PATH/*/*.jpg" --type photo --model default \
13 | --epochs=500 --batch-shape=240 --device=gpu0 \
14 | --generator-downscale=0 --generator-upscale=1 \
15 | --perceptual-layer=conv5_2 --smoothness-weight=5e3 --adversary-weight=5e1 \
16 | --generator-start=10 --discriminator-start=0 --adversarial-start=10 \
17 | --discriminator-size=64 \
18 | --train-noise=1.0
19 |
--------------------------------------------------------------------------------