├── .gitignore
├── LICENSE
├── README.md
├── download_models.sh
├── images
├── boy.png
├── cartoon2.jpg
├── dogsketch.png
├── flowers.png
├── girl2.png
├── girl3.jpg
├── girlmrf.jpg
├── girlsketch.jpg
├── goat.png
├── kid5.png
├── megan.png
├── muse.jpg
├── smallworldI.jpg
└── starry_night.jpg
├── lap_style.lua
├── laplacian.py
├── logstat.py
├── multi-lap-test.sh
├── neural-doodle
└── doodle.py
├── output
├── boy_girl3_5_0.png
├── boy_girl3_5_100.png
├── combinations
│ ├── girlmrf_dogsketch5_1,2_50,100.png
│ ├── girlmrf_dogsketch5_1,3_50,400.png
│ ├── girlmrf_dogsketch5_1_50.png
│ ├── girlmrf_dogsketch5_2,3_100,400.png
│ ├── girlmrf_dogsketch5_2,4_100,1600.png
│ ├── girlmrf_dogsketch5_2_100.png
│ ├── girlmrf_dogsketch_5_0.png
│ ├── girlmrf_dogsketch_5_100.png
│ └── girlmrf_dogsketch_5_200.png
├── girl2_cartoon2_20_0.jpg
├── girl2_cartoon2_20_100.png
├── girlmrf_girlsketch_5_0.png
├── girlmrf_girlsketch_5_100.png
├── girlmrf_smallworldI_20_0.png
├── girlmrf_smallworldI_20_200.png
├── goat_muse20_1_0.png
├── goat_muse20_2_100.png
├── kid5_smallworldI_20_0.png
├── kid5_smallworldI_20_200.png
├── laplacians
│ ├── girl2_car2_0_edge.png
│ ├── girl2_car2_edge.png
│ └── girl2_edge.png
├── megan_flowers20_0.png
├── megan_flowers20_100.png
├── megan_starry10_0.png
└── megan_starry10_100.png
├── single-lap-exp.sh
└── tf-neural-style
├── neural_style.py
├── stylize.py
└── vgg.py
/.gitignore:
--------------------------------------------------------------------------------
1 | commit.bat
2 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Lapstyle: Laplacian-Steered Neural Style Transfer
2 | Code and test images for the paper "[Laplacian-Steered Neural Style Transfer](https://arxiv.org/abs/1707.01253)".
3 |
4 | Lapstyle extends an existing neural style transfer method with one or multiple Laplacian loss layers. The following three neural style transfer implementations have been extended:
5 |
6 | * **lap_style.lua** (*Recommended!*) - https://github.com/jcjohnson/neural-style Gatys-style[1] implemented by Justin Johnson, using the L-BFGS optimization method.
7 | * **tf-neural-style/neural_style.py** - https://github.com/anishathalye/neural-style Gatys-style[1] by Anish Athalye, using Adam.
8 | * **neural-doodle/doodle.py** - https://github.com/alexjc/neural-doodle MRF-CNN[2] implemented by Alex J. Champandard.
9 |
10 | The implementation by Justin Johnson clearly produces the best images (either the original [neural_style.lua](https://github.com/jcjohnson/neural-style/blob/master/neural_style.lua) or the extended [lap_style.lua](https://github.com/askerlee/lapstyle/blob/master/lap_style.lua)). The corresponding content and style losses are also the smallest. Its superiority seems to be ascribed to the L-BFGS optimization, since the algorithm is otherwise identical to Anish Athalye's implementation.
11 |
12 | ## Setup:
13 | The setup procedures are the same as those of each original project. The following procedures for **lap_style.lua** are quoted from https://github.com/jcjohnson/neural-style:
14 |
15 | Dependencies:
16 | * [torch7](https://github.com/torch/torch7)
17 | * [loadcaffe](https://github.com/szagoruyko/loadcaffe)
18 |
19 | Optional dependencies:
20 | * For CUDA backend:
21 | * CUDA 6.5+
22 | * [cunn](https://github.com/torch/cunn)
23 | * For cuDNN backend:
24 | * [cudnn.torch](https://github.com/soumith/cudnn.torch)
25 | * For OpenCL backend:
26 | * [cltorch](https://github.com/hughperkins/cltorch)
27 | * [clnn](https://github.com/hughperkins/clnn)
28 |
29 | After installing dependencies, you'll need to run the following script to download the VGG model:
30 | ```
31 | sh models/download_models.sh
32 | ```
33 | This will download the original [VGG-19 model](https://gist.github.com/ksimonyan/3785162f95cd2d5fee77#file-readme-md).
34 |
35 |
36 | ### Sample usage:
37 | ```
38 | th lap_style.lua -style_image images/flowers.png -content_image images/megan.png -output_image output/megan_flowers20_100.png -content_weight 20 -lap_layers 2 -lap_weights 100
39 | ```
40 |
41 | ### Sample images:
42 |
43 |
44 | 
45 |
46 |
47 |
48 |
49 |
50 | 
51 |
52 |
53 |
54 |
55 | The four images in each group are: 1) content image, 2) style image, 3) image synthesized with the original Gatys-style, and 4) image synthesized with Lapstyle.
56 |
57 | Note: although photo-realistic style transfer[3] (https://github.com/luanfujun/deep-photo-styletransfer) performs amazingly well on their test images, it doesn't work on the images we tested. Seems that in order to make it work well, the content image and the style image has to have highly similar layout and semantic contents.
58 |
59 | ### Citation
60 | You are welcome to cite the paper (https://arxiv.org/abs/1707.01253) with this bibtex:
61 |
62 | ```
63 | @InProceedings{lapstyle,
64 | author = {Shaohua Li and Xinxing Xu and Liqiang Nie and Tat-Seng Chua},
65 | title = {Laplacian-Steered Neural Style Transfer},
66 | booktitle = {Proceedings of the ACM Multimedia Conference (MM), to appear.},
67 | year = {2017},
68 | }
69 | ```
70 |
71 | ### References
72 | [1] Leon A Gatys, Alexander S Ecker,and Matthias Bethge. 2016. Image style transfer using convolutional neural networks. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition. 2414–2423.
73 |
74 | [2] Chuan Li and Michael Wand. 2016. Combining markov random fields and convolutional neural networks for image synthesis. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition. 2479–2486.
75 |
76 | [3] Fujun Luan, Sylvain Paris, Eli Shechtman, and Kavita Bala. 2017. Deep Photo Style Transfer. arXiv preprint arXiv:1703.07511 (2017).
77 |
--------------------------------------------------------------------------------
/download_models.sh:
--------------------------------------------------------------------------------
1 | cd models
2 | wget -c https://gist.githubusercontent.com/ksimonyan/3785162f95cd2d5fee77/raw/bb2b4fe0a9bb0669211cf3d0bc949dfdda173e9e/VGG_ILSVRC_19_layers_deploy.prototxt
3 | wget -c --no-check-certificate https://bethgelab.org/media/uploads/deeptextures/vgg_normalised.caffemodel
4 | wget -c http://www.robots.ox.ac.uk/~vgg/software/very_deep/caffe/VGG_ILSVRC_19_layers.caffemodel
5 | cd ..
6 |
--------------------------------------------------------------------------------
/images/boy.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/images/boy.png
--------------------------------------------------------------------------------
/images/cartoon2.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/images/cartoon2.jpg
--------------------------------------------------------------------------------
/images/dogsketch.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/images/dogsketch.png
--------------------------------------------------------------------------------
/images/flowers.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/images/flowers.png
--------------------------------------------------------------------------------
/images/girl2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/images/girl2.png
--------------------------------------------------------------------------------
/images/girl3.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/images/girl3.jpg
--------------------------------------------------------------------------------
/images/girlmrf.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/images/girlmrf.jpg
--------------------------------------------------------------------------------
/images/girlsketch.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/images/girlsketch.jpg
--------------------------------------------------------------------------------
/images/goat.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/images/goat.png
--------------------------------------------------------------------------------
/images/kid5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/images/kid5.png
--------------------------------------------------------------------------------
/images/megan.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/images/megan.png
--------------------------------------------------------------------------------
/images/muse.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/images/muse.jpg
--------------------------------------------------------------------------------
/images/smallworldI.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/images/smallworldI.jpg
--------------------------------------------------------------------------------
/images/starry_night.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/images/starry_night.jpg
--------------------------------------------------------------------------------
/lap_style.lua:
--------------------------------------------------------------------------------
1 | require 'torch'
2 | require 'nn'
3 | require 'image'
4 | require 'optim'
5 | require 'math'
6 |
7 | require 'loadcaffe'
8 |
9 |
10 | local cmd = torch.CmdLine()
11 |
12 | -- Basic options
13 | cmd:option('-style_image', 'examples/inputs/seated-nude.jpg',
14 | 'Style target image')
15 | cmd:option('-style_blend_weights', 'nil')
16 | cmd:option('-content_image', 'examples/inputs/tubingen.jpg',
17 | 'Content target image')
18 | -- cmd:option('-image_size', 512, 'Maximum height / width of generated image')
19 | cmd:option('-gpu', '0', 'Zero-indexed ID of the GPU to use; for CPU mode set -gpu = -1')
20 | cmd:option('-multigpu_strategy', '', 'Index of layers to split the network across GPUs')
21 |
22 | -- Optimization options
23 | cmd:option('-content_weight', 5e0)
24 | cmd:option('-style_weight', 1e2)
25 |
26 | cmd:option('-lap_weights', '100')
27 | cmd:option('-lap_layers', '2')
28 | cmd:option('-lap_nobp', false)
29 |
30 | cmd:option('-tv_weight', 1e-3)
31 | cmd:option('-num_iterations', 1000)
32 | cmd:option('-normalize_gradients', false)
33 | cmd:option('-init', 'random', 'random|image')
34 | cmd:option('-init_image', '')
35 | cmd:option('-optimizer', 'lbfgs', 'lbfgs|adam')
36 | cmd:option('-learning_rate', 1e1)
37 | cmd:option('-lbfgs_num_correction', 0)
38 |
39 | -- Output options
40 | cmd:option('-print_iter', 50)
41 | cmd:option('-save_iter', 100)
42 | cmd:option('-output_image', 'out.png')
43 |
44 | -- Other options
45 | cmd:option('-style_scale', 1.0)
46 | cmd:option('-original_colors', 0)
47 | cmd:option('-pooling', 'max', 'max|avg')
48 | cmd:option('-proto_file', 'models/VGG_ILSVRC_19_layers_deploy.prototxt')
49 | cmd:option('-model_file', 'models/VGG_ILSVRC_19_layers.caffemodel')
50 | cmd:option('-backend', 'nn', 'nn|cudnn|clnn')
51 | cmd:option('-cudnn_autotune', false)
52 | cmd:option('-seed', -1)
53 |
54 | cmd:option('-content_layers', 'relu4_2', 'layers for content')
55 | cmd:option('-style_layers', 'relu1_1,relu2_1,relu3_1,relu4_1,relu5_1', 'layers for style')
56 |
57 |
58 | local function main(params)
59 | local dtype, multigpu = setup_gpu(params)
60 |
61 | local loadcaffe_backend = params.backend
62 | if params.backend == 'clnn' then loadcaffe_backend = 'nn' end
63 | local cnn = loadcaffe.load(params.proto_file, params.model_file, loadcaffe_backend):type(dtype)
64 |
65 | local content_image = image.load(params.content_image, 3)
66 | -- content_image = image.scale(content_image, params.image_size, 'bilinear')
67 | local content_image_caffe = preprocess(content_image):float()
68 |
69 | -- local style_size = math.ceil(params.style_scale * params.image_size)
70 | local style_image_list = params.style_image:split(',')
71 | local style_images_caffe = {}
72 | for _, img_path in ipairs(style_image_list) do
73 | local img = image.load(img_path, 3)
74 | -- img = image.scale(img, style_size, 'bilinear')
75 | local img_caffe = preprocess(img):float()
76 | table.insert(style_images_caffe, img_caffe)
77 | end
78 |
79 | local init_image = nil
80 | if params.init_image ~= '' then
81 | init_image = image.load(params.init_image, 3)
82 | local H, W = content_image:size(2), content_image:size(3)
83 | init_image = image.scale(init_image, W, H, 'bilinear')
84 | init_image = preprocess(init_image):float()
85 | end
86 |
87 | -- Handle style blending weights for multiple style inputs
88 | local style_blend_weights = nil
89 | if params.style_blend_weights == 'nil' then
90 | -- Style blending not specified, so use equal weighting
91 | style_blend_weights = {}
92 | for i = 1, #style_image_list do
93 | table.insert(style_blend_weights, 1.0)
94 | end
95 | else
96 | style_blend_weights = params.style_blend_weights:split(',')
97 | assert(#style_blend_weights == #style_image_list,
98 | '-style_blend_weights and -style_images must have the same number of elements')
99 | end
100 | -- Normalize the style blending weights so they sum to 1
101 | local style_blend_sum = 0
102 | for i = 1, #style_blend_weights do
103 | style_blend_weights[i] = tonumber(style_blend_weights[i])
104 | style_blend_sum = style_blend_sum + style_blend_weights[i]
105 | end
106 | for i = 1, #style_blend_weights do
107 | style_blend_weights[i] = style_blend_weights[i] / style_blend_sum
108 | end
109 |
110 | local content_layers = params.content_layers:split(",")
111 | local style_layers = params.style_layers:split(",")
112 |
113 | local lap_layers = params.lap_layers:split(",")
114 | for i = 1, #lap_layers do
115 | lap_layers[i] = tonumber(lap_layers[i])
116 | end
117 | local lap_weights = params.lap_weights:split(",")
118 | for i = 1, #lap_weights do
119 | lap_weights[i] = tonumber(lap_weights[i])
120 | end
121 | assert( #lap_layers == #lap_weights )
122 |
123 | -- Set up the network, inserting style and content loss modules
124 | local content_losses, style_losses, lap_losses = {}, {}, {}
125 | local next_content_idx, next_style_idx = 1, 1
126 | local net1 = nn.Sequential()
127 | if params.tv_weight > 0 then
128 | local tv_mod = nn.TVLoss(params.tv_weight):type(dtype)
129 | net1:add(tv_mod)
130 | end
131 | for i = 1, #cnn do
132 | if next_content_idx <= #content_layers or next_style_idx <= #style_layers then
133 | local layer = cnn:get(i)
134 | local name = layer.name
135 | local layer_type = torch.type(layer)
136 | local is_pooling = (layer_type == 'cudnn.SpatialMaxPooling' or layer_type == 'nn.SpatialMaxPooling')
137 | if is_pooling and params.pooling == 'avg' then
138 | assert(layer.padW == 0 and layer.padH == 0)
139 | local kW, kH = layer.kW, layer.kH
140 | local dW, dH = layer.dW, layer.dH
141 | local avg_pool_layer = nn.SpatialAveragePooling(kW, kH, dW, dH):type(dtype)
142 | local msg = 'Replacing max pooling at layer %d with average pooling'
143 | print(string.format(msg, i))
144 | net1:add(avg_pool_layer)
145 | else
146 | net1:add(layer)
147 | end
148 | if name == content_layers[next_content_idx] then
149 | print("Setting up content layer", i, ":", layer.name)
150 | local norm = params.normalize_gradients
151 | local loss_module = nn.ContentLoss(params.content_weight, norm):type(dtype)
152 | net1:add(loss_module)
153 | table.insert(content_losses, loss_module)
154 | next_content_idx = next_content_idx + 1
155 | end
156 | if name == style_layers[next_style_idx] then
157 | print("Setting up style layer ", i, ":", layer.name)
158 | local norm = params.normalize_gradients
159 | local loss_module = nn.StyleLoss(params.style_weight, norm):type(dtype)
160 | net1:add(loss_module)
161 | table.insert(style_losses, loss_module)
162 | next_style_idx = next_style_idx + 1
163 | end
164 | end
165 | end
166 |
167 | local net = nn.ConcatTable()
168 | net:add(net1)
169 |
170 | --[[
171 | local function lapofGauss(size, sigma)
172 | local center = 0.5 * size + 0.5
173 | local logauss = torch.Tensor(size,size)
174 | for i=1,size do
175 | for j=1,size do
176 | xsq = math.pow((i-center)/sigma,2)/2
177 | ysq = math.pow((j-center)/sigma,2)/2
178 | derivCoef = 1 - (xsq + ysq)
179 | logauss[i][j] = derivCoef * math.exp(-(xsq + ysq))
180 | end
181 | end
182 | logauss = logauss - logauss:sum() / (size*size)
183 | logauss = logauss / logauss[{math.floor(center),math.floor(center)}]
184 | return logauss
185 | end
186 |
187 | local ks = 5
188 | logauss = lapofGauss(ks,0.5)
189 | lapW = torch.Tensor(1,3,ks,ks)
190 | for i = 1, 3 do
191 | lapW[{1,i,{},{}}] = logauss
192 | end
193 |
194 | --]]
195 |
196 | -- conv weight shape: out_channels, in_channels, kernel_size[0], kernel_size[1]
197 | local ks = 3
198 | laplacian = torch.Tensor(3,3):zero()
199 | laplacian[{1,2}] = -1.0
200 | laplacian[{2,1}] = -1.0
201 | laplacian[{2,2}] = 4.0
202 | laplacian[{2,3}] = -1.0
203 | laplacian[{3,2}] = -1.0
204 | lapW = torch.Tensor(1,3,3,3)
205 | for i = 1, 3 do
206 | lapW[{1,i,{},{}}] = laplacian
207 | end
208 |
209 | stride = math.floor(ks/2)
210 | for i = 1, #lap_layers do
211 | local netlap = nn.Sequential()
212 | local ps = math.pow(2, lap_layers[i])
213 | local avg_pool_layer = nn.SpatialAveragePooling(ps, ps, ps, ps):type(dtype)
214 | netlap:add(avg_pool_layer)
215 | local conv_layer = nn.SpatialConvolution(3,1,ks,ks,stride,stride):type(dtype)
216 | conv_layer.weight = lapW
217 | netlap:add(conv_layer)
218 | local norm = params.normalize_gradients
219 | local loss_module = nn.ContentLoss(lap_weights[i], norm):type(dtype)
220 | netlap:add(loss_module)
221 | table.insert(content_losses, loss_module)
222 | table.insert(lap_losses, loss_module)
223 | net:add(netlap)
224 | end
225 |
226 | -- print(string.format('content losses: %d', #content_losses))
227 |
228 | if multigpu then
229 | net = setup_multi_gpu(net, params)
230 | end
231 | net:type(dtype)
232 |
233 | -- Capture content targets
234 | for i = 1, #content_losses do
235 | content_losses[i].mode = 'capture'
236 | end
237 | print 'Capturing content targets'
238 | print(net)
239 | content_image_caffe = content_image_caffe:type(dtype)
240 | net:forward(content_image_caffe:type(dtype))
241 |
242 | -- Capture style targets
243 | for i = 1, #content_losses do
244 | content_losses[i].mode = 'none'
245 | end
246 | for i = 1, #style_images_caffe do
247 | print(string.format('Capturing style target %d', i))
248 | for j = 1, #style_losses do
249 | style_losses[j].mode = 'capture'
250 | style_losses[j].blend_weight = style_blend_weights[i]
251 | end
252 | net:forward(style_images_caffe[i]:type(dtype))
253 | end
254 |
255 | -- Set all loss modules to loss mode
256 | for i = 1, #content_losses do
257 | content_losses[i].mode = 'loss'
258 | end
259 |
260 | if params.lap_nobp then
261 | for i = 1, #lap_losses do
262 | lap_losses[i].strength_bp = 0
263 | end
264 | end
265 |
266 | for i = 1, #style_losses do
267 | style_losses[i].mode = 'loss'
268 | end
269 |
270 | -- We don't need the base CNN anymore, so clean it up to save memory.
271 | cnn = nil
272 | for i=1, #net.modules do
273 | local module = net.modules[i]
274 | if torch.type(module) == 'nn.SpatialConvolutionMM' then
275 | -- remove these, not used, but uses gpu memory
276 | module.gradWeight = nil
277 | module.gradBias = nil
278 | end
279 | end
280 | collectgarbage()
281 |
282 | -- Initialize the image
283 | if params.seed >= 0 then
284 | torch.manualSeed(params.seed)
285 | end
286 | local img = nil
287 | if params.init == 'random' then
288 | img = torch.randn(content_image:size()):float():mul(0.001)
289 | elseif params.init == 'image' then
290 | if init_image then
291 | img = init_image:clone()
292 | else
293 | img = content_image_caffe:clone()
294 | end
295 | else
296 | error('Invalid init type')
297 | end
298 | img = img:type(dtype)
299 |
300 | -- Run it through the network once to get the proper size for the gradient
301 | -- All the gradients will come from the extra loss modules, so we just pass
302 | -- zeros into the top of the net on the backward pass.
303 | local y = net:forward(img)
304 | local dy = img.new(#y):zero()
305 |
306 | -- Declaring this here lets us access it in maybe_print
307 | local optim_state = nil
308 | if params.optimizer == 'lbfgs' then
309 | optim_state = {
310 | maxIter = params.num_iterations,
311 | verbose=true,
312 | tolX=-1,
313 | tolFun=-1,
314 | }
315 | if params.lbfgs_num_correction > 0 then
316 | optim_state.nCorrection = params.lbfgs_num_correction
317 | end
318 | elseif params.optimizer == 'adam' then
319 | optim_state = {
320 | learningRate = params.learning_rate,
321 | }
322 | else
323 | error(string.format('Unrecognized optimizer "%s"', params.optimizer))
324 | end
325 |
326 | local function maybe_print(t, loss)
327 | local verbose = params.print_iter > 0 and
328 | (t % params.print_iter == 0 or t == params.num_iterations - 1)
329 | if verbose then
330 | print(string.format('Iteration %d / %d', t, params.num_iterations))
331 | for i, loss_module in ipairs(content_losses) do
332 | print(string.format(' Content %d loss: %f', i, loss_module.loss))
333 | end
334 | for i, loss_module in ipairs(style_losses) do
335 | print(string.format(' Style %d loss: %f', i, loss_module.loss))
336 | end
337 | print(string.format(' Total loss: %f', loss))
338 | end
339 | end
340 |
341 | local function maybe_save(t)
342 | local should_save = params.save_iter > 0 and t % params.save_iter == 0
343 | should_save = should_save or t == params.num_iterations
344 | if should_save then
345 | local disp = deprocess(img:double())
346 | disp = image.minmax{tensor=disp, min=0, max=1}
347 | local filename = build_filename(params.output_image, t)
348 | if t == params.num_iterations then
349 | filename = params.output_image
350 | end
351 |
352 | -- Maybe perform postprocessing for color-independent style transfer
353 | if params.original_colors == 1 then
354 | disp = original_colors(content_image, disp)
355 | end
356 |
357 | image.save(filename, disp)
358 | end
359 | end
360 |
361 | -- Function to evaluate loss and gradient. We run the net forward and
362 | -- backward to get the gradient, and sum up losses from the loss modules.
363 | -- optim.lbfgs internally handles iteration and calls this function many
364 | -- times, so we manually count the number of iterations to handle printing
365 | -- and saving intermediate results.
366 | local num_calls = 0
367 | local function feval(x)
368 | net:forward(x)
369 | local grad = net:updateGradInput(x, dy)
370 | local loss = 0
371 | for _, mod in ipairs(content_losses) do
372 | loss = loss + mod.loss
373 | end
374 | for _, mod in ipairs(style_losses) do
375 | loss = loss + mod.loss
376 | end
377 | maybe_print(num_calls, loss)
378 | num_calls = num_calls + 1
379 | maybe_save(num_calls)
380 |
381 | collectgarbage()
382 | -- optim.lbfgs expects a vector for gradients
383 | return loss, grad:view(grad:nElement())
384 | end
385 |
386 | -- Run optimization.
387 | if params.optimizer == 'lbfgs' then
388 | print('Running optimization with L-BFGS')
389 | local x, losses = optim.lbfgs(feval, img, optim_state)
390 | elseif params.optimizer == 'adam' then
391 | print('Running optimization with ADAM')
392 | for t = 1, params.num_iterations do
393 | local x, losses = optim.adam(feval, img, optim_state)
394 | end
395 | end
396 | end
397 |
398 |
399 | function setup_gpu(params)
400 | local multigpu = false
401 | if params.gpu:find(',') then
402 | multigpu = true
403 | params.gpu = params.gpu:split(',')
404 | for i = 1, #params.gpu do
405 | params.gpu[i] = tonumber(params.gpu[i]) + 1
406 | end
407 | else
408 | params.gpu = tonumber(params.gpu) + 1
409 | end
410 | local dtype = 'torch.FloatTensor'
411 | if multigpu or params.gpu > 0 then
412 | if params.backend ~= 'clnn' then
413 | require 'cutorch'
414 | require 'cunn'
415 | if multigpu then
416 | cutorch.setDevice(params.gpu[1])
417 | else
418 | cutorch.setDevice(params.gpu)
419 | end
420 | dtype = 'torch.CudaTensor'
421 | else
422 | require 'clnn'
423 | require 'cltorch'
424 | if multigpu then
425 | cltorch.setDevice(params.gpu[1])
426 | else
427 | cltorch.setDevice(params.gpu)
428 | end
429 | dtype = torch.Tensor():cl():type()
430 | end
431 | else
432 | params.backend = 'nn'
433 | end
434 |
435 | if params.backend == 'cudnn' then
436 | require 'cudnn'
437 | if params.cudnn_autotune then
438 | cudnn.benchmark = true
439 | end
440 | cudnn.SpatialConvolution.accGradParameters = nn.SpatialConvolutionMM.accGradParameters -- ie: nop
441 | end
442 | return dtype, multigpu
443 | end
444 |
445 |
446 | function setup_multi_gpu(net, params)
447 | local DEFAULT_STRATEGIES = {
448 | [2] = {3},
449 | }
450 | local gpu_splits = nil
451 | if params.multigpu_strategy == '' then
452 | -- Use a default strategy
453 | gpu_splits = DEFAULT_STRATEGIES[#params.gpu]
454 | -- Offset the default strategy by one if we are using TV
455 | if params.tv_weight > 0 then
456 | for i = 1, #gpu_splits do gpu_splits[i] = gpu_splits[i] + 1 end
457 | end
458 | else
459 | -- Use the user-specified multigpu strategy
460 | gpu_splits = params.multigpu_strategy:split(',')
461 | for i = 1, #gpu_splits do
462 | gpu_splits[i] = tonumber(gpu_splits[i])
463 | end
464 | end
465 | assert(gpu_splits ~= nil, 'Must specify -multigpu_strategy')
466 | local gpus = params.gpu
467 |
468 | local cur_chunk = nn.Sequential()
469 | local chunks = {}
470 | for i = 1, #net do
471 | cur_chunk:add(net:get(i))
472 | if i == gpu_splits[1] then
473 | table.remove(gpu_splits, 1)
474 | table.insert(chunks, cur_chunk)
475 | cur_chunk = nn.Sequential()
476 | end
477 | end
478 | table.insert(chunks, cur_chunk)
479 | assert(#chunks == #gpus)
480 |
481 | local new_net = nn.Sequential()
482 | for i = 1, #chunks do
483 | local out_device = nil
484 | if i == #chunks then
485 | out_device = gpus[1]
486 | end
487 | new_net:add(nn.GPU(chunks[i], gpus[i], out_device))
488 | end
489 |
490 | return new_net
491 | end
492 |
493 |
494 | function build_filename(output_image, iteration)
495 | local ext = paths.extname(output_image)
496 | local basename = paths.basename(output_image, ext)
497 | local directory = paths.dirname(output_image)
498 | return string.format('%s/%s_%d.%s',directory, basename, iteration, ext)
499 | end
500 |
501 |
502 | -- Preprocess an image before passing it to a Caffe model.
503 | -- We need to rescale from [0, 1] to [0, 255], convert from RGB to BGR,
504 | -- and subtract the mean pixel.
505 | function preprocess(img)
506 | local mean_pixel = torch.DoubleTensor({103.939, 116.779, 123.68})
507 | local perm = torch.LongTensor{3, 2, 1}
508 | img = img:index(1, perm):mul(256.0)
509 | mean_pixel = mean_pixel:view(3, 1, 1):expandAs(img)
510 | img:add(-1, mean_pixel)
511 | return img
512 | end
513 |
514 |
515 | -- Undo the above preprocessing.
516 | function deprocess(img)
517 | local mean_pixel = torch.DoubleTensor({103.939, 116.779, 123.68})
518 | mean_pixel = mean_pixel:view(3, 1, 1):expandAs(img)
519 | img = img + mean_pixel
520 | local perm = torch.LongTensor{3, 2, 1}
521 | img = img:index(1, perm):div(256.0)
522 | return img
523 | end
524 |
525 |
526 | -- Combine the Y channel of the generated image and the UV channels of the
527 | -- content image to perform color-independent style transfer.
528 | function original_colors(content, generated)
529 | local generated_y = image.rgb2yuv(generated)[{{1, 1}}]
530 | local content_uv = image.rgb2yuv(content)[{{2, 3}}]
531 | return image.yuv2rgb(torch.cat(generated_y, content_uv, 1))
532 | end
533 |
534 |
535 | -- Define an nn Module to compute content loss in-place
536 | local ContentLoss, parent = torch.class('nn.ContentLoss', 'nn.Module')
537 |
538 | function ContentLoss:__init(strength, normalize)
539 | parent.__init(self)
540 | self.strength = strength
541 | -- strength when doing BP. used to disable lap_losses when -lap_nobp is specified
542 | self.strength_bp = strength
543 | self.target = torch.Tensor()
544 | self.normalize = normalize or false
545 | self.loss = 0
546 | self.crit = nn.MSECriterion()
547 | self.mode = 'none'
548 | end
549 |
550 | function ContentLoss:updateOutput(input)
551 | if self.mode == 'loss' then
552 | self.loss = self.crit:forward(input, self.target) * self.strength
553 | elseif self.mode == 'capture' then
554 | self.target:resizeAs(input):copy(input)
555 | end
556 | self.output = input
557 | return self.output
558 | end
559 |
560 | function ContentLoss:updateGradInput(input, gradOutput)
561 | if self.mode == 'loss' then
562 | if input:nElement() == self.target:nElement() then
563 | self.gradInput = self.crit:backward(input, self.target)
564 | end
565 | if self.normalize then
566 | self.gradInput:div(torch.norm(self.gradInput, 1) + 1e-8)
567 | end
568 | self.gradInput:mul(self.strength_bp)
569 | self.gradInput:add(gradOutput)
570 | else
571 | self.gradInput:resizeAs(gradOutput):copy(gradOutput)
572 | end
573 | return self.gradInput
574 | end
575 |
576 |
577 | local Gram, parent = torch.class('nn.GramMatrix', 'nn.Module')
578 |
579 | function Gram:__init()
580 | parent.__init(self)
581 | end
582 |
583 | function Gram:updateOutput(input)
584 | assert(input:dim() == 3)
585 | local C, H, W = input:size(1), input:size(2), input:size(3)
586 | local x_flat = input:view(C, H * W)
587 | self.output:resize(C, C)
588 | self.output:mm(x_flat, x_flat:t())
589 | return self.output
590 | end
591 |
592 | function Gram:updateGradInput(input, gradOutput)
593 | assert(input:dim() == 3 and input:size(1))
594 | local C, H, W = input:size(1), input:size(2), input:size(3)
595 | local x_flat = input:view(C, H * W)
596 | self.gradInput:resize(C, H * W):mm(gradOutput, x_flat)
597 | self.gradInput:addmm(gradOutput:t(), x_flat)
598 | self.gradInput = self.gradInput:view(C, H, W)
599 | return self.gradInput
600 | end
601 |
602 |
603 | -- Define an nn Module to compute style loss in-place
604 | local StyleLoss, parent = torch.class('nn.StyleLoss', 'nn.Module')
605 |
606 | function StyleLoss:__init(strength, normalize)
607 | parent.__init(self)
608 | self.normalize = normalize or false
609 | self.strength = strength
610 | self.target = torch.Tensor()
611 | self.mode = 'none'
612 | self.loss = 0
613 |
614 | self.gram = nn.GramMatrix()
615 | self.blend_weight = nil
616 | self.G = nil
617 | self.crit = nn.MSECriterion()
618 | end
619 |
620 | function StyleLoss:updateOutput(input)
621 | self.G = self.gram:forward(input)
622 | self.G:div(input:nElement())
623 | if self.mode == 'capture' then
624 | if self.blend_weight == nil then
625 | self.target:resizeAs(self.G):copy(self.G)
626 | elseif self.target:nElement() == 0 then
627 | self.target:resizeAs(self.G):copy(self.G):mul(self.blend_weight)
628 | else
629 | self.target:add(self.blend_weight, self.G)
630 | end
631 | elseif self.mode == 'loss' then
632 | self.loss = self.strength * self.crit:forward(self.G, self.target)
633 | end
634 | self.output = input
635 | return self.output
636 | end
637 |
638 | function StyleLoss:updateGradInput(input, gradOutput)
639 | if self.mode == 'loss' then
640 | local dG = self.crit:backward(self.G, self.target)
641 | dG:div(input:nElement())
642 | self.gradInput = self.gram:backward(input, dG)
643 | if self.normalize then
644 | self.gradInput:div(torch.norm(self.gradInput, 1) + 1e-8)
645 | end
646 | self.gradInput:mul(self.strength)
647 | self.gradInput:add(gradOutput)
648 | else
649 | self.gradInput = gradOutput
650 | end
651 | return self.gradInput
652 | end
653 |
654 |
655 | local TVLoss, parent = torch.class('nn.TVLoss', 'nn.Module')
656 |
657 | function TVLoss:__init(strength)
658 | parent.__init(self)
659 | self.strength = strength
660 | self.x_diff = torch.Tensor()
661 | self.y_diff = torch.Tensor()
662 | end
663 |
664 | function TVLoss:updateOutput(input)
665 | self.output = input
666 | return self.output
667 | end
668 |
669 | -- TV loss backward pass inspired by kaishengtai/neuralart
670 | function TVLoss:updateGradInput(input, gradOutput)
671 | self.gradInput:resizeAs(input):zero()
672 | local C, H, W = input:size(1), input:size(2), input:size(3)
673 | self.x_diff:resize(3, H - 1, W - 1)
674 | self.y_diff:resize(3, H - 1, W - 1)
675 | self.x_diff:copy(input[{{}, {1, -2}, {1, -2}}])
676 | self.x_diff:add(-1, input[{{}, {1, -2}, {2, -1}}])
677 | self.y_diff:copy(input[{{}, {1, -2}, {1, -2}}])
678 | self.y_diff:add(-1, input[{{}, {2, -1}, {1, -2}}])
679 | self.gradInput[{{}, {1, -2}, {1, -2}}]:add(self.x_diff):add(self.y_diff)
680 | self.gradInput[{{}, {1, -2}, {2, -1}}]:add(-1, self.x_diff)
681 | self.gradInput[{{}, {2, -1}, {1, -2}}]:add(-1, self.y_diff)
682 | self.gradInput:mul(self.strength)
683 | self.gradInput:add(gradOutput)
684 | return self.gradInput
685 | end
686 |
687 |
688 | local params = cmd:parse(arg)
689 | main(params)
690 |
--------------------------------------------------------------------------------
/laplacian.py:
--------------------------------------------------------------------------------
1 | # Generate image Laplacian of a given image, save it as a .png file for visualization
2 |
3 | import numpy as np
4 | import scipy.optimize, scipy.ndimage, scipy.misc
5 | import lasagne
6 | from lasagne.layers import Conv2DLayer, InputLayer
7 | import sys
8 | import pdb
9 |
10 | def prepare_image(image):
11 | """Given an image loaded from disk, turn it into a representation compatible with the model.
12 | The format is (b,c,y,x) with batch=1 for a single image, channels=3 for RGB, and y,x matching
13 | the resolution.
14 | """
15 | image = np.swapaxes(np.swapaxes(image, 1, 2), 0, 1)[::-1, :, :]
16 | image = image.astype(np.float32)
17 | return image[np.newaxis]
18 |
19 | def finalize_image(image, scale):
20 | """Based on the output of the neural network, convert it into an image format that can be saved
21 | to disk -- shuffling dimensions as appropriate.
22 | """
23 | image = np.swapaxes(np.swapaxes(image[::-1], 0, 1), 1, 2)
24 | # ignore the sign, scale up the pixel value to make it more striking
25 | image = np.abs(image) * scale
26 | image = np.clip(image, 0, 255).astype('uint8')
27 | return image
28 |
29 | infilename = sys.argv[1]
30 | outfilename = sys.argv[2]
31 | if len(sys.argv) > 3:
32 | scale = int( sys.argv[3] )
33 | else:
34 | scale = 3
35 |
36 | net = {}
37 | # once a channel among 'R','G','B',
38 | # if all channels are fed to laplacian conv at the same time,
39 | # the output will be sum of the outputs from all input channels
40 | net['img'] = InputLayer((None, 1, None, None))
41 | net['laplacian'] = Conv2DLayer(net['img'], 1, 3, pad=1)
42 | laplacian = np.array( [ [0,-1,0], [-1,4,-1], [0,-1,0] ], dtype=np.float32 )
43 | W = np.zeros( (1, 1, 3, 3), dtype=np.float32 )
44 | W[0,0] = laplacian
45 | net['laplacian'].W.set_value(W)
46 |
47 | orig_img = scipy.ndimage.imread(infilename, mode='RGB')
48 | img = prepare_image(orig_img)
49 |
50 | output = []
51 | for i in xrange(3):
52 | img_chan = img[:, [i], :, :]
53 | tensor_input = { net['img']: img_chan }
54 | out_chan = lasagne.layers.get_output( net['laplacian'], tensor_input )
55 | output.append( out_chan.eval()[0,0] )
56 |
57 | output = np.array(output)
58 |
59 | out_img = finalize_image(output, scale)
60 | scipy.misc.toimage(out_img, cmin=0, cmax=255).save(outfilename)
61 |
--------------------------------------------------------------------------------
/logstat.py:
--------------------------------------------------------------------------------
1 | # Get statistics from lap_style.lua logs, used to generate Table 1 in the lapstyle paper
2 | import re
3 | import os
4 | import sys
5 | import numpy as np
6 |
7 | contentimageAll = ( 'megan.png', 'kid5.png', 'goat.png', 'girlmrf.jpg', 'boy.png' )
8 | styleimageAll = ( 'flowers.png', 'smallworldI.jpg', 'muse.png', 'girlsketch.png', 'girl3.jpg' )
9 | #sigs = ("20_2_100.log", "20_2_100_nobp.log")
10 | #contentLayer2contentLossType = [ -1, 1, 2, -1 ]
11 |
12 | sigs = ("relu2_2,relu4_2_20_100_nobp.log",)
13 | contentLayer2contentLossType = [ -1, 0, 1, 2 ]
14 |
15 | logpath =sys.argv[1]
16 | readlogcount = 0
17 |
18 | max_layer_num = 9
19 | init_losses = []
20 | end_losses = []
21 | end_losses_nobp = []
22 |
23 | for i, contentFile in enumerate(contentimageAll):
24 | styleFile = styleimageAll[i]
25 | contentName = os.path.splitext(contentFile)[0]
26 | styleName = os.path.splitext(styleFile)[0]
27 | for sig in sigs:
28 | logfilename = "%s/%s_%s%s" %(logpath, contentName, styleName, sig)
29 | if not os.path.isfile(logfilename):
30 | print "'%s' doesn't exist!" %(logfilename)
31 | else:
32 | if sig[-8:] == 'nobp.log':
33 | nobp = True
34 | else:
35 | nobp = False
36 |
37 | LOG = open(logfilename)
38 | readlogcount += 1
39 | iter_type = 'none'
40 | style_loss_sum = 0
41 | content_loss_sum = 0
42 | lap_loss_sum = 0
43 |
44 | for line in LOG:
45 | line = line.strip()
46 | # Iteration 0 / 1000
47 | result = re.match(r"Iteration (\d+) / (\d+)", line)
48 | if result:
49 | if iter_type == 'init':
50 | loss_block = [1.0, lap_loss_sum/total_loss, total_loss/lap_loss_sum, content_loss_sum/lap_loss_sum, style_loss_sum/lap_loss_sum]
51 | init_losses.append(loss_block)
52 | lap_loss_sum0 = lap_loss_sum
53 | style_loss_sum = 0
54 | content_loss_sum = 0
55 | lap_loss_sum = 0
56 | curr_iter = int(result.group(1))
57 | total_iter = int(result.group(2))
58 | if curr_iter == 0:
59 | iter_type = 'init'
60 | elif curr_iter == total_iter - 1:
61 | iter_type = 'end'
62 | else:
63 | iter_type = 'mid'
64 |
65 | continue
66 | if iter_type == 'init' or iter_type == 'end':
67 | # Content 1 loss: 4858483.750000
68 | result = re.match(r"(Content|Style) (\d+) loss: ([0-9.]+)", line)
69 | if result:
70 | loss = float(result.group(3))
71 | loss_type = result.group(1)
72 | layer_no = int(result.group(2))
73 | if loss_type == 'Content':
74 | contentLossType = contentLayer2contentLossType[layer_no]
75 | if contentLossType == 1:
76 | content_loss_sum += loss
77 | if contentLossType == 2:
78 | lap_loss_sum += loss
79 | else:
80 | style_loss_sum += loss
81 | else:
82 | result = re.match(r"Total loss: ([0-9.]+)", line)
83 | if result:
84 | total_loss = float(result.group(1))
85 |
86 | if iter_type == 'end':
87 | loss_block = [lap_loss_sum/lap_loss_sum0, lap_loss_sum/total_loss, total_loss/lap_loss_sum0,
88 | content_loss_sum/lap_loss_sum0, style_loss_sum/lap_loss_sum0]
89 | if nobp:
90 | end_losses_nobp.append(loss_block)
91 | else:
92 | end_losses.append(loss_block)
93 |
94 | print "%d log files read" %readlogcount
95 | init_losses = np.array(init_losses)
96 | #arr_labels = ('init_losses', 'end_losses', 'end_losses_nobp')
97 | # always init_losses_nobp == init_losses. So no need to print it
98 | #for i,arr in enumerate([init_losses, end_losses, end_losses_nobp]):
99 | arr_labels = ('init_losses', 'end_losses_nobp')
100 | for i,arr in enumerate([init_losses, end_losses_nobp]):
101 | arr = np.array(arr)
102 | arr_label = arr_labels[i]
103 | loss_labels = ('lap', 'lap-frac', 'total', 'content', 'style')
104 | print "%s:" %arr_label
105 | for j,loss_label in enumerate(loss_labels):
106 | losses = arr[:,j]
107 | mean = np.mean(losses)
108 | std = np.std(losses)
109 | print "%s: %.5f (%.5f)" %(loss_label, mean, std)
110 | print losses
111 |
--------------------------------------------------------------------------------
/multi-lap-test.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash -x
2 | # test lap_style.lua with the combination of multiple laplacian layers, on a single image pair
3 |
4 | contentimg=$1
5 | styleimg=$2
6 | contentweight=$3
7 | contentFilename=$(basename "$contentimg")
8 | contentname="${contentFilename%.*}"
9 | styleFilename=$(basename "$styleimg")
10 | stylename="${styleFilename%.*}"
11 | laplayersAll=( 1 1 2 1,2 1,3 2,3 2,4)
12 | lapweightsAll=(0 50 100 50,100 50,400 100,400 100,1600)
13 | configLen=${#laplayersAll[@]}
14 | for (( i=0; i<$configLen; i++ )); do
15 | laplayers=${laplayersAll[$i]}
16 | lapweights=${lapweightsAll[$i]}
17 | outsig="${contentname}_${stylename}${contentweight}_${laplayers}_${lapweights}"
18 | th lap_style.lua -style_image images/$styleimg -content_image images/$contentimg -output_image output/${outsig}.png -content_weight $contentweight -lap_layers $laplayers -lap_weights $lapweights 2>&1| tee output/${outsig}.log
19 | done
20 |
--------------------------------------------------------------------------------
/neural-doodle/doodle.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | #
3 | # Neural Doodle!
4 | # Copyright (c) 2017, Shaohua Li
5 | # Copyright (c) 2016, Alex J. Champandard.
6 | # Please refer to https://github.com/alexjc/neural-doodle for a user manual.
7 |
8 | ''' Dimensionalities and other numbers are based on the command:
9 | python3 doodle-orig.py --style samples/Gogh.jpg --content samples/Seth.png \
10 | --output SethAsGogh.png --device=gpu0 --phases=4 --iterations=40
11 | '''
12 |
13 | import os
14 | import sys
15 | import bz2
16 | import math
17 | import time
18 | import pickle
19 | import argparse
20 | import itertools
21 | import collections
22 | import pdb
23 |
24 |
25 | # Configure all options first so we can custom load other libraries (Theano) based on device specified by user.
26 | parser = argparse.ArgumentParser(description='Generate a new image by applying style onto a content image.',
27 | formatter_class=argparse.ArgumentDefaultsHelpFormatter)
28 | add_arg = parser.add_argument
29 |
30 | add_arg('--content', default=None, type=str, help='Content image path as optimization target.')
31 | add_arg('--content-weight', default=30.0, type=float, help='Weight of content relative to style.')
32 | add_arg('--lap-weight', default=100.0, type=float, help='Weight of laplace content relative to style.')
33 | # consider add '1_laplace' to content_layers, to force similar laplacian of the new image and the content image
34 | add_arg('--content-layers', default='4_2,1_laplace', type=str, help='The layer with which to match content.')
35 | add_arg('--style', default=None, type=str, help='Style image path to extract patches.')
36 | add_arg('--style-weight', default=15.0, type=float, help='Weight of style relative to content.')
37 | add_arg('--style-layers', default='3_1,4_1', type=str, help='The layers to match style patches.')
38 | add_arg('--semantic-ext', default='_sem.png', type=str, help='File extension for the semantic maps.')
39 | add_arg('--semantic-weight', default=10.0, type=float, help='Global weight of semantics vs. features.')
40 | add_arg('--output', default='output.png', type=str, help='Output image path to save once done.')
41 | add_arg('--output-size', default=None, type=str, help='Size of the output image, e.g. 512x512.')
42 | add_arg('--phases', default=3, type=int, help='Number of image scales to process in phases.')
43 | add_arg('--slices', default=2, type=int, help='Split patches up into this number of batches.')
44 | add_arg('--cache', default=0, type=int, help='Whether to compute matches only once.')
45 | add_arg('--smoothness', default=1E+0, type=float, help='Weight of image smoothing scheme.')
46 | add_arg('--variety', default=0.0, type=float, help='Bias toward selecting diverse patches, e.g. 0.5.')
47 | add_arg('--seed', default='noise', type=str, help='Seed image path, "noise" or "content".')
48 | add_arg('--seed-range', default='16:240', type=str, help='Random colors chosen in range, e.g. 0:255.')
49 | add_arg('--iterations', default=100, type=int, help='Number of iterations to run each resolution.')
50 | add_arg('--device', default='gpu', type=str, help='Index of the GPU number to use, for theano.')
51 | add_arg('--print-every', default=10, type=int, help='How often to log statistics to stdout.')
52 | add_arg('--save-every', default=10, type=int, help='How frequently to save PNG into `frames`.')
53 | args = parser.parse_args()
54 |
55 |
56 | #----------------------------------------------------------------------------------------------------------------------
57 |
58 | # Color coded output helps visualize the information a little better, plus looks cool!
59 | class ansi:
60 | BOLD = '\033[1;97m'
61 | WHITE = '\033[0;97m'
62 | YELLOW = '\033[0;33m'
63 | YELLOW_B = '\033[0;33m'
64 | RED = '\033[0;31m'
65 | RED_B = '\033[1;31m'
66 | BLUE = '\033[0;94m'
67 | BLUE_B = '\033[1;94m'
68 | CYAN = '\033[0;36m'
69 | CYAN_B = '\033[1;36m'
70 | ENDC = '\033[0m'
71 |
72 | def error(message, *lines):
73 | string = "\n{}ERROR: " + message + "{}\n" + "\n".join(lines) + "{}\n"
74 | print(string.format(ansi.RED_B, ansi.RED, ansi.ENDC))
75 | sys.exit(-1)
76 |
77 | print('{}Neural Doodle for semantic style transfer.{}'.format(ansi.CYAN_B, ansi.ENDC))
78 |
79 | # Load the underlying deep learning libraries based on the device specified. If you specify THEANO_FLAGS manually,
80 | # the code assumes you know what you are doing and they are not overriden!
81 | os.environ.setdefault('THEANO_FLAGS', 'floatX=float32,device={},force_device=True,'\
82 | 'print_active_device=False'.format(args.device))
83 |
84 | # Scientific & Imaging Libraries
85 | import numpy as np
86 | import scipy.optimize, scipy.ndimage, scipy.misc
87 | import PIL
88 |
89 | # Numeric Computing (GPU)
90 | import theano
91 | import theano.tensor as T
92 | import theano.tensor.nnet.neighbours
93 |
94 | # Support ansi colors in Windows too.
95 | if sys.platform == 'win32':
96 | import colorama
97 |
98 | # Deep Learning Framework
99 | import lasagne
100 | from lasagne.layers import Conv2DLayer as ConvLayer, Pool2DLayer as PoolLayer
101 | from lasagne.layers import InputLayer, ConcatLayer
102 |
103 | print('{} - Using device `{}` for processing the images.{}'.format(ansi.CYAN, theano.config.device, ansi.ENDC))
104 |
105 |
106 | #----------------------------------------------------------------------------------------------------------------------
107 | # Convolutional Neural Network
108 | #----------------------------------------------------------------------------------------------------------------------
109 | class Model(object):
110 | """Store all the data related to the neural network (aka. "model"). This is currently based on VGG19.
111 | """
112 |
113 | def __init__(self):
114 | self.pixel_mean = np.array([103.939, 116.779, 123.680], dtype=np.float32).reshape((3,1,1))
115 |
116 | self.setup_model()
117 | self.load_data()
118 |
119 | def setup_model(self, input=None):
120 | """Use lasagne to create a network of convolution layers, first using VGG19 as the framework
121 | and then adding augmentations for Semantic Style Transfer.
122 | """
123 | net, self.channels = {}, {}
124 |
125 | # Primary network for the main image. These are convolution only, and stop at layer 4_2 (rest unused).
126 | net['img'] = input or InputLayer((None, 3, None, None))
127 | net['conv1_1'] = ConvLayer(net['img'], 64, 3, pad=1)
128 | net['conv1_2'] = ConvLayer(net['conv1_1'], 64, 3, pad=1)
129 | net['pool1'] = PoolLayer(net['conv1_2'], 2, mode='average_exc_pad')
130 | net['conv2_1'] = ConvLayer(net['pool1'], 128, 3, pad=1)
131 | net['conv2_2'] = ConvLayer(net['conv2_1'], 128, 3, pad=1)
132 | net['pool2'] = PoolLayer(net['conv2_2'], 2, mode='average_exc_pad')
133 | net['conv3_1'] = ConvLayer(net['pool2'], 256, 3, pad=1)
134 | net['conv3_2'] = ConvLayer(net['conv3_1'], 256, 3, pad=1)
135 | net['conv3_3'] = ConvLayer(net['conv3_2'], 256, 3, pad=1)
136 | net['conv3_4'] = ConvLayer(net['conv3_3'], 256, 3, pad=1)
137 | net['pool3'] = PoolLayer(net['conv3_4'], 2, mode='average_exc_pad')
138 | net['conv4_1'] = ConvLayer(net['pool3'], 512, 3, pad=1)
139 | # 512 filters, 3x3
140 | net['conv4_2'] = ConvLayer(net['conv4_1'], 512, 3, pad=1)
141 | net['conv4_3'] = ConvLayer(net['conv4_2'], 512, 3, pad=1)
142 | net['conv4_4'] = ConvLayer(net['conv4_3'], 512, 3, pad=1)
143 | net['pool4'] = PoolLayer(net['conv4_4'], 2, mode='average_exc_pad')
144 | net['conv5_1'] = ConvLayer(net['pool4'], 512, 3, pad=1)
145 | net['conv5_2'] = ConvLayer(net['conv5_1'], 512, 3, pad=1)
146 | net['conv5_3'] = ConvLayer(net['conv5_2'], 512, 3, pad=1)
147 | net['conv5_4'] = ConvLayer(net['conv5_3'], 512, 3, pad=1)
148 | net['main'] = net['conv5_4']
149 |
150 | # Auxiliary network for the semantic layers, and the nearest neighbors calculations.
151 | # batch size: 1. num_filters: 1 (temporary. will be updated later)
152 | net['map'] = InputLayer((1, 1, None, None))
153 | for j, i in itertools.product(range(5), range(4)):
154 | if j < 2 and i > 1: continue
155 | suffix = '%i_%i' % (j+1, i+1)
156 |
157 | if i == 0:
158 | # PoolLayer: Pool2DLayer. 2**j: pooling region. mode: mean pooling (majority voting)
159 | # all pooling layers net['map1'], ..., net['map5'] are fed by the same net['map']
160 | # net['map*'] are at decreasing granularity, in sync with conv*
161 | # pooling layer keeps the channel num of the input layer net['map']. In the example, 3
162 | net['map%i'%(j+1)] = PoolLayer(net['map'], 2**j, mode='average_exc_pad')
163 | # channels[layer]: number of filters
164 | self.channels[suffix] = net['conv'+suffix].num_filters
165 |
166 | # sem* is used to calculate style loss
167 | # most sem* layers are not used, except 2 layers
168 | # semantic_weight default: 10
169 | if args.semantic_weight > 0.0:
170 | # sem1_1 <= conv1_1 + map1
171 | # sem1_2 <= conv1_2 + map1
172 | # sem2_1 <= conv2_1 + map2
173 | # sem2_2 <= conv2_2 + map2
174 | # sem3_1 <= conv3_1 + map3
175 | # sem3_2 <= conv3_2 + map3
176 | # sem3_3 <= conv3_3 + map3
177 | # sem3_4 <= conv3_4 + map3
178 | # sem4_1 <= conv4_1 + map4
179 | # sem4_2 <= conv4_2 + map4
180 | # sem4_3 <= conv4_3 + map4
181 | # sem4_4 <= conv4_4 + map4
182 | # sem5_1 <= conv5_1 + map5
183 | # sem5_2 <= conv5_2 + map5
184 | # sem5_3 <= conv5_3 + map5
185 | # sem5_4 <= conv5_4 + map5
186 | net['sem'+suffix] = ConcatLayer([net['conv'+suffix], net['map%i'%(j+1)]])
187 | else:
188 | net['sem'+suffix] = net['conv'+suffix]
189 |
190 | net['dup'+suffix] = InputLayer(net['sem'+suffix].output_shape)
191 | # num_filters=1 is only a placeholder, will be updated to the number of patches in each slice
192 | # nn filter size: 3*3
193 | net['nn'+suffix] = ConvLayer(net['dup'+suffix], 1, 3, b=None, pad=0, flip_filters=False)
194 | shape = net['nn'+suffix].W.get_value().shape
195 | net['nn'+suffix].W = theano.shared( net['nn'+suffix].W.get_value(), broadcastable=[False]* len(shape) )
196 |
197 | # laplacian layer
198 | # do pooling first to reduce effective image size and reduce required memory & running time
199 | net['pool1_1'] = PoolLayer(net['img'], 2, mode='average_exc_pad')
200 | net['conv1_laplace'] = ConvLayer(net['pool1_1'], 1, 3, pad=1)
201 | laplacian = np.array( [ [0,-1,0], [-1,4,-1], [0,-1,0] ], dtype=theano.config.floatX )
202 | W = np.zeros((1, 3, 3, 3), dtype=theano.config.floatX)
203 | for t in range(3):
204 | W[0,t] = laplacian
205 | net['conv1_laplace'].W.set_value(W)
206 |
207 | net['sem1_laplace'] = net['conv1_laplace']
208 | net['dup1_laplace'] = InputLayer(net['sem1_laplace'].output_shape)
209 | net['nn1_laplace'] = ConvLayer(net['dup1_laplace'], 1, 3, b=None, pad=0, flip_filters=False)
210 | shape = net['nn1_laplace'].W.get_value().shape
211 | net['nn1_laplace'].W = theano.shared( net['nn1_laplace'].W.get_value(), broadcastable=[False]* len(shape) )
212 | self.channels['1_laplace'] = net['conv1_laplace'].num_filters
213 | self.network = net
214 |
215 | def load_data(self):
216 | """Open the serialized parameters from a pre-trained network, and load them into the model created.
217 | """
218 | vgg19_file = os.path.join(os.path.dirname(__file__), 'vgg19_conv.pkl.bz2')
219 | if not os.path.exists(vgg19_file):
220 | error("Model file with pre-trained convolution layers not found. Download here...",
221 | "https://github.com/alexjc/neural-doodle/releases/download/v0.0/vgg19_conv.pkl.bz2")
222 |
223 | data = pickle.load(bz2.open(vgg19_file, 'rb'))
224 | # layers before and including conv5_4. 16 conv layers, 32 parameter arrays
225 | params = lasagne.layers.get_all_param_values(self.network['main'])
226 | lasagne.layers.set_all_param_values(self.network['main'], data[:len(params)])
227 |
228 | # layers = [ sem3_1, sem4_1, conv4_2 ] & sem1_laplace
229 | def setup(self, layers):
230 | """Setup the inputs and outputs, knowing the layers that are required by the optimization algorithm.
231 | """
232 | self.tensor_img = T.tensor4()
233 | self.tensor_map = T.tensor4()
234 | # self.network['img']: image input; self.network['map']: semantic input
235 | tensor_inputs = {self.network['img']: self.tensor_img, self.network['map']: self.tensor_map}
236 | # outputs from 3 layers sem3_1, sem4_1, conv4_2, given tensor_img and tensor_map
237 | outputs = lasagne.layers.get_output([self.network[l] for l in layers], tensor_inputs)
238 | self.tensor_outputs = {k: v for k, v in zip(layers, outputs)}
239 |
240 | # type: sem or conv
241 | # type+l: sem3_1, sem4_1 or conv3_1, conv4_1
242 | def get_outputs(self, type, layers):
243 | """Fetch the output tensors for the network layers.
244 | """
245 | return [self.tensor_outputs[type+l] for l in layers]
246 |
247 | def prepare_image(self, image):
248 | """Given an image loaded from disk, turn it into a representation compatible with the model.
249 | The format is (b,c,y,x) with batch=1 for a single image, channels=3 for RGB, and y,x matching
250 | the resolution.
251 | """
252 | image = np.swapaxes(np.swapaxes(image, 1, 2), 0, 1)[::-1, :, :]
253 | image = image.astype(np.float32) - self.pixel_mean
254 | return image[np.newaxis]
255 |
256 | def finalize_image(self, image, resolution):
257 | """Based on the output of the neural network, convert it into an image format that can be saved
258 | to disk -- shuffling dimensions as appropriate.
259 | """
260 | image = np.swapaxes(np.swapaxes(image[::-1], 0, 1), 1, 2)
261 | image = np.clip(image, 0, 255).astype('uint8')
262 | return scipy.misc.imresize(image, resolution, interp='bicubic')
263 |
264 |
265 | #----------------------------------------------------------------------------------------------------------------------
266 | # Semantic Style Transfer
267 | #----------------------------------------------------------------------------------------------------------------------
268 | class NeuralGenerator(object):
269 | """This is the main part of the application that generates an image using optimization and LBFGS.
270 | The images will be processed at increasing resolutions in the run() method.
271 | """
272 |
273 | def __init__(self):
274 | """Constructor sets up global variables, loads and validates files, then builds the model.
275 | """
276 | self.start_time = time.time()
277 | self.style_cache = {}
278 | # style_layers: 3_1, 4_1, 1_laplace
279 | self.style_layers = args.style_layers.split(',')
280 | self.content_layers = args.content_layers.split(',')
281 | self.used_layers = self.style_layers + self.content_layers
282 |
283 | # Prepare file output and load files specified as input.
284 | if args.save_every is not None:
285 | os.makedirs('frames', exist_ok=True)
286 | if args.output is not None and os.path.isfile(args.output):
287 | os.remove(args.output)
288 |
289 | print(ansi.CYAN, end='')
290 | target = args.content or args.output
291 | self.content_img_original, self.content_map_original = self.load_images('content', target)
292 | self.style_img_original, self.style_map_original = self.load_images('style', args.style)
293 |
294 | if self.content_map_original is None and self.content_img_original is None:
295 | print(" - No content files found; result depends on seed only.")
296 | print(ansi.ENDC, end='')
297 |
298 | # Display some useful errors if the user's input can't be understood.
299 | if self.style_img_original is None:
300 | error("Couldn't find style image as expected.",
301 | " - Try making sure `{}` exists and is a valid image.".format(args.style))
302 |
303 | if self.content_map_original is not None and self.style_map_original is None:
304 | basename, _ = os.path.splitext(args.style)
305 | error("Expecting a semantic map for the input style image too.",
306 | " - Try creating the file `{}_sem.png` with your annotations.".format(basename))
307 |
308 | if self.style_map_original is not None and self.content_map_original is None:
309 | basename, _ = os.path.splitext(target)
310 | error("Expecting a semantic map for the input content image too.",
311 | " - Try creating the file `{}_sem.png` with your annotations.".format(basename))
312 |
313 | if self.content_map_original is None:
314 | if self.content_img_original is None and args.output_size:
315 | shape = tuple([int(i) for i in args.output_size.split('x')])
316 | else:
317 | shape = self.style_img_original.shape[:2]
318 |
319 | self.content_map_original = np.zeros(shape+(3,))
320 | args.semantic_weight = 0.0
321 |
322 | if self.style_map_original is None:
323 | self.style_map_original = np.zeros(self.style_img_original.shape[:2]+(3,))
324 | args.semantic_weight = 0.0
325 |
326 | if self.content_img_original is None:
327 | self.content_img_original = np.zeros(self.content_map_original.shape[:2]+(3,))
328 | args.content_weight = 0.0
329 |
330 | if self.content_map_original.shape[2] != self.style_map_original.shape[2]:
331 | error("Mismatch in number of channels for style and content semantic map.",
332 | " - Make sure both images are RGB, RGBA, or L.")
333 |
334 | # Finalize the parameters based on what we loaded, then create the model.
335 | args.semantic_weight = math.sqrt(9.0 / args.semantic_weight) if args.semantic_weight else 0.0
336 | self.model = Model()
337 |
338 |
339 | #------------------------------------------------------------------------------------------------------------------
340 | # Helper Functions
341 | #------------------------------------------------------------------------------------------------------------------
342 |
343 | def load_images(self, name, filename):
344 | """If the image and map files exist, load them. Otherwise they'll be set to default values later.
345 | """
346 | basename, _ = os.path.splitext(filename)
347 | mapname = basename + args.semantic_ext
348 | img = scipy.ndimage.imread(filename, mode='RGB') if os.path.exists(filename) else None
349 | map = scipy.ndimage.imread(mapname) if os.path.exists(mapname) and args.semantic_weight > 0.0 else None
350 |
351 | if img is not None: print(' - Loading `{}` for {} data.'.format(filename, name))
352 | if map is not None: print(' - Adding `{}` as semantic map.'.format(mapname))
353 |
354 | if img is not None and map is not None and img.shape[:2] != map.shape[:2]:
355 | error("The {} image and its semantic map have different resolutions. Either:".format(name),
356 | " - Resize {} to {}, or\n - Resize {} to {}."\
357 | .format(filename, map.shape[1::-1], mapname, img.shape[1::-1]))
358 | return img, map
359 |
360 | def compile(self, arguments, function):
361 | """Build a Theano function that will run the specified expression on the GPU.
362 | """
363 | return theano.function(list(arguments), function, on_unused_input='ignore')
364 |
365 | def compute_norms(self, backend, layer, array):
366 | # self.model.channels[layer]: num of filters of conv_layer
367 | # e.g. layer=3_1, then it's the num of filters of conv3_1
368 | # if layer==sem3_1(4_1): first half, i.e., conv3_1(4_1) output norms
369 | # if layer==conv3_1(4_1): all the output norms
370 | ni = backend.sqrt(backend.sum(array[:,:self.model.channels[layer]] ** 2.0, axis=(1,), keepdims=True))
371 | # if layer==sem3_1(4_1): second half, i.e., map3_1(4_1) output norms
372 | # if layer==conv3_1(4_1): empty array
373 | ns = backend.sqrt(backend.sum(array[:,self.model.channels[layer]:] ** 2.0, axis=(1,), keepdims=True))
374 | return [ni] + [ns]
375 |
376 | def normalize_components(self, layer, array, norms):
377 | if args.style_weight > 0.0:
378 | array[:,:self.model.channels[layer]] /= (norms[0] * 3.0)
379 | if args.semantic_weight > 0.0:
380 | array[:,self.model.channels[layer]:] /= (norms[1] * args.semantic_weight)
381 |
382 |
383 | #------------------------------------------------------------------------------------------------------------------
384 | # Initialization & Setup
385 | #------------------------------------------------------------------------------------------------------------------
386 |
387 | def rescale_image(self, img, scale):
388 | """Re-implementing skimage.transform.scale without the extra dependency. Saves a lot of space and hassle!
389 | """
390 | output = scipy.misc.toimage(img, cmin=0.0, cmax=255)
391 | output.thumbnail((int(output.size[0]*scale), int(output.size[1]*scale)), PIL.Image.ANTIALIAS)
392 | return np.asarray(output)
393 |
394 | def prepare_content(self, scale=1.0):
395 | """Called each phase of the optimization, rescale the original content image and its map to use as inputs.
396 | """
397 | content_img = self.rescale_image(self.content_img_original, scale)
398 | self.content_img = self.model.prepare_image(content_img)
399 |
400 | content_map = self.rescale_image(self.content_map_original, scale)
401 | self.content_map = content_map.transpose((2, 0, 1))[np.newaxis].astype(np.float32)
402 |
403 | def prepare_style(self, scale=1.0):
404 | """Called each phase of the optimization, process the style image according to the scale, then run it
405 | through the model to extract intermediate outputs (e.g. sem4_1) and turn them into patches.
406 | """
407 | style_img = self.rescale_image(self.style_img_original, scale)
408 | self.style_img = self.model.prepare_image(style_img)
409 |
410 | style_map = self.rescale_image(self.style_map_original, scale)
411 | # style_map.shape: (63, 52, 3)
412 | self.style_map = style_map.transpose((2, 0, 1))[np.newaxis].astype(np.float32)
413 | # self.style_map.shape: (1, 3, 63, 52). channel num: 3
414 |
415 | # Compile a function to run on the GPU to extract patches for all layers at once.
416 | # layer_outputs: [ ('3_1', sem3_1_output), ('4_1', sem4_1_output) ]
417 | # sem3_1 = conv3_1 + map3, sem4_1 = conv4_1 + map4
418 | layer_outputs = zip(self.style_layers, self.model.get_outputs('sem', self.style_layers))
419 | # ext_patches: symbolic results from extracting patches from output of
420 | # 'sem3_1' & 'sem4_1'. Input to the network is required
421 | ext_patches = self.do_extract_patches(layer_outputs)
422 | # extractor: 6 symbolic operators that take two inputs
423 | # Assign inputs to tensor_img & tensor_map. Get output from tensor_outputs
424 | # Then extract patches from tensor_outputs
425 | extractor = self.compile([self.model.tensor_img, self.model.tensor_map], ext_patches)
426 | # feed two inputs into each of the 6 symbolic operators
427 | # Assign tensor_img = self.style_img, tensor_map = self.style_map
428 |
429 | # self.style_map.shape: (1, 3, 63, 52). channel num: 3
430 | result = extractor(self.style_img, self.style_map)
431 | # result: conv output of sem*, given style_img | style_map
432 | # a list of 6 arrays in shapes:
433 | # result[0::3] result[1::3] result[2::3]
434 | # sem3_1 (143, 259, 3, 3), (143, 1, 3, 3), (143, 1, 3, 3),
435 | # sem4_1 (20, 515, 3, 3), (20, 1, 3, 3), (20, 1, 3, 3)
436 | # sem3_1_outneighbs conv3_1_neibnorms map3_1_neibnorms
437 | # sem4_1_outneighbs conv4_1_neibnorms map4_1_neibnorms
438 | # Store all the style patches layer by layer, split to match slice size and cast to 16-bit for size.
439 | self.style_data = {}
440 | for layer, *data in zip(self.style_layers, result[0::3], result[1::3], result[2::3]):
441 | # data[0]: neighbors of sem* output
442 | # data[1]: norms of sem* output
443 | # data[2]: norms of semantic pooling layer output
444 | patches = data[0]
445 | l = self.model.network['nn'+layer]
446 | # args.slices: 'Split patches up into this number of batches.' Default: 2
447 | # nn3_1(4_1).num_filters: initialized to the patch num in each slice.
448 | # the original num_filters = '1' has been changed
449 | # nn3_1(4_1).W will be set to each patch later
450 | l.num_filters = patches.shape[0] // args.slices
451 | # self.style_data['3_1']: [0]: sem3_1_outneighbs, [1]: conv3_1_neibnorms,
452 | # [2]: map3_1_neibnorms, [3]: zeros(660) - storing matching history used in evaluate_slices()
453 | self.style_data[layer] = [d[:l.num_filters*args.slices].astype(np.float16) for d in data]\
454 | + [np.zeros((patches.shape[0],), dtype=np.float16)]
455 | print(' - Style layer {}: {} patches in {:,}kb.'.format(layer, patches.shape, patches.size//1000))
456 |
457 | # style_data['3_1'][0]: (142, 259, 3, 3)
458 | # style_data['4_1'][0]: (20, 515, 3, 3)
459 | # num_filters - nn3_1: 71, nn4_1: 10
460 |
461 | def prepare_optimization(self):
462 | """Optimization requires a function to compute the error (aka. loss) which is done in multiple components.
463 | Here we compile a function to run on the GPU that returns all components separately.
464 | """
465 |
466 | # Feed-forward calculation only, returns the result of the convolution post-activation
467 | self.compute_features = self.compile([self.model.tensor_img, self.model.tensor_map],
468 | self.model.get_outputs('sem', self.style_layers))
469 |
470 | # Patch matching calculation that uses only pre-calculated features and a slice of the patches.
471 |
472 | # create empty Theano shared variable for matcher_history of 3_1, 4_1 and 1_laplace
473 | self.matcher_tensors = {l: lasagne.utils.shared_empty(dim=4) for l in self.style_layers}
474 | # matcher_history will be set to style_data[-1] later
475 | self.matcher_history = {l: T.vector() for l in self.style_layers}
476 | # dup3_1 = matcher_tensors['3_1'], dup4_1 = matcher_tensors['4_1']
477 | # matcher_tensors will be set to normalized current_features in evaluate():
478 | # sem3_1, sem4_1 conv output given content_img
479 | # so dup* = normalized conv output of sem* on content_img
480 | # dup* is the input of sem*
481 | self.matcher_inputs = {self.model.network['dup'+l]: self.matcher_tensors[l] for l in self.style_layers}
482 | # nn_layers = ['nn3_1', 'nn4_1']
483 | # nn*.W will be set to normalized style patches in evaluate_slices() <- evaluate() <- fmin_l_bfgs_b()
484 | nn_layers = [self.model.network['nn'+l] for l in self.style_layers]
485 | # 3_1 => nn3_1_output, 4_1 => nn4_1_output, given dup* = conv output of sem* on content_img
486 | self.matcher_outputs = dict(zip(self.style_layers, lasagne.layers.get_output(nn_layers, self.matcher_inputs)))
487 |
488 | # conv of nn* computes the cross correlation between conv outputs of sem*, given content_img and style_img, respectively
489 | # do_match_patches() will find the patch indices corresponding to max conv output
490 | self.compute_matches = {l: self.compile([self.matcher_history[l]], self.do_match_patches(l))\
491 | for l in self.style_layers}
492 |
493 | self.tensor_matches = [T.tensor4() for l in self.style_layers]
494 | # Build a list of Theano expressions that, once summed up, compute the total error.
495 | self.losses = self.content_loss() + self.total_variation_loss() + self.style_loss()
496 | # losses = [('smooth', 'img', Elemwise{mul,no_inplace}.0), ('style', '3_1', Elemwise{mul,no_inplace}.0),
497 | # ('style', '4_1', Elemwise{mul,no_inplace}.0)]
498 | # 'smooth': total variation loss
499 | # Let Theano automatically compute the gradient of the error, used by LBFGS to update image pixels.
500 | grad = T.grad(sum([l[-1] for l in self.losses]), self.model.tensor_img)
501 | # Create a single function that returns the gradient and the individual errors components.
502 | self.compute_grad_and_losses = theano.function(
503 | [self.model.tensor_img, self.model.tensor_map] + self.tensor_matches,
504 | [grad] + [l[-1] for l in self.losses], on_unused_input='ignore')
505 |
506 |
507 | #------------------------------------------------------------------------------------------------------------------
508 | # Theano Computation
509 | #------------------------------------------------------------------------------------------------------------------
510 |
511 | # layers: [ ('3_1', sem(conv)3_1_output), ('4_1', sem(conv)4_1_output) ]
512 | # extract 3*3 patches from the conv output
513 | # size = the filter size in nn* layers. So the patches will be assigned to nn*.W
514 | def do_extract_patches(self, layers, size=3, stride=1):
515 | """This function builds a Theano expression that will get compiled an run on the GPU. It extracts 3x3 patches
516 | from the intermediate outputs in the model.
517 | """
518 | results = []
519 | # l: '3_1', f: sem3_1_output
520 | # sem3_1_output.shape: [1,259,15,13]
521 | # 259: conv3_1: 256 + map3_1: 3
522 | # patches.shape: [10300,9]: 10300 = 259 * (15-2) * (13-2)
523 | # patches shape after reshape: [143,259,3,3]
524 | for l, f in layers:
525 | # Use a Theano helper function to extract "neighbors" of specific size, seems a bit slower than doing
526 | # it manually but much simpler!
527 | # images2neibs() gets small patches in (size*size) from sem(conv)3(4)_1_output,
528 | # i.e. small patches in the neural encoding tensor
529 | # first dimension of "patches" is "filter", so in sem*, the first dimensionality is num_filters of conv* + map*
530 | patches = theano.tensor.nnet.neighbours.images2neibs(f, (size, size), (stride, stride), mode='valid')
531 | # Make sure the patches are in the shape required to insert them into the model as another layer.
532 | patches = patches.reshape((-1, patches.shape[0] // f.shape[1], size, size)).dimshuffle((1, 0, 2, 3))
533 | # Calculate the magnitude that we'll use for normalization at runtime, then store...
534 | # each call of compute_norms() returns two arrays
535 | # if l==sem*, conv* neighbor norms and map* neighbor norms
536 | # if l==conv*, conv* neighbor norms and an empty array
537 | results.extend([patches] + self.compute_norms(T, l, patches))
538 | # self.compute_norms(T, l, patches) returns the (symbolic) magnitude for normalization
539 | return results
540 |
541 | def do_match_patches(self, layer):
542 | # Use node in the model to compute the result of the normalized cross-correlation, using results from the
543 | # nearest-neighbor layers called 'nn3_1' and 'nn4_1'.
544 | # dist: distances (nn_layer outputs)
545 | # dist from nn3_1: [1, 71, 14, 9]
546 | # dist from nn4_1: [1, 10, 6, 3]
547 | # matcher takes normalized content features as matcher_inputs, and normalized sem* features as weights
548 | # matcher_outputs are normalized cross-correlations between normalized content features and sem* features
549 | dist = self.matcher_outputs[layer]
550 | # dist.shape is now (71,126) or (10, 18)
551 | dist = dist.reshape((dist.shape[1], -1))
552 | # Compute the score of each patch, taking into account statistics from previous iteration. This equalizes
553 | # the chances of the patches being selected when the user requests more variety.
554 | # matcher_history[layer] <= dist.max(axis=1), the best dist for each filter in the last run
555 | offset = self.matcher_history[layer].reshape((-1, 1))
556 | scores = (dist - offset * args.variety)
557 | # Pick the best style patches for each patch in the current image, the result is an array of indices.
558 | # Also return the maximum value along both axis, used to compare slices and add patch variety.
559 | # axis 0: filter num, axis 1: patch num
560 | # argmax(axis=0): 126(18), argmax for each patch
561 | # argmax(axis=1): 71(10), argmax for each filter
562 | return [scores.argmax(axis=0), scores.max(axis=0), dist.max(axis=1)]
563 |
564 |
565 | #------------------------------------------------------------------------------------------------------------------
566 | # Error/Loss Functions
567 | #------------------------------------------------------------------------------------------------------------------
568 |
569 | def content_loss(self):
570 | """Return a list of Theano expressions for the error function, measuring how different the current image is
571 | from the reference content that was loaded.
572 | """
573 |
574 | content_loss = []
575 | if args.content_weight == 0.0:
576 | return content_loss
577 |
578 | # First extract all the features we need from the model, these results after convolution.
579 | # content_layers: conv4_2 (only one layer)
580 | extractor = theano.function([self.model.tensor_img], self.model.get_outputs('conv', self.content_layers))
581 | # conv output of the original content image. 512d
582 | result = extractor(self.content_img)
583 |
584 | # Build a list of loss components that compute the mean squared error by comparing current result to desired.
585 | for l, ref in zip(self.content_layers, result):
586 | # input: tensor_img = current_img, tensor_map = content_map
587 | # layer: output from conv4_2
588 | layer = self.model.tensor_outputs['conv'+l]
589 | loss = T.mean((layer - ref) ** 2.0)
590 |
591 | if 'lap' not in l:
592 | content_loss.append(('content', l, args.content_weight * loss))
593 | else:
594 | content_loss.append(('content', l, args.lap_weight * loss))
595 |
596 | print(' - Content layer conv{}: {} features in {:,}kb.'.format(l, ref.shape[1], ref.size//1000))
597 | return content_loss
598 |
599 | def style_loss(self):
600 | """Returns a list of loss components as Theano expressions. Finds the best style patch for each patch in the
601 | current image using normalized cross-correlation, then computes the mean squared error for all patches.
602 | """
603 | style_loss = []
604 | if args.style_weight == 0.0:
605 | return style_loss
606 |
607 | # Extract the patches from the current image, as well as their magnitude.
608 | result = self.do_extract_patches(zip(self.style_layers, self.model.get_outputs('conv', self.style_layers)))
609 |
610 | # Multiple style layers are optimized separately, usually conv3_1 and conv4_1. Semantic data not used here.
611 | # Semantic data is only used for selecting nearest neighbor style patches
612 | # tensor_matches = current_best, i.e. indices of best matching patches in each layer
613 | for l, matches, patches in zip(self.style_layers, self.tensor_matches, result[0::3]):
614 | # Compute the mean squared error between the current patch and the best matching style patch.
615 | # Ignore the last channels (from semantic map) so errors returned are indicative of image only.
616 | # matches = tensor_matches[i] = current_best[i]
617 | loss = T.mean((patches - matches[:,:self.model.channels[l]]) ** 2.0)
618 | if 'laplace' not in l:
619 | style_loss.append(('style', l, args.style_weight * loss))
620 | else:
621 | style_loss.append(('style', l, args.style_lapweight * loss))
622 |
623 | return style_loss
624 |
625 | def total_variation_loss(self):
626 | """Return a loss component as Theano expression for the smoothness prior on the result image.
627 | """
628 | # here tensor_img is always current_img
629 | x = self.model.tensor_img
630 | loss = (((x[:,:,:-1,:-1] - x[:,:,1:,:-1])**2 + (x[:,:,:-1,:-1] - x[:,:,:-1,1:])**2)**1.25).mean()
631 | return [('smooth', 'img', args.smoothness * loss)]
632 |
633 | #------------------------------------------------------------------------------------------------------------------
634 | # Optimization Loop
635 | #------------------------------------------------------------------------------------------------------------------
636 |
637 | def iterate_batches(self, *arrays, batch_size):
638 | """Break down the data in arrays batch by batch and return them as a generator.
639 | """
640 | total_size = arrays[0].shape[0]
641 | indices = np.arange(total_size)
642 | for index in range(0, total_size, batch_size):
643 | excerpt = indices[index:index + batch_size]
644 | yield excerpt, [a[excerpt] for a in arrays]
645 |
646 | # argument f is not directly used in this function
647 | # f is set to matcher_tensors['3_1'('4_1')].
648 | # dup3_1(4_1) = matcher_tensors['3_1'('4_1')], input of nn3_1(4_1)
649 | # input to nn3_1: (1, 259, 16, 11)
650 | # input to nn4_1: (1, 515, 8, 5)
651 | # output from nn3_1: [1, 71, 14, 9]
652 | # output from nn4_1: [1, 10, 6, 3]
653 | # best_idx from nn3_1: 126 (length)
654 | # best_idx from nn4_1: 18 (length)
655 | def evaluate_slices(self, f, l):
656 | # if cache is on, only use previously saved matches
657 | if args.cache and l in self.style_cache:
658 | return self.style_cache[l]
659 |
660 | # style_data: style patches & norms, i.e. 'sem3(4)_1' output given style_img & style_map
661 | # these patches will be set to the weights of 'nn3(4)_1'
662 | layer, data = self.model.network['nn'+l], self.style_data[l]
663 | # history: 143 or 20. Effective: 142 or 20
664 | history = data[-1]
665 |
666 | best_idx, best_val = None, 0.0
667 | # bp: sem3(4)_1_outneighbs, bi: conv3(4)_1_neibnorms,
668 | # bs: map3(4)_1_neibnorms, bh: (660) - history slice (not used: history is directly accessed)
669 | for idx, (bp, bi, bs, bh) in self.iterate_batches(*data, batch_size=layer.num_filters):
670 | weights = bp.astype(np.float32)
671 | # after normalization the conv result will be the cross correlation between sem* patches and the img patches
672 | self.normalize_components(l, weights, (bi, bs))
673 | # weights.shape: (71, 259, 3, 3)
674 | # nn3_1(4_1) num_filters (output channels): 71. input channels: 259
675 | # print nn3_1.input_shape: (1,257,None,None).
676 | # 257 is based on the initialized map shape: 1,1,..,..
677 | # however the actual map shape is 1,3,..,... so nn3_1.input_shape should be 1,259,..,..
678 | layer.W.set_value(weights)
679 |
680 | # history[idx] works as offsets to the correlations
681 | # encourage matches that are different from the previous iteration, to boost diversity
682 | # max indices, max scores (dist - offset), max dists
683 | # (126)/(18) (126)/(18) (71)/(10)
684 | cur_idx, cur_val, cur_match = self.compute_matches[l](history[idx])
685 |
686 | if best_idx is None:
687 | best_idx, best_val = cur_idx, cur_val
688 | else:
689 | i = np.where(cur_val > best_val)
690 | # update those indices where cur_val are larger. i is a boolean array
691 | best_idx[i] = idx[cur_idx[i]]
692 | best_val[i] = cur_val[i]
693 |
694 | # idx: indices for the current batch. 0..71 & 71..142
695 | history[idx] = cur_match
696 |
697 | if args.cache:
698 | self.style_cache[l] = best_idx
699 | return best_idx
700 |
701 | def varshape(self):
702 | return [ self.matcher_outputs[l].shape for l in self.style_layers ]
703 |
704 | def evaluate(self, Xn):
705 | """Callback for the L-BFGS optimization that computes the loss and gradients on the GPU.
706 | """
707 | # Xn: content_img or noisy input (depending on the program argument)
708 | # Adjust the representation to be compatible with the model before computing results.
709 | # demean the original content image as the initialized transfer image
710 | current_img = Xn.reshape(self.content_img.shape).astype(np.float32) - self.model.pixel_mean
711 | # tensor_img = content_img, tensor_map = content_map
712 | # current_features: sem3_1, sem4_1 conv output given content_img
713 | current_features = self.compute_features(current_img, self.content_map)
714 |
715 | # Iterate through each of the style layers one by one, computing best matches.
716 | current_best = []
717 | for l, f in zip(self.style_layers, current_features):
718 | # content patches are normalized here
719 | self.normalize_components(l, f, self.compute_norms(np, l, f))
720 | self.matcher_tensors[l].set_value(f)
721 | # input to nn3_1: (1, 259, 16, 11)
722 | # input to nn4_1: (1, 515, 8, 5)
723 |
724 | # Compute best matching patches in this style layer, going through all slices.
725 | warmup = bool(args.variety > 0.0 and self.iteration == 0)
726 | for _ in range(2 if warmup else 1):
727 | best_idx = self.evaluate_slices(f, l)
728 |
729 | patches = self.style_data[l][0]
730 | current_best.append(patches[best_idx].astype(np.float32))
731 | # current_best: (126, 259, 3, 3), (18, 515, 3, 3)
732 | # output from nn3_1: [1, 71, 14, 9]
733 | # output from nn4_1: [1, 10, 6, 3]
734 | #varshape = self.compile( [self.model.tensor_img, self.model.tensor_map], self.varshape() )
735 | #shapes = varshape(current_img, self.content_map)
736 |
737 | # tensor_img = current_img, tensor_map = content_map, tensor_matches = current_best
738 | grads, *losses = self.compute_grad_and_losses(current_img, self.content_map, *current_best)
739 | if np.isnan(grads).any():
740 | raise OverflowError("Optimization diverged; try using a different device or parameters.")
741 |
742 | # Use magnitude of gradients as an estimate for overall quality.
743 | self.error = self.error * 0.9 + 0.1 * min(np.abs(grads).max(), 255.0)
744 | loss = sum(losses)
745 |
746 | # Dump the image to disk if requested by the user.
747 | if args.save_every and self.frame % args.save_every == 0:
748 | frame = Xn.reshape(self.content_img.shape[1:])
749 | resolution = self.content_img_original.shape
750 | image = scipy.misc.toimage(self.model.finalize_image(frame, resolution), cmin=0, cmax=255)
751 | image.save('frames/%04d.png'%self.frame)
752 |
753 | # Print more information to the console every few iterations.
754 | if args.print_every and self.frame % args.print_every == 0:
755 | print('{:>3} {}loss{} {:8.2e} '.format(self.frame, ansi.BOLD, ansi.ENDC, loss / 1000.0), end='')
756 | category = ''
757 | for v, l in zip(losses, self.losses):
758 | if l[0] == 'smooth':
759 | continue
760 | if l[0] != category:
761 | print(' {}{}{}'.format(ansi.BOLD, l[0], ansi.ENDC), end='')
762 | category = l[0]
763 | print(' {}{}{} {:8.2e} '.format(ansi.BOLD, l[1], ansi.ENDC, v / 1000.0), end='')
764 |
765 | current_time = time.time()
766 | quality = 100.0 - 100.0 * np.sqrt(self.error / 255.0)
767 | print(' {}quality{} {: >4.1f}% '.format(ansi.BOLD, ansi.ENDC, quality), end='')
768 | print(' {}time{} {:3.1f}s '.format(ansi.BOLD, ansi.ENDC, current_time - self.iter_time), flush=True)
769 | self.iter_time = current_time
770 |
771 | # Update counters and timers.
772 | self.frame += 1
773 | self.iteration += 1
774 |
775 | # Return the data in the right format for L-BFGS.
776 | return loss, np.array(grads).flatten().astype(np.float64)
777 |
778 | def run(self):
779 | """The main entry point for the application, runs through multiple phases at increasing resolutions.
780 | """
781 | self.frame, Xn = 0, None
782 | for i in range(args.phases):
783 | self.error = 255.0
784 | scale = 1.0 / 2.0 ** (args.phases - 1 - i)
785 |
786 | shape = self.content_img_original.shape
787 | print('\n{}Phase #{}: resolution {}x{} scale {}{}'\
788 | .format(ansi.BLUE_B, i, int(shape[1]*scale), int(shape[0]*scale), scale, ansi.BLUE))
789 |
790 | # Precompute all necessary data for the various layers, put patches in place into augmented network.
791 | self.model.setup(layers=['sem'+l for l in self.style_layers] + ['conv'+l for l in self.content_layers])
792 | self.prepare_content(scale)
793 | self.prepare_style(scale)
794 |
795 | # Now setup the model with the new data, ready for the optimization loop.
796 | self.model.setup(layers=['sem'+l for l in self.style_layers] + ['conv'+l for l in self.used_layers])
797 | self.prepare_optimization()
798 | print('{}'.format(ansi.ENDC))
799 |
800 | # Setup the seed for the optimization as specified by the user.
801 | shape = self.content_img.shape[2:]
802 | if args.seed == 'content':
803 | Xn = self.content_img[0] + self.model.pixel_mean
804 | if args.seed == 'noise':
805 | bounds = [int(i) for i in args.seed_range.split(':')]
806 | Xn = np.random.uniform(bounds[0], bounds[1], shape + (3,)).astype(np.float32)
807 | if args.seed == 'previous':
808 | Xn = scipy.misc.imresize(Xn[0], shape, interp='bicubic')
809 | Xn = Xn.transpose((2, 0, 1))[np.newaxis]
810 | if os.path.exists(args.seed):
811 | seed_image = scipy.ndimage.imread(args.seed, mode='RGB')
812 | seed_image = scipy.misc.imresize(seed_image, shape, interp='bicubic')
813 | self.seed_image = self.model.prepare_image(seed_image)
814 | Xn = self.seed_image[0] + self.model.pixel_mean
815 | if Xn is None:
816 | error("Seed for optimization was not found. You can either...",
817 | " - Set the `--seed` to `content` or `noise`.", " - Specify `--seed` as a valid filename.")
818 |
819 | # Optimization algorithm needs min and max bounds to prevent divergence.
820 | data_bounds = np.zeros((np.product(Xn.shape), 2), dtype=np.float64)
821 | data_bounds[:] = (0.0, 255.0)
822 |
823 | self.iter_time, self.iteration, interrupt = time.time(), 0, False
824 | # Xn: the input content image
825 | # output new Xn: the best image that minimizes the losses
826 | try:
827 | Xn, Vn, info = scipy.optimize.fmin_l_bfgs_b(
828 | self.evaluate,
829 | Xn.astype(np.float64).flatten(),
830 | bounds=data_bounds,
831 | factr=0.0, pgtol=0.0, # Disable automatic termination, set low threshold.
832 | m=5, # Maximum correlations kept in memory by algorithm.
833 | maxfun=args.iterations-1, # Limit number of calls to evaluate().
834 | iprint=-1) # Handle our own logging of information.
835 | except OverflowError:
836 | error("The optimization diverged and NaNs were encountered.",
837 | " - Try using a different `--device` or change the parameters.",
838 | " - Make sure libraries are updated to work around platform bugs.")
839 | except KeyboardInterrupt:
840 | interrupt = True
841 |
842 | args.seed = 'previous'
843 | resolution = self.content_img.shape
844 | Xn = Xn.reshape(resolution)
845 |
846 | output = self.model.finalize_image(Xn[0], self.content_img_original.shape)
847 | scipy.misc.toimage(output, cmin=0, cmax=255).save(args.output)
848 | if interrupt: break
849 |
850 | status = "finished in" if not interrupt else "interrupted at"
851 | print('\n{}Optimization {} {:3.1f}s, average pixel error {:3.1f}!{}\n'\
852 | .format(ansi.CYAN, status, time.time() - self.start_time, self.error, ansi.ENDC))
853 |
854 |
855 | if __name__ == "__main__":
856 | generator = NeuralGenerator()
857 | generator.run()
858 |
--------------------------------------------------------------------------------
/output/boy_girl3_5_0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/output/boy_girl3_5_0.png
--------------------------------------------------------------------------------
/output/boy_girl3_5_100.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/output/boy_girl3_5_100.png
--------------------------------------------------------------------------------
/output/combinations/girlmrf_dogsketch5_1,2_50,100.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/output/combinations/girlmrf_dogsketch5_1,2_50,100.png
--------------------------------------------------------------------------------
/output/combinations/girlmrf_dogsketch5_1,3_50,400.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/output/combinations/girlmrf_dogsketch5_1,3_50,400.png
--------------------------------------------------------------------------------
/output/combinations/girlmrf_dogsketch5_1_50.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/output/combinations/girlmrf_dogsketch5_1_50.png
--------------------------------------------------------------------------------
/output/combinations/girlmrf_dogsketch5_2,3_100,400.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/output/combinations/girlmrf_dogsketch5_2,3_100,400.png
--------------------------------------------------------------------------------
/output/combinations/girlmrf_dogsketch5_2,4_100,1600.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/output/combinations/girlmrf_dogsketch5_2,4_100,1600.png
--------------------------------------------------------------------------------
/output/combinations/girlmrf_dogsketch5_2_100.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/output/combinations/girlmrf_dogsketch5_2_100.png
--------------------------------------------------------------------------------
/output/combinations/girlmrf_dogsketch_5_0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/output/combinations/girlmrf_dogsketch_5_0.png
--------------------------------------------------------------------------------
/output/combinations/girlmrf_dogsketch_5_100.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/output/combinations/girlmrf_dogsketch_5_100.png
--------------------------------------------------------------------------------
/output/combinations/girlmrf_dogsketch_5_200.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/output/combinations/girlmrf_dogsketch_5_200.png
--------------------------------------------------------------------------------
/output/girl2_cartoon2_20_0.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/output/girl2_cartoon2_20_0.jpg
--------------------------------------------------------------------------------
/output/girl2_cartoon2_20_100.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/output/girl2_cartoon2_20_100.png
--------------------------------------------------------------------------------
/output/girlmrf_girlsketch_5_0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/output/girlmrf_girlsketch_5_0.png
--------------------------------------------------------------------------------
/output/girlmrf_girlsketch_5_100.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/output/girlmrf_girlsketch_5_100.png
--------------------------------------------------------------------------------
/output/girlmrf_smallworldI_20_0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/output/girlmrf_smallworldI_20_0.png
--------------------------------------------------------------------------------
/output/girlmrf_smallworldI_20_200.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/output/girlmrf_smallworldI_20_200.png
--------------------------------------------------------------------------------
/output/goat_muse20_1_0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/output/goat_muse20_1_0.png
--------------------------------------------------------------------------------
/output/goat_muse20_2_100.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/output/goat_muse20_2_100.png
--------------------------------------------------------------------------------
/output/kid5_smallworldI_20_0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/output/kid5_smallworldI_20_0.png
--------------------------------------------------------------------------------
/output/kid5_smallworldI_20_200.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/output/kid5_smallworldI_20_200.png
--------------------------------------------------------------------------------
/output/laplacians/girl2_car2_0_edge.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/output/laplacians/girl2_car2_0_edge.png
--------------------------------------------------------------------------------
/output/laplacians/girl2_car2_edge.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/output/laplacians/girl2_car2_edge.png
--------------------------------------------------------------------------------
/output/laplacians/girl2_edge.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/output/laplacians/girl2_edge.png
--------------------------------------------------------------------------------
/output/megan_flowers20_0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/output/megan_flowers20_0.png
--------------------------------------------------------------------------------
/output/megan_flowers20_100.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/output/megan_flowers20_100.png
--------------------------------------------------------------------------------
/output/megan_starry10_0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/output/megan_starry10_0.png
--------------------------------------------------------------------------------
/output/megan_starry10_100.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/askerlee/lapstyle/60489ea862f2d53316a1dd83b6af7fff8324df38/output/megan_starry10_100.png
--------------------------------------------------------------------------------
/single-lap-exp.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash -x
2 | # test lap_style.lua with default settings on five test image pairs.
3 | # You can specify a different laplacian layer(s) using laplayersAll and lapweightsAll.
4 |
5 | contentimageAll=( megan.png kid5.png goat.png girlmrf.jpg boy.png)
6 | styleimageAll=( flowers.png smallworldI.jpg muse.jpg girlsketch.jpg girl3.jpg)
7 | inputLen=${#contentimageAll[@]}
8 | contentweight=20
9 | #laplayersAll=( 2 2,4)
10 | #lapweightsAll=(100 100,1600)
11 | laplayersAll=( 2)
12 | lapweightsAll=(100)
13 | configLen=${#laplayersAll[@]}
14 | for (( i=0; i<$inputLen; i++ )); do
15 | contentimage=${contentimageAll[$i]}
16 | contentname="${contentimage%.*}"
17 | styleimage=${styleimageAll[$i]}
18 | stylename="${styleimage%.*}"
19 | for (( j=0; j<$configLen; j++ )); do
20 | laplayers=${laplayersAll[$j]}
21 | lapweights=${lapweightsAll[$j]}
22 | outsig="${contentname}_${stylename}${contentweight}_${laplayers}_${lapweights}"
23 | th lap_style.lua -style_image images/$styleimage -content_image images/$contentimage -output_image output/${outsig}.png -content_weight $contentweight -lap_layers $laplayers -lap_weights $lapweights 2>&1| tee output/${outsig}.log
24 | outsig="${contentname}_${stylename}${contentweight}_${laplayers}_${lapweights}_nobp"
25 | th lap_style.lua -style_image images/$styleimage -content_image images/$contentimage -output_image output/${outsig}.png -content_weight $contentweight -lap_layers $laplayers -lap_weights $lapweights -lap_nobp 2>&1| tee output/${outsig}.log
26 | done
27 | done
28 |
--------------------------------------------------------------------------------
/tf-neural-style/neural_style.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2015-2017 Anish Athalye. Released under GPLv3.
2 | # Revised by Shaohua Li in Apr 2017.
3 | # Please refer to https://github.com/anishathalye/neural-style for a user manual
4 |
5 | import os
6 |
7 | import numpy as np
8 | import scipy.misc
9 |
10 | from stylize import stylize
11 |
12 | import math
13 | from argparse import ArgumentParser
14 |
15 | from PIL import Image
16 |
17 | # default arguments
18 | CONTENT_WEIGHT = 5.0
19 | LAP_LAYERS = '2'
20 | LAP_WEIGHT = 5e1
21 | CONTENT_WEIGHT_BLEND = 1.0
22 | STYLE_WEIGHT = 5e2
23 | TV_WEIGHT = 1e2
24 | STYLE_LAYER_WEIGHT_EXP = 1.0
25 | LEARNING_RATE = 1e1
26 | BETA1 = 0.9
27 | BETA2 = 0.999
28 | EPSILON = 1e-08
29 | STYLE_SCALE = 1.0
30 | ITERATIONS = 1000
31 | VGG_PATH = 'imagenet-vgg-verydeep-19.mat'
32 | POOLING = 'max'
33 | CHECKPOINT_ITERATIONS = 100
34 | PRINT_ITERATIONS = 50
35 |
36 | def build_parser():
37 | parser = ArgumentParser()
38 | parser.add_argument('--content',
39 | dest='content', help='content image',
40 | metavar='CONTENT', required=True)
41 | parser.add_argument('--styles',
42 | dest='styles',
43 | nargs='+', help='one or more style images',
44 | metavar='STYLE', required=True)
45 | parser.add_argument('--output',
46 | dest='output', help='output path',
47 | metavar='OUTPUT', required=True)
48 | parser.add_argument('--iterations', type=int,
49 | dest='iterations', help='iterations (default %(default)s)',
50 | metavar='ITERATIONS', default=ITERATIONS)
51 | parser.add_argument('--print-iterations', type=int,
52 | dest='print_iterations', help='statistics printing frequency',
53 | metavar='PRINT_ITERATIONS', default=PRINT_ITERATIONS)
54 | parser.add_argument('--checkpoint-output',
55 | dest='checkpoint_output', help='checkpoint output format, e.g. output%%s.jpg',
56 | metavar='OUTPUT')
57 | parser.add_argument('--checkpoint-iterations', type=int,
58 | dest='checkpoint_iterations', help='checkpoint frequency',
59 | metavar='CHECKPOINT_ITERATIONS', default=CHECKPOINT_ITERATIONS)
60 | parser.add_argument('--width', type=int,
61 | dest='width', help='output width',
62 | metavar='WIDTH')
63 | parser.add_argument('--style-scales', type=float,
64 | dest='style_scales',
65 | nargs='+', help='one or more style scales',
66 | metavar='STYLE_SCALE')
67 | parser.add_argument('--network',
68 | dest='network', help='path to network parameters (default %(default)s)',
69 | metavar='VGG_PATH', default=VGG_PATH)
70 | parser.add_argument('--content-weight-blend', type=float,
71 | dest='content_weight_blend', help='content weight blend, conv4_2 * blend + conv5_2 * (1-blend) (default %(default)s)',
72 | metavar='CONTENT_WEIGHT_BLEND', default=CONTENT_WEIGHT_BLEND)
73 | parser.add_argument('--lap-layers', type=str,
74 | dest='lap_layers', help='Laplacian layers (default %(default)s)',
75 | metavar='LAP_LAYERS', default=LAP_LAYERS)
76 | parser.add_argument('--lap-weight', type=float,
77 | dest='lap_weight', help='laplacian weight (default %(default)s)',
78 | metavar='LAP_WEIGHT', default=LAP_WEIGHT)
79 | parser.add_argument('--content-weight', type=float,
80 | dest='content_weight', help='content weight (default %(default)s)',
81 | metavar='CONTENT_WEIGHT', default=CONTENT_WEIGHT)
82 | parser.add_argument('--style-weight', type=float,
83 | dest='style_weight', help='style weight (default %(default)s)',
84 | metavar='STYLE_WEIGHT', default=STYLE_WEIGHT)
85 | parser.add_argument('--style-layer-weight-exp', type=float,
86 | dest='style_layer_weight_exp', help='style layer weight exponentional increase - weight(layer) = weight_exp*weight(layer) (default %(default)s)',
87 | metavar='STYLE_LAYER_WEIGHT_EXP', default=STYLE_LAYER_WEIGHT_EXP)
88 | parser.add_argument('--style-blend-weights', type=float,
89 | dest='style_blend_weights', help='style blending weights',
90 | nargs='+', metavar='STYLE_BLEND_WEIGHT')
91 | parser.add_argument('--tv-weight', type=float,
92 | dest='tv_weight', help='total variation regularization weight (default %(default)s)',
93 | metavar='TV_WEIGHT', default=TV_WEIGHT)
94 | parser.add_argument('--learning-rate', type=float,
95 | dest='learning_rate', help='learning rate (default %(default)s)',
96 | metavar='LEARNING_RATE', default=LEARNING_RATE)
97 | parser.add_argument('--beta1', type=float,
98 | dest='beta1', help='Adam: beta1 parameter (default %(default)s)',
99 | metavar='BETA1', default=BETA1)
100 | parser.add_argument('--beta2', type=float,
101 | dest='beta2', help='Adam: beta2 parameter (default %(default)s)',
102 | metavar='BETA2', default=BETA2)
103 | parser.add_argument('--eps', type=float,
104 | dest='epsilon', help='Adam: epsilon parameter (default %(default)s)',
105 | metavar='EPSILON', default=EPSILON)
106 | parser.add_argument('--initial',
107 | dest='initial', help='initial image',
108 | metavar='INITIAL')
109 | parser.add_argument('--initial-noiseblend', type=float,
110 | dest='initial_noiseblend', help='ratio of blending initial image with normalized noise (if no initial image specified, content image is used) (default %(default)s)',
111 | metavar='INITIAL_NOISEBLEND')
112 | parser.add_argument('--preserve-colors', action='store_true',
113 | dest='preserve_colors', help='style-only transfer (preserving colors) - if color transfer is not needed')
114 | parser.add_argument('--pooling',
115 | dest='pooling', help='pooling layer configuration: max or avg (default %(default)s)',
116 | metavar='POOLING', default=POOLING)
117 | return parser
118 |
119 |
120 | def main():
121 | parser = build_parser()
122 | options = parser.parse_args()
123 |
124 | if not os.path.isfile(options.network):
125 | parser.error("Network %s does not exist. (Did you forget to download it?)" % options.network)
126 |
127 | content_image = imread(options.content)
128 | style_images = [imread(style) for style in options.styles]
129 |
130 | width = options.width
131 | if width is not None:
132 | new_shape = (int(math.floor(float(content_image.shape[0]) /
133 | content_image.shape[1] * width)), width)
134 | content_image = scipy.misc.imresize(content_image, new_shape)
135 | target_shape = content_image.shape
136 | for i in range(len(style_images)):
137 | style_scale = STYLE_SCALE
138 | if options.style_scales is not None:
139 | style_scale = options.style_scales[i]
140 | style_images[i] = scipy.misc.imresize(style_images[i], style_scale *
141 | target_shape[1] / style_images[i].shape[1])
142 |
143 | style_blend_weights = options.style_blend_weights
144 | if style_blend_weights is None:
145 | # default is equal weights
146 | style_blend_weights = [1.0/len(style_images) for _ in style_images]
147 | else:
148 | total_blend_weight = sum(style_blend_weights)
149 | style_blend_weights = [weight/total_blend_weight
150 | for weight in style_blend_weights]
151 |
152 | options.lap_layers = options.lap_layers.split(',')
153 |
154 | initial = options.initial
155 | if initial is not None:
156 | initial = scipy.misc.imresize(imread(initial), content_image.shape[:2])
157 | # Initial guess is specified, but not noiseblend - no noise should be blended
158 | if options.initial_noiseblend is None:
159 | options.initial_noiseblend = 0.0
160 | else:
161 | # Neither inital, nor noiseblend is provided, falling back to random generated initial guess
162 | if options.initial_noiseblend is None:
163 | options.initial_noiseblend = 1.0
164 | if options.initial_noiseblend < 1.0:
165 | initial = content_image
166 |
167 | if options.checkpoint_output and "%s" not in options.checkpoint_output:
168 | parser.error("To save intermediate images, the checkpoint output "
169 | "parameter must contain `%s` (e.g. `foo%s.jpg`)")
170 |
171 | for iteration, image in stylize(
172 | network=options.network,
173 | initial=initial,
174 | initial_noiseblend=options.initial_noiseblend,
175 | content=content_image,
176 | styles=style_images,
177 | preserve_colors=options.preserve_colors,
178 | iterations=options.iterations,
179 | content_weight=options.content_weight,
180 | content_weight_blend=options.content_weight_blend,
181 | lap_layers=options.lap_layers,
182 | lap_weight=options.lap_weight,
183 | style_weight=options.style_weight,
184 | style_layer_weight_exp=options.style_layer_weight_exp,
185 | style_blend_weights=style_blend_weights,
186 | tv_weight=options.tv_weight,
187 | learning_rate=options.learning_rate,
188 | beta1=options.beta1,
189 | beta2=options.beta2,
190 | epsilon=options.epsilon,
191 | pooling=options.pooling,
192 | print_iterations=options.print_iterations,
193 | checkpoint_iterations=options.checkpoint_iterations
194 | ):
195 | output_file = None
196 | combined_rgb = image
197 | if iteration is not None:
198 | if options.checkpoint_output:
199 | output_file = options.checkpoint_output % iteration
200 | else:
201 | output_file = options.output
202 | if output_file:
203 | imsave(output_file, combined_rgb)
204 |
205 |
206 | def imread(path):
207 | img = scipy.misc.imread(path).astype(np.float)
208 | if len(img.shape) == 2:
209 | # grayscale
210 | img = np.dstack((img,img,img))
211 | elif img.shape[2] == 4:
212 | # PNG with alpha channel
213 | img = img[:,:,:3]
214 | return img
215 |
216 |
217 | def imsave(path, img):
218 | img = np.clip(img, 0, 255).astype(np.uint8)
219 | Image.fromarray(img).save(path, quality=95)
220 |
221 | if __name__ == '__main__':
222 | main()
223 |
--------------------------------------------------------------------------------
/tf-neural-style/stylize.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2015-2017 Anish Athalye. Released under GPLv3.
2 |
3 | import vgg
4 |
5 | import tensorflow as tf
6 | import numpy as np
7 |
8 | from sys import stderr
9 |
10 | from PIL import Image
11 |
12 | CONTENT_LAYERS = ['relu4_2', 'relu5_2']
13 | STYLE_LAYERS = ('relu1_1', 'relu2_1', 'relu3_1', 'relu4_1', 'relu5_1')
14 |
15 | try:
16 | reduce
17 | except NameError:
18 | from functools import reduce
19 |
20 |
21 | def stylize(network, initial, initial_noiseblend, content, styles, preserve_colors, iterations,
22 | content_weight, content_weight_blend, lap_weight, lap_layers,
23 | style_weight, style_layer_weight_exp, style_blend_weights, tv_weight,
24 | learning_rate, beta1, beta2, epsilon, pooling,
25 | print_iterations=None, checkpoint_iterations=None):
26 | """
27 | Stylize images.
28 |
29 | This function yields tuples (iteration, image); `iteration` is None
30 | if this is the final image (the last iteration). Other tuples are yielded
31 | every `checkpoint_iterations` iterations.
32 |
33 | :rtype: iterator[tuple[int|None,image]]
34 | """
35 | shape = (1,) + content.shape
36 | style_shapes = [(1,) + style.shape for style in styles]
37 | content_features = {}
38 | style_features = [{} for _ in styles]
39 |
40 | vgg_weights, vgg_mean_pixel = vgg.load_net(network)
41 |
42 | layer_weight = 1.0
43 | style_layers_weights = {}
44 | for style_layer in STYLE_LAYERS:
45 | style_layers_weights[style_layer] = layer_weight
46 | layer_weight *= style_layer_weight_exp
47 |
48 | # normalize style layer weights
49 | layer_weights_sum = 0
50 | for style_layer in STYLE_LAYERS:
51 | layer_weights_sum += style_layers_weights[style_layer]
52 | for style_layer in STYLE_LAYERS:
53 | style_layers_weights[style_layer] /= layer_weights_sum
54 |
55 | global CONTENT_LAYERS
56 | for lap_layer in lap_layers:
57 | CONTENT_LAYERS.append( 'lap'+lap_layer )
58 |
59 | # compute content features in feedforward mode
60 | g = tf.Graph()
61 | with g.as_default(), g.device('/cpu:0'), tf.Session() as sess:
62 | image = tf.placeholder('float', shape=shape)
63 | net = vgg.net_preloaded(vgg_weights, image, pooling)
64 | content_pre = np.array([vgg.preprocess(content, vgg_mean_pixel)])
65 | for layer in CONTENT_LAYERS:
66 | content_features[layer] = net[layer].eval(feed_dict={image: content_pre})
67 |
68 | if len(lap_layers) > 0:
69 | stderr.write('Lap layers: %s\n' %(', '.join(lap_layers)))
70 |
71 | # compute style features in feedforward mode
72 | for i in range(len(styles)):
73 | g = tf.Graph()
74 | with g.as_default(), g.device('/cpu:0'), tf.Session() as sess:
75 | image = tf.placeholder('float', shape=style_shapes[i])
76 | net = vgg.net_preloaded(vgg_weights, image, pooling)
77 | style_pre = np.array([vgg.preprocess(styles[i], vgg_mean_pixel)])
78 | for layer in STYLE_LAYERS:
79 | features = net[layer].eval(feed_dict={image: style_pre})
80 | features = np.reshape(features, (-1, features.shape[3]))
81 | gram = np.matmul(features.T, features) / features.size
82 | style_features[i][layer] = gram
83 |
84 | initial_content_noise_coeff = 1.0 - initial_noiseblend
85 | #content_weight_step = (content_weight_max - content_weight_min) * 1.0 / iterations
86 | #stderr.write('content weight step: %.2f\n' % content_weight_step)
87 |
88 | # make stylized image using backpropogation
89 | with tf.Graph().as_default():
90 | if initial is None:
91 | noise = np.random.normal(size=shape, scale=np.std(content) * 0.1)
92 | initial = tf.random_normal(shape) * 0.256
93 | else:
94 | initial = np.array([vgg.preprocess(initial, vgg_mean_pixel)])
95 | initial = initial.astype('float32')
96 | noise = np.random.normal(size=shape, scale=np.std(content) * 0.1)
97 | initial = (initial) * initial_content_noise_coeff + (tf.random_normal(shape) * 0.256) * (1.0 - initial_content_noise_coeff)
98 | image = tf.Variable(initial)
99 | net = vgg.net_preloaded(vgg_weights, image, pooling)
100 | #content_weight = tf.constant(content_weight_max, dtype=tf.float32)
101 |
102 | # content loss
103 | content_layers_weights = {}
104 | content_layers_weights['relu4_2'] = content_weight_blend
105 | content_layers_weights['relu5_2'] = 1.0 - content_weight_blend
106 |
107 | content_loss = 0
108 | lap_loss = 0
109 | content_losses = []
110 | lap_losses = []
111 |
112 | for content_layer in CONTENT_LAYERS:
113 | if 'lap' in content_layer:
114 | loss = lap_weight * (2 * tf.nn.l2_loss( net[content_layer] -
115 | content_features[content_layer] ) /
116 | content_features[content_layer].size )
117 | lap_losses.append(loss)
118 | else:
119 | weight = content_weight
120 | content_layer_weight = content_layers_weights[content_layer]
121 | loss = content_layer_weight * weight * (2 * tf.nn.l2_loss(
122 | net[content_layer] - content_features[content_layer]) /
123 | content_features[content_layer].size)
124 | content_losses.append(loss)
125 |
126 | content_loss += reduce(tf.add, content_losses)
127 | lap_loss += reduce(tf.add, lap_losses)
128 |
129 | # style loss
130 | style_loss = 0
131 | for i in range(len(styles)):
132 | style_losses = []
133 | for style_layer in STYLE_LAYERS:
134 | layer = net[style_layer]
135 | _, height, width, number = map(lambda i: i.value, layer.get_shape())
136 | size = height * width * number
137 | feats = tf.reshape(layer, (-1, number))
138 | gram = tf.matmul(tf.transpose(feats), feats) / size
139 | style_gram = style_features[i][style_layer]
140 | style_losses.append(style_layers_weights[style_layer] * 2 * tf.nn.l2_loss(gram - style_gram) / style_gram.size)
141 | style_loss += style_weight * style_blend_weights[i] * reduce(tf.add, style_losses)
142 |
143 | # total variation denoising
144 | tv_y_size = _tensor_size(image[:,1:,:,:])
145 | tv_x_size = _tensor_size(image[:,:,1:,:])
146 | tv_loss = tv_weight * 2 * (
147 | (tf.nn.l2_loss(image[:,1:,:,:] - image[:,:shape[1]-1,:,:]) /
148 | tv_y_size) +
149 | (tf.nn.l2_loss(image[:,:,1:,:] - image[:,:,:shape[2]-1,:]) /
150 | tv_x_size))
151 | # overall loss
152 | loss = content_loss + style_loss + tv_loss + lap_loss
153 |
154 | # optimizer setup
155 | train_step = tf.train.AdamOptimizer(learning_rate, beta1, beta2, epsilon).minimize(loss)
156 |
157 | def print_progress():
158 | stderr.write(' content loss: %g\n' % content_loss.eval())
159 | #stderr.write(' content weight: %g\n' % content_weight.eval())
160 | stderr.write(' laplacian loss: %g\n' % lap_loss.eval())
161 | stderr.write(' style loss: %g\n' % style_loss.eval())
162 | stderr.write(' tv loss: %g\n' % tv_loss.eval())
163 | stderr.write(' total loss: %g\n' % loss.eval())
164 |
165 | # optimization
166 | best_loss = float('inf')
167 | best = None
168 | with tf.Session() as sess:
169 | sess.run(tf.global_variables_initializer())
170 | stderr.write('Optimization started...\n')
171 | if (print_iterations and print_iterations != 0):
172 | print_progress()
173 | for i in range(iterations):
174 | stderr.write('Iteration %4d/%4d\n' % (i + 1, iterations))
175 | train_step.run()
176 | #content_weight = tf.constant( tf.add( content_weight, -content_weight_step ).eval() )
177 |
178 | last_step = (i == iterations - 1)
179 | if last_step or (print_iterations and i % print_iterations == 0):
180 | print_progress()
181 |
182 | if (checkpoint_iterations and i % checkpoint_iterations == 0) or last_step:
183 | this_loss = loss.eval()
184 | if this_loss < best_loss:
185 | best_loss = this_loss
186 | best = image.eval()
187 |
188 | img_out = vgg.unprocess(best.reshape(shape[1:]), vgg_mean_pixel)
189 |
190 | if preserve_colors and preserve_colors == True:
191 | original_image = np.clip(content, 0, 255)
192 | styled_image = np.clip(img_out, 0, 255)
193 |
194 | # Luminosity transfer steps:
195 | # 1. Convert stylized RGB->grayscale accoriding to Rec.601 luma (0.299, 0.587, 0.114)
196 | # 2. Convert stylized grayscale into YUV (YCbCr)
197 | # 3. Convert original image into YUV (YCbCr)
198 | # 4. Recombine (stylizedYUV.Y, originalYUV.U, originalYUV.V)
199 | # 5. Convert recombined image from YUV back to RGB
200 |
201 | # 1
202 | styled_grayscale = rgb2gray(styled_image)
203 | styled_grayscale_rgb = gray2rgb(styled_grayscale)
204 |
205 | # 2
206 | styled_grayscale_yuv = np.array(Image.fromarray(styled_grayscale_rgb.astype(np.uint8)).convert('YCbCr'))
207 |
208 | # 3
209 | original_yuv = np.array(Image.fromarray(original_image.astype(np.uint8)).convert('YCbCr'))
210 |
211 | # 4
212 | w, h, _ = original_image.shape
213 | combined_yuv = np.empty((w, h, 3), dtype=np.uint8)
214 | combined_yuv[..., 0] = styled_grayscale_yuv[..., 0]
215 | combined_yuv[..., 1] = original_yuv[..., 1]
216 | combined_yuv[..., 2] = original_yuv[..., 2]
217 |
218 | # 5
219 | img_out = np.array(Image.fromarray(combined_yuv, 'YCbCr').convert('RGB'))
220 |
221 |
222 | yield (
223 | (None if last_step else i),
224 | img_out
225 | )
226 |
227 |
228 | def _tensor_size(tensor):
229 | from operator import mul
230 | return reduce(mul, (d.value for d in tensor.get_shape()), 1)
231 |
232 | def rgb2gray(rgb):
233 | return np.dot(rgb[...,:3], [0.299, 0.587, 0.114])
234 |
235 | def gray2rgb(gray):
236 | w, h = gray.shape
237 | rgb = np.empty((w, h, 3), dtype=np.float32)
238 | rgb[:, :, 2] = rgb[:, :, 1] = rgb[:, :, 0] = gray
239 | return rgb
240 |
241 | def l1_loss(tensor):
242 | return tf.reduce_sum(tf.abs(tensor))
243 |
--------------------------------------------------------------------------------
/tf-neural-style/vgg.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2015-2017 Anish Athalye. Released under GPLv3.
2 |
3 | import tensorflow as tf
4 | import numpy as np
5 | import scipy.io
6 |
7 | VGG19_LAYERS = (
8 | 'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1',
9 |
10 | 'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2',
11 |
12 | 'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3',
13 | 'relu3_3', 'conv3_4', 'relu3_4', 'pool3',
14 |
15 | 'conv4_1', 'relu4_1', 'conv4_2', 'relu4_2', 'conv4_3',
16 | 'relu4_3', 'conv4_4', 'relu4_4', 'pool4',
17 |
18 | 'conv5_1', 'relu5_1', 'conv5_2', 'relu5_2', 'conv5_3',
19 | 'relu5_3', 'conv5_4', 'relu5_4'
20 | )
21 | LAPLACIAN_LAYERS = ( 'pool_lap1', 'lap1', 'pool_lap2', 'lap2', 'pool_lap3', 'lap3' )
22 |
23 | def load_net(data_path):
24 | data = scipy.io.loadmat(data_path)
25 | mean = data['normalization'][0][0][0]
26 | mean_pixel = np.mean(mean, axis=(0, 1))
27 | weights = data['layers'][0]
28 | return weights, mean_pixel
29 |
30 | def net_preloaded(weights, input_image, pooling):
31 | net = {}
32 | current = input_image
33 | for i, name in enumerate(VGG19_LAYERS):
34 | kind = name[:4]
35 | if kind == 'conv':
36 | kernels, bias = weights[i][0][0][0][0]
37 | # matconvnet: weights are [width, height, in_channels, out_channels]
38 | # tensorflow: weights are [height, width, in_channels, out_channels]
39 | kernels = np.transpose(kernels, (1, 0, 2, 3))
40 | bias = bias.reshape(-1)
41 | current = _conv_layer(current, kernels, bias)
42 | elif kind == 'relu':
43 | current = tf.nn.relu(current)
44 | elif kind == 'pool':
45 | current = _pool_layer(current, pooling)
46 | net[name] = current
47 |
48 | laplacian = np.array( [ [0,-1,0], [-1,4,-1], [0,-1,0] ], dtype=np.float32 )
49 | lapW = np.zeros( (3, 3, 3, 1), dtype=np.float32 )
50 | for t in range(3):
51 | lapW[:,:,t,0] = laplacian
52 |
53 | for i in range(1,4):
54 | net['pool_lap%d'%i] = _pool_layer( input_image, 'avg', 2**i )
55 | #net['lap%d'%i] = _conv_layer(net['pool_lap%d'%i], lapW, [0.0])
56 | net['lap%d'%i] = _lap_layer(net['pool_lap%d'%i])
57 | assert len(net) == len(VGG19_LAYERS) + len(LAPLACIAN_LAYERS)
58 | return net
59 |
60 | def _conv_layer(input, weights, bias):
61 | conv = tf.nn.conv2d(input, tf.constant(weights), strides=(1, 1, 1, 1),
62 | padding='SAME')
63 | return tf.nn.bias_add(conv, bias)
64 |
65 |
66 | def _pool_layer(input, pooling, poolsize=2):
67 | ksize = (1, poolsize, poolsize, 1)
68 | if pooling == 'avg':
69 | return tf.nn.avg_pool(input, ksize, strides=(1, poolsize, poolsize, 1),
70 | padding='SAME')
71 | else:
72 | return tf.nn.max_pool(input, ksize, strides=(1, poolsize, poolsize, 1),
73 | padding='SAME')
74 |
75 | def _lap_layer(input):
76 | laplacian = np.array( [ [0,-1,0], [-1,4,-1], [0,-1,0] ], dtype=np.float32 )
77 | lapW = np.zeros( (3, 3, 1, 1), dtype=np.float32 )
78 | lapW[:,:,0,0] = laplacian
79 | color_outs = []
80 | for i in range(3):
81 | color = input[:,:,:,i]
82 | color4d = tf.expand_dims(color, -1)
83 | color_out = _conv_layer(color4d, lapW, [0.0])
84 | color_outs.append(color_out)
85 | output = tf.concat(color_outs, axis=-1)
86 | output = tf.abs(output)
87 | sum_output = tf.reduce_sum(output, reduction_indices=[3], keep_dims=False)
88 | #cut_cond = tf.less( max_output, tf.ones(tf.shape(max_output)) * thres )
89 | #cut_output = tf.where( cut_cond, tf.zeros(tf.shape(max_output)), max_output )
90 | return sum_output
91 |
92 |
93 | def preprocess(image, mean_pixel):
94 | return image - mean_pixel
95 |
96 |
97 | def unprocess(image, mean_pixel):
98 | return image + mean_pixel
99 |
--------------------------------------------------------------------------------