├── .gitignore ├── LICENSE ├── README.md ├── assets ├── cj_mix.png ├── cn2kr.png ├── compare2.png ├── compare3.png ├── cover.png ├── cursive.png ├── demo.png ├── failure.png ├── intro.gif ├── ko_wiki.gif ├── kr_demo.png ├── kr_mix.png ├── kr_mix_v2.png ├── mingchao4.png ├── network.png ├── network.svg ├── network_v2.png ├── poem.gif ├── random.png ├── reddit_bonus_humor_easter_egg.gif ├── sample_per_font.png └── transition.png ├── charset └── cjk.json ├── export.py ├── font2img.py ├── infer.py ├── model ├── __init__.py ├── dataset.py ├── ops.py ├── unet.py └── utils.py ├── package.py └── train.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | datasets/ 3 | experiments/ 4 | .DS_Store 5 | .idea/ 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # zi2zi: Master Chinese Calligraphy with Conditional Adversarial Networks 2 | 3 |

4 | animation 5 |

6 | 7 | ## Introduction 8 | Learning eastern asian language typefaces with GAN. zi2zi(字到字, meaning from character to character) is an application and extension of the recent popular [pix2pix](https://github.com/phillipi/pix2pix) model to Chinese characters. 9 | 10 | Details could be found in this [**blog post**](https://kaonashi-tyc.github.io/2017/04/06/zi2zi.html). 11 | 12 | ## Network Structure 13 | ### Original Model 14 | ![alt network](assets/network.png) 15 | 16 | The network structure is based off pix2pix with the addition of category embedding and two other losses, category loss and constant loss, from [AC-GAN](https://arxiv.org/abs/1610.09585) and [DTN](https://arxiv.org/abs/1611.02200) respectively. 17 | 18 | ### Updated Model with Label Shuffling 19 | 20 | ![alt network](assets/network_v2.png) 21 | 22 | After sufficient training, **d_loss** will drop to near zero, and the model's performance plateaued. **Label Shuffling** mitigate this problem by presenting new challenges to the model. 23 | 24 | Specifically, within a given minibatch, for the same set of source characters, we generate two sets of target characters: one with correct embedding labels, the other with the shuffled labels. The shuffled set likely will not have the corresponding target images to compute **L1\_Loss**, but can be used as a good source for all other losses, forcing the model to further generalize beyond the limited set of provided examples. Empirically, label shuffling improves the model's generalization on unseen data with better details, and decrease the required number of characters. 25 | 26 | You can enable label shuffling by setting **flip_labels=1** option in **train.py** script. It is recommended that you enable this after **d_loss** flatlines around zero, for further tuning. 27 | 28 | ## Gallery 29 | ### Compare with Ground Truth 30 | 31 |

32 | compare 33 |

34 | 35 | ### Brush Writing Fonts 36 |

37 | brush 38 |

39 | 40 | ### Cursive Script (Requested by SNS audience) 41 |

42 | cursive 43 |

44 | 45 | 46 | ### Mingchao Style (宋体/明朝体) 47 |

48 | gaussian 49 |

50 | 51 | ### Korean 52 |

53 | korean 54 |

55 | 56 | ### Interpolation 57 |

58 | animation 59 |

60 | 61 | ### Animation 62 |

63 | animation 64 | animation 65 |

66 | 67 |

68 | easter egg 69 |

70 | 71 | 72 | ## How to Use 73 | ### Step Zero 74 | Download tons of fonts as you please 75 | ### Requirement 76 | * Python 2.7 77 | * CUDA 78 | * cudnn 79 | * Tensorflow >= 1.0.1 80 | * Pillow(PIL) 81 | * numpy >= 1.12.1 82 | * scipy >= 0.18.1 83 | * imageio 84 | 85 | ### Preprocess 86 | To avoid IO bottleneck, preprocessing is necessary to pickle your data into binary and persist in memory during training. 87 | 88 | First run the below command to get the font images: 89 | 90 | ```sh 91 | python font2img.py --src_font=src.ttf 92 | --dst_font=tgt.otf 93 | --charset=CN 94 | --sample_count=1000 95 | --sample_dir=dir 96 | --label=0 97 | --filter=1 98 | --shuffle=1 99 | ``` 100 | Four default charsets are offered: CN, CN_T(traditional), JP, KR. You can also point it to a one line file, it will generate the images of the characters in it. Note, **filter** option is highly recommended, it will pre sample some characters and filter all the images that have the same hash, usually indicating that character is missing. **label** indicating index in the category embeddings that this font associated with, default to 0. 101 | 102 | After obtaining all images, run **package.py** to pickle the images and their corresponding labels into binary format: 103 | 104 | ```sh 105 | python package.py --dir=image_directories 106 | --save_dir=binary_save_directory 107 | --split_ratio=[0,1] 108 | ``` 109 | 110 | After running this, you will find two objects **train.obj** and **val.obj** under the save_dir for training and validation, respectively. 111 | 112 | ### Experiment Layout 113 | ```sh 114 | experiment/ 115 | └── data 116 | ├── train.obj 117 | └── val.obj 118 | ``` 119 | Create a **experiment** directory under the root of the project, and a data directory within it to place the two binaries. Assuming a directory layout enforce bettet data isolation, especially if you have multiple experiments running. 120 | ### Train 121 | To start training run the following command 122 | 123 | ```sh 124 | python train.py --experiment_dir=experiment 125 | --experiment_id=0 126 | --batch_size=16 127 | --lr=0.001 128 | --epoch=40 129 | --sample_steps=50 130 | --schedule=20 131 | --L1_penalty=100 132 | --Lconst_penalty=15 133 | ``` 134 | **schedule** here means in between how many epochs, the learning rate will decay by half. The train command will create **sample,logs,checkpoint** directory under **experiment_dir** if non-existed, where you can check and manage the progress of your training. 135 | 136 | ### Infer and Interpolate 137 | After training is done, run the below command to infer test data: 138 | 139 | ```sh 140 | python infer.py --model_dir=checkpoint_dir/ 141 | --batch_size=16 142 | --source_obj=binary_obj_path 143 | --embedding_ids=label[s] of the font, separate by comma 144 | --save_dir=save_dir/ 145 | ``` 146 | 147 | Also you can do interpolation with this command: 148 | 149 | ```sh 150 | python infer.py --model_dir= checkpoint_dir/ 151 | --batch_size=10 152 | --source_obj=obj_path 153 | --embedding_ids=label[s] of the font, separate by comma 154 | --save_dir=frames/ 155 | --output_gif=gif_path 156 | --interpolate=1 157 | --steps=10 158 | --uroboros=1 159 | ``` 160 | 161 | It will run through all the pairs of fonts specified in embedding_ids and interpolate the number of steps as specified. 162 | 163 | ### Pretrained Model 164 | Pretained model can be downloaded [here](https://drive.google.com/open?id=0Bz6mX0EGe2ZuNEFSNWpTQkxPM2c) which is trained with 27 fonts, only generator is saved to reduce the model size. You can use encoder in the this pretrained model to accelerate the training process. 165 | ## Acknowledgements 166 | Code derived and rehashed from: 167 | 168 | * [pix2pix-tensorflow](https://github.com/yenchenlin/pix2pix-tensorflow) by [yenchenlin](https://github.com/yenchenlin) 169 | * [Domain Transfer Network](https://github.com/yunjey/domain-transfer-network) by [yunjey](https://github.com/yunjey) 170 | * [ac-gan](https://github.com/buriburisuri/ac-gan) by [buriburisuri](https://github.com/buriburisuri) 171 | * [dc-gan](https://github.com/carpedm20/DCGAN-tensorflow) by [carpedm20](https://github.com/carpedm20) 172 | * [origianl pix2pix torch code](https://github.com/phillipi/pix2pix) by [phillipi](https://github.com/phillipi) 173 | 174 | ## License 175 | Apache 2.0 176 | 177 | -------------------------------------------------------------------------------- /assets/cj_mix.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaonashi-tyc/zi2zi/546025f59690b7c7c85de0146aba6f24f26f6b9d/assets/cj_mix.png -------------------------------------------------------------------------------- /assets/cn2kr.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaonashi-tyc/zi2zi/546025f59690b7c7c85de0146aba6f24f26f6b9d/assets/cn2kr.png -------------------------------------------------------------------------------- /assets/compare2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaonashi-tyc/zi2zi/546025f59690b7c7c85de0146aba6f24f26f6b9d/assets/compare2.png -------------------------------------------------------------------------------- /assets/compare3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaonashi-tyc/zi2zi/546025f59690b7c7c85de0146aba6f24f26f6b9d/assets/compare3.png -------------------------------------------------------------------------------- /assets/cover.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaonashi-tyc/zi2zi/546025f59690b7c7c85de0146aba6f24f26f6b9d/assets/cover.png -------------------------------------------------------------------------------- /assets/cursive.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaonashi-tyc/zi2zi/546025f59690b7c7c85de0146aba6f24f26f6b9d/assets/cursive.png -------------------------------------------------------------------------------- /assets/demo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaonashi-tyc/zi2zi/546025f59690b7c7c85de0146aba6f24f26f6b9d/assets/demo.png -------------------------------------------------------------------------------- /assets/failure.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaonashi-tyc/zi2zi/546025f59690b7c7c85de0146aba6f24f26f6b9d/assets/failure.png -------------------------------------------------------------------------------- /assets/intro.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaonashi-tyc/zi2zi/546025f59690b7c7c85de0146aba6f24f26f6b9d/assets/intro.gif -------------------------------------------------------------------------------- /assets/ko_wiki.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaonashi-tyc/zi2zi/546025f59690b7c7c85de0146aba6f24f26f6b9d/assets/ko_wiki.gif -------------------------------------------------------------------------------- /assets/kr_demo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaonashi-tyc/zi2zi/546025f59690b7c7c85de0146aba6f24f26f6b9d/assets/kr_demo.png -------------------------------------------------------------------------------- /assets/kr_mix.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaonashi-tyc/zi2zi/546025f59690b7c7c85de0146aba6f24f26f6b9d/assets/kr_mix.png -------------------------------------------------------------------------------- /assets/kr_mix_v2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaonashi-tyc/zi2zi/546025f59690b7c7c85de0146aba6f24f26f6b9d/assets/kr_mix_v2.png -------------------------------------------------------------------------------- /assets/mingchao4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaonashi-tyc/zi2zi/546025f59690b7c7c85de0146aba6f24f26f6b9d/assets/mingchao4.png -------------------------------------------------------------------------------- /assets/network.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaonashi-tyc/zi2zi/546025f59690b7c7c85de0146aba6f24f26f6b9d/assets/network.png -------------------------------------------------------------------------------- /assets/network.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /assets/network_v2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaonashi-tyc/zi2zi/546025f59690b7c7c85de0146aba6f24f26f6b9d/assets/network_v2.png -------------------------------------------------------------------------------- /assets/poem.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaonashi-tyc/zi2zi/546025f59690b7c7c85de0146aba6f24f26f6b9d/assets/poem.gif -------------------------------------------------------------------------------- /assets/random.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaonashi-tyc/zi2zi/546025f59690b7c7c85de0146aba6f24f26f6b9d/assets/random.png -------------------------------------------------------------------------------- /assets/reddit_bonus_humor_easter_egg.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaonashi-tyc/zi2zi/546025f59690b7c7c85de0146aba6f24f26f6b9d/assets/reddit_bonus_humor_easter_egg.gif -------------------------------------------------------------------------------- /assets/sample_per_font.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaonashi-tyc/zi2zi/546025f59690b7c7c85de0146aba6f24f26f6b9d/assets/sample_per_font.png -------------------------------------------------------------------------------- /assets/transition.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaonashi-tyc/zi2zi/546025f59690b7c7c85de0146aba6f24f26f6b9d/assets/transition.png -------------------------------------------------------------------------------- /export.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import print_function 3 | from __future__ import absolute_import 4 | 5 | import tensorflow as tf 6 | import argparse 7 | from model.unet import UNet 8 | 9 | parser = argparse.ArgumentParser(description='Export generator weights from the checkpoint file') 10 | parser.add_argument('--model_dir', dest='model_dir', required=True, 11 | help='directory that saves the model checkpoints') 12 | parser.add_argument('--batch_size', dest='batch_size', type=int, default=16, help='number of examples in batch') 13 | parser.add_argument('--inst_norm', dest='inst_norm', type=bool, default=False, 14 | help='use conditional instance normalization in your model') 15 | parser.add_argument('--save_dir', default='save_dir', type=str, help='path to save inferred images') 16 | args = parser.parse_args() 17 | 18 | 19 | def main(_): 20 | config = tf.ConfigProto() 21 | config.gpu_options.allow_growth = True 22 | 23 | with tf.Session(config=config) as sess: 24 | model = UNet(batch_size=args.batch_size) 25 | model.register_session(sess) 26 | model.build_model(is_training=False, inst_norm=args.inst_norm) 27 | model.export_generator(save_dir=args.save_dir, model_dir=args.model_dir) 28 | 29 | 30 | if __name__ == '__main__': 31 | tf.app.run() 32 | -------------------------------------------------------------------------------- /font2img.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import print_function 3 | from __future__ import absolute_import 4 | 5 | import argparse 6 | import sys 7 | import numpy as np 8 | import os 9 | from PIL import Image 10 | from PIL import ImageDraw 11 | from PIL import ImageFont 12 | import json 13 | import collections 14 | 15 | reload(sys) 16 | sys.setdefaultencoding("utf-8") 17 | 18 | CN_CHARSET = None 19 | CN_T_CHARSET = None 20 | JP_CHARSET = None 21 | KR_CHARSET = None 22 | 23 | DEFAULT_CHARSET = "./charset/cjk.json" 24 | 25 | 26 | def load_global_charset(): 27 | global CN_CHARSET, JP_CHARSET, KR_CHARSET, CN_T_CHARSET 28 | cjk = json.load(open(DEFAULT_CHARSET)) 29 | CN_CHARSET = cjk["gbk"] 30 | JP_CHARSET = cjk["jp"] 31 | KR_CHARSET = cjk["kr"] 32 | CN_T_CHARSET = cjk["gb2312_t"] 33 | 34 | 35 | def draw_single_char(ch, font, canvas_size, x_offset, y_offset): 36 | img = Image.new("RGB", (canvas_size, canvas_size), (255, 255, 255)) 37 | draw = ImageDraw.Draw(img) 38 | draw.text((x_offset, y_offset), ch, (0, 0, 0), font=font) 39 | return img 40 | 41 | 42 | def draw_example(ch, src_font, dst_font, canvas_size, x_offset, y_offset, filter_hashes): 43 | dst_img = draw_single_char(ch, dst_font, canvas_size, x_offset, y_offset) 44 | # check the filter example in the hashes or not 45 | dst_hash = hash(dst_img.tobytes()) 46 | if dst_hash in filter_hashes: 47 | return None 48 | src_img = draw_single_char(ch, src_font, canvas_size, x_offset, y_offset) 49 | example_img = Image.new("RGB", (canvas_size * 2, canvas_size), (255, 255, 255)) 50 | example_img.paste(dst_img, (0, 0)) 51 | example_img.paste(src_img, (canvas_size, 0)) 52 | return example_img 53 | 54 | 55 | def filter_recurring_hash(charset, font, canvas_size, x_offset, y_offset): 56 | """ Some characters are missing in a given font, filter them 57 | by checking the recurring hashes 58 | """ 59 | _charset = charset[:] 60 | np.random.shuffle(_charset) 61 | sample = _charset[:2000] 62 | hash_count = collections.defaultdict(int) 63 | for c in sample: 64 | img = draw_single_char(c, font, canvas_size, x_offset, y_offset) 65 | hash_count[hash(img.tobytes())] += 1 66 | recurring_hashes = filter(lambda d: d[1] > 2, hash_count.items()) 67 | return [rh[0] for rh in recurring_hashes] 68 | 69 | 70 | def font2img(src, dst, charset, char_size, canvas_size, 71 | x_offset, y_offset, sample_count, sample_dir, label=0, filter_by_hash=True): 72 | src_font = ImageFont.truetype(src, size=char_size) 73 | dst_font = ImageFont.truetype(dst, size=char_size) 74 | 75 | filter_hashes = set() 76 | if filter_by_hash: 77 | filter_hashes = set(filter_recurring_hash(charset, dst_font, canvas_size, x_offset, y_offset)) 78 | print("filter hashes -> %s" % (",".join([str(h) for h in filter_hashes]))) 79 | 80 | count = 0 81 | 82 | for c in charset: 83 | if count == sample_count: 84 | break 85 | e = draw_example(c, src_font, dst_font, canvas_size, x_offset, y_offset, filter_hashes) 86 | if e: 87 | e.save(os.path.join(sample_dir, "%d_%04d.jpg" % (label, count))) 88 | count += 1 89 | if count % 100 == 0: 90 | print("processed %d chars" % count) 91 | 92 | 93 | load_global_charset() 94 | parser = argparse.ArgumentParser(description='Convert font to images') 95 | parser.add_argument('--src_font', dest='src_font', required=True, help='path of the source font') 96 | parser.add_argument('--dst_font', dest='dst_font', required=True, help='path of the target font') 97 | parser.add_argument('--filter', dest='filter', type=int, default=0, help='filter recurring characters') 98 | parser.add_argument('--charset', dest='charset', type=str, default='CN', 99 | help='charset, can be either: CN, JP, KR or a one line file') 100 | parser.add_argument('--shuffle', dest='shuffle', type=int, default=0, help='shuffle a charset before processings') 101 | parser.add_argument('--char_size', dest='char_size', type=int, default=150, help='character size') 102 | parser.add_argument('--canvas_size', dest='canvas_size', type=int, default=256, help='canvas size') 103 | parser.add_argument('--x_offset', dest='x_offset', type=int, default=20, help='x offset') 104 | parser.add_argument('--y_offset', dest='y_offset', type=int, default=20, help='y_offset') 105 | parser.add_argument('--sample_count', dest='sample_count', type=int, default=1000, help='number of characters to draw') 106 | parser.add_argument('--sample_dir', dest='sample_dir', help='directory to save examples') 107 | parser.add_argument('--label', dest='label', type=int, default=0, help='label as the prefix of examples') 108 | 109 | args = parser.parse_args() 110 | 111 | if __name__ == "__main__": 112 | if args.charset in ['CN', 'JP', 'KR', 'CN_T']: 113 | charset = locals().get("%s_CHARSET" % args.charset) 114 | else: 115 | charset = [c for c in open(args.charset).readline()[:-1].decode("utf-8")] 116 | if args.shuffle: 117 | np.random.shuffle(charset) 118 | font2img(args.src_font, args.dst_font, charset, args.char_size, 119 | args.canvas_size, args.x_offset, args.y_offset, 120 | args.sample_count, args.sample_dir, args.label, args.filter) 121 | -------------------------------------------------------------------------------- /infer.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import print_function 3 | from __future__ import absolute_import 4 | 5 | import tensorflow as tf 6 | import os 7 | import argparse 8 | from model.unet import UNet 9 | from model.utils import compile_frames_to_gif 10 | 11 | """ 12 | People are made to have fun and be 中二 sometimes 13 | --Bored Yan LeCun 14 | """ 15 | 16 | parser = argparse.ArgumentParser(description='Inference for unseen data') 17 | parser.add_argument('--model_dir', dest='model_dir', required=True, 18 | help='directory that saves the model checkpoints') 19 | parser.add_argument('--batch_size', dest='batch_size', type=int, default=16, help='number of examples in batch') 20 | parser.add_argument('--source_obj', dest='source_obj', type=str, required=True, help='the source images for inference') 21 | parser.add_argument('--embedding_ids', default='embedding_ids', type=str, help='embeddings involved') 22 | parser.add_argument('--save_dir', default='save_dir', type=str, help='path to save inferred images') 23 | parser.add_argument('--inst_norm', dest='inst_norm', type=int, default=0, 24 | help='use conditional instance normalization in your model') 25 | parser.add_argument('--interpolate', dest='interpolate', type=int, default=0, 26 | help='interpolate between different embedding vectors') 27 | parser.add_argument('--steps', dest='steps', type=int, default=10, help='interpolation steps in between vectors') 28 | parser.add_argument('--output_gif', dest='output_gif', type=str, default=None, help='output name transition gif') 29 | parser.add_argument('--uroboros', dest='uroboros', type=int, default=0, 30 | help='Shōnen yo, you have stepped into uncharted territory') 31 | args = parser.parse_args() 32 | 33 | 34 | def main(_): 35 | config = tf.ConfigProto() 36 | config.gpu_options.allow_growth = True 37 | 38 | with tf.Session(config=config) as sess: 39 | model = UNet(batch_size=args.batch_size) 40 | model.register_session(sess) 41 | model.build_model(is_training=False, inst_norm=args.inst_norm) 42 | embedding_ids = [int(i) for i in args.embedding_ids.split(",")] 43 | if not args.interpolate: 44 | if len(embedding_ids) == 1: 45 | embedding_ids = embedding_ids[0] 46 | model.infer(model_dir=args.model_dir, source_obj=args.source_obj, embedding_ids=embedding_ids, 47 | save_dir=args.save_dir) 48 | else: 49 | if len(embedding_ids) < 2: 50 | raise Exception("no need to interpolate yourself unless you are a narcissist") 51 | chains = embedding_ids[:] 52 | if args.uroboros: 53 | chains.append(chains[0]) 54 | pairs = list() 55 | for i in range(len(chains) - 1): 56 | pairs.append((chains[i], chains[i + 1])) 57 | for s, e in pairs: 58 | model.interpolate(model_dir=args.model_dir, source_obj=args.source_obj, between=[s, e], 59 | save_dir=args.save_dir, steps=args.steps) 60 | if args.output_gif: 61 | gif_path = os.path.join(args.save_dir, args.output_gif) 62 | compile_frames_to_gif(args.save_dir, gif_path) 63 | print("gif saved at %s" % gif_path) 64 | 65 | 66 | if __name__ == '__main__': 67 | tf.app.run() 68 | -------------------------------------------------------------------------------- /model/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import print_function 3 | from __future__ import absolute_import 4 | -------------------------------------------------------------------------------- /model/dataset.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import print_function 3 | from __future__ import absolute_import 4 | import cPickle as pickle 5 | import numpy as np 6 | import random 7 | import os 8 | from .utils import pad_seq, bytes_to_file, \ 9 | read_split_image, shift_and_resize_image, normalize_image 10 | 11 | 12 | class PickledImageProvider(object): 13 | def __init__(self, obj_path): 14 | self.obj_path = obj_path 15 | self.examples = self.load_pickled_examples() 16 | 17 | def load_pickled_examples(self): 18 | with open(self.obj_path, "rb") as of: 19 | examples = list() 20 | while True: 21 | try: 22 | e = pickle.load(of) 23 | examples.append(e) 24 | if len(examples) % 1000 == 0: 25 | print("processed %d examples" % len(examples)) 26 | except EOFError: 27 | break 28 | except Exception: 29 | pass 30 | print("unpickled total %d examples" % len(examples)) 31 | return examples 32 | 33 | 34 | def get_batch_iter(examples, batch_size, augment): 35 | # the transpose ops requires deterministic 36 | # batch size, thus comes the padding 37 | padded = pad_seq(examples, batch_size) 38 | 39 | def process(img): 40 | img = bytes_to_file(img) 41 | try: 42 | img_A, img_B = read_split_image(img) 43 | if augment: 44 | # augment the image by: 45 | # 1) enlarge the image 46 | # 2) random crop the image back to its original size 47 | # NOTE: image A and B needs to be in sync as how much 48 | # to be shifted 49 | w, h, _ = img_A.shape 50 | multiplier = random.uniform(1.00, 1.20) 51 | # add an eps to prevent cropping issue 52 | nw = int(multiplier * w) + 1 53 | nh = int(multiplier * h) + 1 54 | shift_x = int(np.ceil(np.random.uniform(0.01, nw - w))) 55 | shift_y = int(np.ceil(np.random.uniform(0.01, nh - h))) 56 | img_A = shift_and_resize_image(img_A, shift_x, shift_y, nw, nh) 57 | img_B = shift_and_resize_image(img_B, shift_x, shift_y, nw, nh) 58 | img_A = normalize_image(img_A) 59 | img_B = normalize_image(img_B) 60 | return np.concatenate([img_A, img_B], axis=2) 61 | finally: 62 | img.close() 63 | 64 | def batch_iter(): 65 | for i in range(0, len(padded), batch_size): 66 | batch = padded[i: i + batch_size] 67 | labels = [e[0] for e in batch] 68 | processed = [process(e[1]) for e in batch] 69 | # stack into tensor 70 | yield labels, np.array(processed).astype(np.float32) 71 | 72 | return batch_iter() 73 | 74 | 75 | class TrainDataProvider(object): 76 | def __init__(self, data_dir, train_name="train.obj", val_name="val.obj", filter_by=None): 77 | self.data_dir = data_dir 78 | self.filter_by = filter_by 79 | self.train_path = os.path.join(self.data_dir, train_name) 80 | self.val_path = os.path.join(self.data_dir, val_name) 81 | self.train = PickledImageProvider(self.train_path) 82 | self.val = PickledImageProvider(self.val_path) 83 | if self.filter_by: 84 | print("filter by label ->", filter_by) 85 | self.train.examples = filter(lambda e: e[0] in self.filter_by, self.train.examples) 86 | self.val.examples = filter(lambda e: e[0] in self.filter_by, self.val.examples) 87 | print("train examples -> %d, val examples -> %d" % (len(self.train.examples), len(self.val.examples))) 88 | 89 | def get_train_iter(self, batch_size, shuffle=True): 90 | training_examples = self.train.examples[:] 91 | if shuffle: 92 | np.random.shuffle(training_examples) 93 | return get_batch_iter(training_examples, batch_size, augment=True) 94 | 95 | def get_val_iter(self, batch_size, shuffle=True): 96 | """ 97 | Validation iterator runs forever 98 | """ 99 | val_examples = self.val.examples[:] 100 | if shuffle: 101 | np.random.shuffle(val_examples) 102 | while True: 103 | val_batch_iter = get_batch_iter(val_examples, batch_size, augment=False) 104 | for labels, examples in val_batch_iter: 105 | yield labels, examples 106 | 107 | def compute_total_batch_num(self, batch_size): 108 | """Total padded batch num""" 109 | return int(np.ceil(len(self.train.examples) / float(batch_size))) 110 | 111 | def get_all_labels(self): 112 | """Get all training labels""" 113 | return list({e[0] for e in self.train.examples}) 114 | 115 | def get_train_val_path(self): 116 | return self.train_path, self.val_path 117 | 118 | 119 | class InjectDataProvider(object): 120 | def __init__(self, obj_path): 121 | self.data = PickledImageProvider(obj_path) 122 | print("examples -> %d" % len(self.data.examples)) 123 | 124 | def get_single_embedding_iter(self, batch_size, embedding_id): 125 | examples = self.data.examples[:] 126 | batch_iter = get_batch_iter(examples, batch_size, augment=False) 127 | for _, images in batch_iter: 128 | # inject specific embedding style here 129 | labels = [embedding_id] * batch_size 130 | yield labels, images 131 | 132 | def get_random_embedding_iter(self, batch_size, embedding_ids): 133 | examples = self.data.examples[:] 134 | batch_iter = get_batch_iter(examples, batch_size, augment=False) 135 | for _, images in batch_iter: 136 | # inject specific embedding style here 137 | labels = [random.choice(embedding_ids) for i in range(batch_size)] 138 | yield labels, images 139 | 140 | 141 | class NeverEndingLoopingProvider(InjectDataProvider): 142 | def __init__(self, obj_path): 143 | super(NeverEndingLoopingProvider, self).__init__(obj_path) 144 | 145 | def get_random_embedding_iter(self, batch_size, embedding_ids): 146 | while True: 147 | # np.random.shuffle(self.data.examples) 148 | rand_iter = super(NeverEndingLoopingProvider, self) \ 149 | .get_random_embedding_iter(batch_size, embedding_ids) 150 | for labels, images in rand_iter: 151 | yield labels, images 152 | -------------------------------------------------------------------------------- /model/ops.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import print_function 3 | from __future__ import absolute_import 4 | import tensorflow as tf 5 | 6 | 7 | def batch_norm(x, is_training, epsilon=1e-5, decay=0.9, scope="batch_norm"): 8 | return tf.contrib.layers.batch_norm(x, decay=decay, updates_collections=None, epsilon=epsilon, 9 | scale=True, is_training=is_training, scope=scope) 10 | 11 | 12 | def conv2d(x, output_filters, kh=5, kw=5, sh=2, sw=2, stddev=0.02, scope="conv2d"): 13 | with tf.variable_scope(scope): 14 | shape = x.get_shape().as_list() 15 | W = tf.get_variable('W', [kh, kw, shape[-1], output_filters], 16 | initializer=tf.truncated_normal_initializer(stddev=stddev)) 17 | Wconv = tf.nn.conv2d(x, W, strides=[1, sh, sw, 1], padding='SAME') 18 | 19 | biases = tf.get_variable('b', [output_filters], initializer=tf.constant_initializer(0.0)) 20 | Wconv_plus_b = tf.reshape(tf.nn.bias_add(Wconv, biases), Wconv.get_shape()) 21 | 22 | return Wconv_plus_b 23 | 24 | 25 | def deconv2d(x, output_shape, kh=5, kw=5, sh=2, sw=2, stddev=0.02, scope="deconv2d"): 26 | with tf.variable_scope(scope): 27 | # filter : [height, width, output_channels, in_channels] 28 | input_shape = x.get_shape().as_list() 29 | W = tf.get_variable('W', [kh, kw, output_shape[-1], input_shape[-1]], 30 | initializer=tf.random_normal_initializer(stddev=stddev)) 31 | 32 | deconv = tf.nn.conv2d_transpose(x, W, output_shape=output_shape, 33 | strides=[1, sh, sw, 1]) 34 | 35 | biases = tf.get_variable('b', [output_shape[-1]], initializer=tf.constant_initializer(0.0)) 36 | deconv_plus_b = tf.reshape(tf.nn.bias_add(deconv, biases), deconv.get_shape()) 37 | 38 | return deconv_plus_b 39 | 40 | 41 | def lrelu(x, leak=0.2): 42 | return tf.maximum(x, leak * x) 43 | 44 | 45 | def fc(x, output_size, stddev=0.02, scope="fc"): 46 | with tf.variable_scope(scope): 47 | shape = x.get_shape().as_list() 48 | W = tf.get_variable("W", [shape[1], output_size], tf.float32, 49 | tf.random_normal_initializer(stddev=stddev)) 50 | b = tf.get_variable("b", [output_size], 51 | initializer=tf.constant_initializer(0.0)) 52 | return tf.matmul(x, W) + b 53 | 54 | 55 | def init_embedding(size, dimension, stddev=0.01, scope="embedding"): 56 | with tf.variable_scope(scope): 57 | return tf.get_variable("E", [size, 1, 1, dimension], tf.float32, 58 | tf.random_normal_initializer(stddev=stddev)) 59 | 60 | 61 | def conditional_instance_norm(x, ids, labels_num, mixed=False, scope="conditional_instance_norm"): 62 | with tf.variable_scope(scope): 63 | shape = x.get_shape().as_list() 64 | batch_size, output_filters = shape[0], shape[-1] 65 | scale = tf.get_variable("scale", [labels_num, output_filters], tf.float32, tf.constant_initializer(1.0)) 66 | shift = tf.get_variable("shift", [labels_num, output_filters], tf.float32, tf.constant_initializer(0.0)) 67 | 68 | mu, sigma = tf.nn.moments(x, [1, 2], keep_dims=True) 69 | norm = (x - mu) / tf.sqrt(sigma + 1e-5) 70 | 71 | batch_scale = tf.reshape(tf.nn.embedding_lookup([scale], ids=ids), [batch_size, 1, 1, output_filters]) 72 | batch_shift = tf.reshape(tf.nn.embedding_lookup([shift], ids=ids), [batch_size, 1, 1, output_filters]) 73 | 74 | z = norm * batch_scale + batch_shift 75 | return z 76 | -------------------------------------------------------------------------------- /model/unet.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import print_function 3 | from __future__ import absolute_import 4 | 5 | import tensorflow as tf 6 | import numpy as np 7 | import scipy.misc as misc 8 | import os 9 | import time 10 | from collections import namedtuple 11 | from .ops import conv2d, deconv2d, lrelu, fc, batch_norm, init_embedding, conditional_instance_norm 12 | from .dataset import TrainDataProvider, InjectDataProvider, NeverEndingLoopingProvider 13 | from .utils import scale_back, merge, save_concat_images 14 | 15 | # Auxiliary wrapper classes 16 | # Used to save handles(important nodes in computation graph) for later evaluation 17 | LossHandle = namedtuple("LossHandle", ["d_loss", "g_loss", "const_loss", "l1_loss", 18 | "category_loss", "cheat_loss", "tv_loss"]) 19 | InputHandle = namedtuple("InputHandle", ["real_data", "embedding_ids", "no_target_data", "no_target_ids"]) 20 | EvalHandle = namedtuple("EvalHandle", ["encoder", "generator", "target", "source", "embedding"]) 21 | SummaryHandle = namedtuple("SummaryHandle", ["d_merged", "g_merged"]) 22 | 23 | 24 | class UNet(object): 25 | def __init__(self, experiment_dir=None, experiment_id=0, batch_size=16, input_width=256, output_width=256, 26 | generator_dim=64, discriminator_dim=64, L1_penalty=100, Lconst_penalty=15, Ltv_penalty=0.0, 27 | Lcategory_penalty=1.0, embedding_num=40, embedding_dim=128, input_filters=3, output_filters=3): 28 | self.experiment_dir = experiment_dir 29 | self.experiment_id = experiment_id 30 | self.batch_size = batch_size 31 | self.input_width = input_width 32 | self.output_width = output_width 33 | self.generator_dim = generator_dim 34 | self.discriminator_dim = discriminator_dim 35 | self.L1_penalty = L1_penalty 36 | self.Lconst_penalty = Lconst_penalty 37 | self.Ltv_penalty = Ltv_penalty 38 | self.Lcategory_penalty = Lcategory_penalty 39 | self.embedding_num = embedding_num 40 | self.embedding_dim = embedding_dim 41 | self.input_filters = input_filters 42 | self.output_filters = output_filters 43 | # init all the directories 44 | self.sess = None 45 | # experiment_dir is needed for training 46 | if experiment_dir: 47 | self.data_dir = os.path.join(self.experiment_dir, "data") 48 | self.checkpoint_dir = os.path.join(self.experiment_dir, "checkpoint") 49 | self.sample_dir = os.path.join(self.experiment_dir, "sample") 50 | self.log_dir = os.path.join(self.experiment_dir, "logs") 51 | 52 | if not os.path.exists(self.checkpoint_dir): 53 | os.makedirs(self.checkpoint_dir) 54 | print("create checkpoint directory") 55 | if not os.path.exists(self.log_dir): 56 | os.makedirs(self.log_dir) 57 | print("create log directory") 58 | if not os.path.exists(self.sample_dir): 59 | os.makedirs(self.sample_dir) 60 | print("create sample directory") 61 | 62 | def encoder(self, images, is_training, reuse=False): 63 | with tf.variable_scope("generator"): 64 | if reuse: 65 | tf.get_variable_scope().reuse_variables() 66 | 67 | encode_layers = dict() 68 | 69 | def encode_layer(x, output_filters, layer): 70 | act = lrelu(x) 71 | conv = conv2d(act, output_filters=output_filters, scope="g_e%d_conv" % layer) 72 | enc = batch_norm(conv, is_training, scope="g_e%d_bn" % layer) 73 | encode_layers["e%d" % layer] = enc 74 | return enc 75 | 76 | e1 = conv2d(images, self.generator_dim, scope="g_e1_conv") 77 | encode_layers["e1"] = e1 78 | e2 = encode_layer(e1, self.generator_dim * 2, 2) 79 | e3 = encode_layer(e2, self.generator_dim * 4, 3) 80 | e4 = encode_layer(e3, self.generator_dim * 8, 4) 81 | e5 = encode_layer(e4, self.generator_dim * 8, 5) 82 | e6 = encode_layer(e5, self.generator_dim * 8, 6) 83 | e7 = encode_layer(e6, self.generator_dim * 8, 7) 84 | e8 = encode_layer(e7, self.generator_dim * 8, 8) 85 | 86 | return e8, encode_layers 87 | 88 | def decoder(self, encoded, encoding_layers, ids, inst_norm, is_training, reuse=False): 89 | with tf.variable_scope("generator"): 90 | if reuse: 91 | tf.get_variable_scope().reuse_variables() 92 | 93 | s = self.output_width 94 | s2, s4, s8, s16, s32, s64, s128 = int(s / 2), int(s / 4), int(s / 8), int(s / 16), int(s / 32), int( 95 | s / 64), int(s / 128) 96 | 97 | def decode_layer(x, output_width, output_filters, layer, enc_layer, dropout=False, do_concat=True): 98 | dec = deconv2d(tf.nn.relu(x), [self.batch_size, output_width, 99 | output_width, output_filters], scope="g_d%d_deconv" % layer) 100 | if layer != 8: 101 | # IMPORTANT: normalization for last layer 102 | # Very important, otherwise GAN is unstable 103 | # Trying conditional instance normalization to 104 | # overcome the fact that batch normalization offers 105 | # different train/test statistics 106 | if inst_norm: 107 | dec = conditional_instance_norm(dec, ids, self.embedding_num, scope="g_d%d_inst_norm" % layer) 108 | else: 109 | dec = batch_norm(dec, is_training, scope="g_d%d_bn" % layer) 110 | if dropout: 111 | dec = tf.nn.dropout(dec, 0.5) 112 | if do_concat: 113 | dec = tf.concat([dec, enc_layer], 3) 114 | return dec 115 | 116 | d1 = decode_layer(encoded, s128, self.generator_dim * 8, layer=1, enc_layer=encoding_layers["e7"], 117 | dropout=True) 118 | d2 = decode_layer(d1, s64, self.generator_dim * 8, layer=2, enc_layer=encoding_layers["e6"], dropout=True) 119 | d3 = decode_layer(d2, s32, self.generator_dim * 8, layer=3, enc_layer=encoding_layers["e5"], dropout=True) 120 | d4 = decode_layer(d3, s16, self.generator_dim * 8, layer=4, enc_layer=encoding_layers["e4"]) 121 | d5 = decode_layer(d4, s8, self.generator_dim * 4, layer=5, enc_layer=encoding_layers["e3"]) 122 | d6 = decode_layer(d5, s4, self.generator_dim * 2, layer=6, enc_layer=encoding_layers["e2"]) 123 | d7 = decode_layer(d6, s2, self.generator_dim, layer=7, enc_layer=encoding_layers["e1"]) 124 | d8 = decode_layer(d7, s, self.output_filters, layer=8, enc_layer=None, do_concat=False) 125 | 126 | output = tf.nn.tanh(d8) # scale to (-1, 1) 127 | return output 128 | 129 | def generator(self, images, embeddings, embedding_ids, inst_norm, is_training, reuse=False): 130 | e8, enc_layers = self.encoder(images, is_training=is_training, reuse=reuse) 131 | local_embeddings = tf.nn.embedding_lookup(embeddings, ids=embedding_ids) 132 | local_embeddings = tf.reshape(local_embeddings, [self.batch_size, 1, 1, self.embedding_dim]) 133 | embedded = tf.concat([e8, local_embeddings], 3) 134 | output = self.decoder(embedded, enc_layers, embedding_ids, inst_norm, is_training=is_training, reuse=reuse) 135 | return output, e8 136 | 137 | def discriminator(self, image, is_training, reuse=False): 138 | with tf.variable_scope("discriminator"): 139 | if reuse: 140 | tf.get_variable_scope().reuse_variables() 141 | h0 = lrelu(conv2d(image, self.discriminator_dim, scope="d_h0_conv")) 142 | h1 = lrelu(batch_norm(conv2d(h0, self.discriminator_dim * 2, scope="d_h1_conv"), 143 | is_training, scope="d_bn_1")) 144 | h2 = lrelu(batch_norm(conv2d(h1, self.discriminator_dim * 4, scope="d_h2_conv"), 145 | is_training, scope="d_bn_2")) 146 | h3 = lrelu(batch_norm(conv2d(h2, self.discriminator_dim * 8, sh=1, sw=1, scope="d_h3_conv"), 147 | is_training, scope="d_bn_3")) 148 | # real or fake binary loss 149 | fc1 = fc(tf.reshape(h3, [self.batch_size, -1]), 1, scope="d_fc1") 150 | # category loss 151 | fc2 = fc(tf.reshape(h3, [self.batch_size, -1]), self.embedding_num, scope="d_fc2") 152 | 153 | return tf.nn.sigmoid(fc1), fc1, fc2 154 | 155 | def build_model(self, is_training=True, inst_norm=False, no_target_source=False): 156 | real_data = tf.placeholder(tf.float32, 157 | [self.batch_size, self.input_width, self.input_width, 158 | self.input_filters + self.output_filters], 159 | name='real_A_and_B_images') 160 | embedding_ids = tf.placeholder(tf.int64, shape=None, name="embedding_ids") 161 | no_target_data = tf.placeholder(tf.float32, 162 | [self.batch_size, self.input_width, self.input_width, 163 | self.input_filters + self.output_filters], 164 | name='no_target_A_and_B_images') 165 | no_target_ids = tf.placeholder(tf.int64, shape=None, name="no_target_embedding_ids") 166 | 167 | # target images 168 | real_B = real_data[:, :, :, :self.input_filters] 169 | # source images 170 | real_A = real_data[:, :, :, self.input_filters:self.input_filters + self.output_filters] 171 | 172 | embedding = init_embedding(self.embedding_num, self.embedding_dim) 173 | fake_B, encoded_real_A = self.generator(real_A, embedding, embedding_ids, is_training=is_training, 174 | inst_norm=inst_norm) 175 | real_AB = tf.concat([real_A, real_B], 3) 176 | fake_AB = tf.concat([real_A, fake_B], 3) 177 | 178 | # Note it is not possible to set reuse flag back to False 179 | # initialize all variables before setting reuse to True 180 | real_D, real_D_logits, real_category_logits = self.discriminator(real_AB, is_training=is_training, reuse=False) 181 | fake_D, fake_D_logits, fake_category_logits = self.discriminator(fake_AB, is_training=is_training, reuse=True) 182 | 183 | # encoding constant loss 184 | # this loss assume that generated imaged and real image 185 | # should reside in the same space and close to each other 186 | encoded_fake_B = self.encoder(fake_B, is_training, reuse=True)[0] 187 | const_loss = (tf.reduce_mean(tf.square(encoded_real_A - encoded_fake_B))) * self.Lconst_penalty 188 | 189 | # category loss 190 | true_labels = tf.reshape(tf.one_hot(indices=embedding_ids, depth=self.embedding_num), 191 | shape=[self.batch_size, self.embedding_num]) 192 | real_category_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=real_category_logits, 193 | labels=true_labels)) 194 | fake_category_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=fake_category_logits, 195 | labels=true_labels)) 196 | category_loss = self.Lcategory_penalty * (real_category_loss + fake_category_loss) 197 | 198 | # binary real/fake loss 199 | d_loss_real = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=real_D_logits, 200 | labels=tf.ones_like(real_D))) 201 | d_loss_fake = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=fake_D_logits, 202 | labels=tf.zeros_like(fake_D))) 203 | # L1 loss between real and generated images 204 | l1_loss = self.L1_penalty * tf.reduce_mean(tf.abs(fake_B - real_B)) 205 | # total variation loss 206 | width = self.output_width 207 | tv_loss = (tf.nn.l2_loss(fake_B[:, 1:, :, :] - fake_B[:, :width - 1, :, :]) / width 208 | + tf.nn.l2_loss(fake_B[:, :, 1:, :] - fake_B[:, :, :width - 1, :]) / width) * self.Ltv_penalty 209 | 210 | # maximize the chance generator fool the discriminator 211 | cheat_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=fake_D_logits, 212 | labels=tf.ones_like(fake_D))) 213 | 214 | d_loss = d_loss_real + d_loss_fake + category_loss / 2.0 215 | g_loss = cheat_loss + l1_loss + self.Lcategory_penalty * fake_category_loss + const_loss + tv_loss 216 | 217 | if no_target_source: 218 | # no_target source are examples that don't have the corresponding target images 219 | # however, except L1 loss, we can compute category loss, binary loss and constant losses with those examples 220 | # it is useful when discriminator get saturated and d_loss drops to near zero 221 | # those data could be used as additional source of losses to break the saturation 222 | no_target_A = no_target_data[:, :, :, self.input_filters:self.input_filters + self.output_filters] 223 | no_target_B, encoded_no_target_A = self.generator(no_target_A, embedding, no_target_ids, 224 | is_training=is_training, 225 | inst_norm=inst_norm, reuse=True) 226 | no_target_labels = tf.reshape(tf.one_hot(indices=no_target_ids, depth=self.embedding_num), 227 | shape=[self.batch_size, self.embedding_num]) 228 | no_target_AB = tf.concat([no_target_A, no_target_B], 3) 229 | no_target_D, no_target_D_logits, no_target_category_logits = self.discriminator(no_target_AB, 230 | is_training=is_training, 231 | reuse=True) 232 | encoded_no_target_B = self.encoder(no_target_B, is_training, reuse=True)[0] 233 | no_target_const_loss = tf.reduce_mean( 234 | tf.square(encoded_no_target_A - encoded_no_target_B)) * self.Lconst_penalty 235 | no_target_category_loss = tf.reduce_mean( 236 | tf.nn.sigmoid_cross_entropy_with_logits(logits=no_target_category_logits, 237 | labels=no_target_labels)) * self.Lcategory_penalty 238 | 239 | d_loss_no_target = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=no_target_D_logits, 240 | labels=tf.zeros_like( 241 | no_target_D))) 242 | cheat_loss += tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=no_target_D_logits, 243 | labels=tf.ones_like(no_target_D))) 244 | d_loss = d_loss_real + d_loss_fake + d_loss_no_target + (category_loss + no_target_category_loss) / 3.0 245 | g_loss = cheat_loss / 2.0 + l1_loss + \ 246 | (self.Lcategory_penalty * fake_category_loss + no_target_category_loss) / 2.0 + \ 247 | (const_loss + no_target_const_loss) / 2.0 + tv_loss 248 | 249 | d_loss_real_summary = tf.summary.scalar("d_loss_real", d_loss_real) 250 | d_loss_fake_summary = tf.summary.scalar("d_loss_fake", d_loss_fake) 251 | category_loss_summary = tf.summary.scalar("category_loss", category_loss) 252 | cheat_loss_summary = tf.summary.scalar("cheat_loss", cheat_loss) 253 | l1_loss_summary = tf.summary.scalar("l1_loss", l1_loss) 254 | fake_category_loss_summary = tf.summary.scalar("fake_category_loss", fake_category_loss) 255 | const_loss_summary = tf.summary.scalar("const_loss", const_loss) 256 | d_loss_summary = tf.summary.scalar("d_loss", d_loss) 257 | g_loss_summary = tf.summary.scalar("g_loss", g_loss) 258 | tv_loss_summary = tf.summary.scalar("tv_loss", tv_loss) 259 | 260 | d_merged_summary = tf.summary.merge([d_loss_real_summary, d_loss_fake_summary, 261 | category_loss_summary, d_loss_summary]) 262 | g_merged_summary = tf.summary.merge([cheat_loss_summary, l1_loss_summary, 263 | fake_category_loss_summary, 264 | const_loss_summary, 265 | g_loss_summary, tv_loss_summary]) 266 | 267 | # expose useful nodes in the graph as handles globally 268 | input_handle = InputHandle(real_data=real_data, 269 | embedding_ids=embedding_ids, 270 | no_target_data=no_target_data, 271 | no_target_ids=no_target_ids) 272 | 273 | loss_handle = LossHandle(d_loss=d_loss, 274 | g_loss=g_loss, 275 | const_loss=const_loss, 276 | l1_loss=l1_loss, 277 | category_loss=category_loss, 278 | cheat_loss=cheat_loss, 279 | tv_loss=tv_loss) 280 | 281 | eval_handle = EvalHandle(encoder=encoded_real_A, 282 | generator=fake_B, 283 | target=real_B, 284 | source=real_A, 285 | embedding=embedding) 286 | 287 | summary_handle = SummaryHandle(d_merged=d_merged_summary, 288 | g_merged=g_merged_summary) 289 | 290 | # those operations will be shared, so we need 291 | # to make them visible globally 292 | setattr(self, "input_handle", input_handle) 293 | setattr(self, "loss_handle", loss_handle) 294 | setattr(self, "eval_handle", eval_handle) 295 | setattr(self, "summary_handle", summary_handle) 296 | 297 | def register_session(self, sess): 298 | self.sess = sess 299 | 300 | def retrieve_trainable_vars(self, freeze_encoder=False): 301 | t_vars = tf.trainable_variables() 302 | 303 | d_vars = [var for var in t_vars if 'd_' in var.name] 304 | g_vars = [var for var in t_vars if 'g_' in var.name] 305 | 306 | if freeze_encoder: 307 | # exclude encoder weights 308 | print("freeze encoder weights") 309 | g_vars = [var for var in g_vars if not ("g_e" in var.name)] 310 | 311 | return g_vars, d_vars 312 | 313 | def retrieve_generator_vars(self): 314 | all_vars = tf.global_variables() 315 | generate_vars = [var for var in all_vars if 'embedding' in var.name or "g_" in var.name] 316 | return generate_vars 317 | 318 | def retrieve_handles(self): 319 | input_handle = getattr(self, "input_handle") 320 | loss_handle = getattr(self, "loss_handle") 321 | eval_handle = getattr(self, "eval_handle") 322 | summary_handle = getattr(self, "summary_handle") 323 | 324 | return input_handle, loss_handle, eval_handle, summary_handle 325 | 326 | def get_model_id_and_dir(self): 327 | model_id = "experiment_%d_batch_%d" % (self.experiment_id, self.batch_size) 328 | model_dir = os.path.join(self.checkpoint_dir, model_id) 329 | return model_id, model_dir 330 | 331 | def checkpoint(self, saver, step): 332 | model_name = "unet.model" 333 | model_id, model_dir = self.get_model_id_and_dir() 334 | 335 | if not os.path.exists(model_dir): 336 | os.makedirs(model_dir) 337 | 338 | saver.save(self.sess, os.path.join(model_dir, model_name), global_step=step) 339 | 340 | def restore_model(self, saver, model_dir): 341 | 342 | ckpt = tf.train.get_checkpoint_state(model_dir) 343 | 344 | if ckpt: 345 | saver.restore(self.sess, ckpt.model_checkpoint_path) 346 | print("restored model %s" % model_dir) 347 | else: 348 | print("fail to restore model %s" % model_dir) 349 | 350 | def generate_fake_samples(self, input_images, embedding_ids): 351 | input_handle, loss_handle, eval_handle, summary_handle = self.retrieve_handles() 352 | fake_images, real_images, \ 353 | d_loss, g_loss, l1_loss = self.sess.run([eval_handle.generator, 354 | eval_handle.target, 355 | loss_handle.d_loss, 356 | loss_handle.g_loss, 357 | loss_handle.l1_loss], 358 | feed_dict={ 359 | input_handle.real_data: input_images, 360 | input_handle.embedding_ids: embedding_ids, 361 | input_handle.no_target_data: input_images, 362 | input_handle.no_target_ids: embedding_ids 363 | }) 364 | return fake_images, real_images, d_loss, g_loss, l1_loss 365 | 366 | def validate_model(self, val_iter, epoch, step): 367 | labels, images = next(val_iter) 368 | fake_imgs, real_imgs, d_loss, g_loss, l1_loss = self.generate_fake_samples(images, labels) 369 | print("Sample: d_loss: %.5f, g_loss: %.5f, l1_loss: %.5f" % (d_loss, g_loss, l1_loss)) 370 | 371 | merged_fake_images = merge(scale_back(fake_imgs), [self.batch_size, 1]) 372 | merged_real_images = merge(scale_back(real_imgs), [self.batch_size, 1]) 373 | merged_pair = np.concatenate([merged_real_images, merged_fake_images], axis=1) 374 | 375 | model_id, _ = self.get_model_id_and_dir() 376 | 377 | model_sample_dir = os.path.join(self.sample_dir, model_id) 378 | if not os.path.exists(model_sample_dir): 379 | os.makedirs(model_sample_dir) 380 | 381 | sample_img_path = os.path.join(model_sample_dir, "sample_%02d_%04d.png" % (epoch, step)) 382 | misc.imsave(sample_img_path, merged_pair) 383 | 384 | def export_generator(self, save_dir, model_dir, model_name="gen_model"): 385 | saver = tf.train.Saver() 386 | self.restore_model(saver, model_dir) 387 | 388 | gen_saver = tf.train.Saver(var_list=self.retrieve_generator_vars()) 389 | gen_saver.save(self.sess, os.path.join(save_dir, model_name), global_step=0) 390 | 391 | def infer(self, source_obj, embedding_ids, model_dir, save_dir): 392 | source_provider = InjectDataProvider(source_obj) 393 | 394 | if isinstance(embedding_ids, int) or len(embedding_ids) == 1: 395 | embedding_id = embedding_ids if isinstance(embedding_ids, int) else embedding_ids[0] 396 | source_iter = source_provider.get_single_embedding_iter(self.batch_size, embedding_id) 397 | else: 398 | source_iter = source_provider.get_random_embedding_iter(self.batch_size, embedding_ids) 399 | 400 | tf.global_variables_initializer().run() 401 | saver = tf.train.Saver(var_list=self.retrieve_generator_vars()) 402 | self.restore_model(saver, model_dir) 403 | 404 | def save_imgs(imgs, count): 405 | p = os.path.join(save_dir, "inferred_%04d.png" % count) 406 | save_concat_images(imgs, img_path=p) 407 | print("generated images saved at %s" % p) 408 | 409 | count = 0 410 | batch_buffer = list() 411 | for labels, source_imgs in source_iter: 412 | fake_imgs = self.generate_fake_samples(source_imgs, labels)[0] 413 | merged_fake_images = merge(scale_back(fake_imgs), [self.batch_size, 1]) 414 | batch_buffer.append(merged_fake_images) 415 | if len(batch_buffer) == 10: 416 | save_imgs(batch_buffer, count) 417 | batch_buffer = list() 418 | count += 1 419 | if batch_buffer: 420 | # last batch 421 | save_imgs(batch_buffer, count) 422 | 423 | def interpolate(self, source_obj, between, model_dir, save_dir, steps): 424 | tf.global_variables_initializer().run() 425 | saver = tf.train.Saver(var_list=self.retrieve_generator_vars()) 426 | self.restore_model(saver, model_dir) 427 | # new interpolated dimension 428 | new_x_dim = steps + 1 429 | alphas = np.linspace(0.0, 1.0, new_x_dim) 430 | 431 | def _interpolate_tensor(_tensor): 432 | """ 433 | Compute the interpolated tensor here 434 | """ 435 | 436 | x = _tensor[between[0]] 437 | y = _tensor[between[1]] 438 | 439 | interpolated = list() 440 | for alpha in alphas: 441 | interpolated.append(x * (1. - alpha) + alpha * y) 442 | 443 | interpolated = np.asarray(interpolated, dtype=np.float32) 444 | return interpolated 445 | 446 | def filter_embedding_vars(var): 447 | var_name = var.name 448 | if var_name.find("embedding") != -1: 449 | return True 450 | if var_name.find("inst_norm/shift") != -1 or var_name.find("inst_norm/scale") != -1: 451 | return True 452 | return False 453 | 454 | embedding_vars = filter(filter_embedding_vars, tf.trainable_variables()) 455 | # here comes the hack, we overwrite the original tensor 456 | # with interpolated ones. Note, the shape might differ 457 | 458 | # this is to restore the embedding at the end 459 | embedding_snapshot = list() 460 | for e_var in embedding_vars: 461 | val = e_var.eval(session=self.sess) 462 | embedding_snapshot.append((e_var, val)) 463 | t = _interpolate_tensor(val) 464 | op = tf.assign(e_var, t, validate_shape=False) 465 | print("overwrite %s tensor" % e_var.name, "old_shape ->", e_var.get_shape(), "new shape ->", t.shape) 466 | self.sess.run(op) 467 | 468 | source_provider = InjectDataProvider(source_obj) 469 | input_handle, _, eval_handle, _ = self.retrieve_handles() 470 | for step_idx in range(len(alphas)): 471 | alpha = alphas[step_idx] 472 | print("interpolate %d -> %.4f + %d -> %.4f" % (between[0], 1. - alpha, between[1], alpha)) 473 | source_iter = source_provider.get_single_embedding_iter(self.batch_size, 0) 474 | batch_buffer = list() 475 | count = 0 476 | for _, source_imgs in source_iter: 477 | count += 1 478 | labels = [step_idx] * self.batch_size 479 | generated, = self.sess.run([eval_handle.generator], 480 | feed_dict={ 481 | input_handle.real_data: source_imgs, 482 | input_handle.embedding_ids: labels 483 | }) 484 | merged_fake_images = merge(scale_back(generated), [self.batch_size, 1]) 485 | batch_buffer.append(merged_fake_images) 486 | if len(batch_buffer): 487 | save_concat_images(batch_buffer, 488 | os.path.join(save_dir, "frame_%02d_%02d_step_%02d.png" % ( 489 | between[0], between[1], step_idx))) 490 | # restore the embedding variables 491 | print("restore embedding values") 492 | for var, val in embedding_snapshot: 493 | op = tf.assign(var, val, validate_shape=False) 494 | self.sess.run(op) 495 | 496 | def train(self, lr=0.0002, epoch=100, schedule=10, resume=True, flip_labels=False, 497 | freeze_encoder=False, fine_tune=None, sample_steps=50, checkpoint_steps=500): 498 | g_vars, d_vars = self.retrieve_trainable_vars(freeze_encoder=freeze_encoder) 499 | input_handle, loss_handle, _, summary_handle = self.retrieve_handles() 500 | 501 | if not self.sess: 502 | raise Exception("no session registered") 503 | 504 | learning_rate = tf.placeholder(tf.float32, name="learning_rate") 505 | d_optimizer = tf.train.AdamOptimizer(learning_rate, beta1=0.5).minimize(loss_handle.d_loss, var_list=d_vars) 506 | g_optimizer = tf.train.AdamOptimizer(learning_rate, beta1=0.5).minimize(loss_handle.g_loss, var_list=g_vars) 507 | tf.global_variables_initializer().run() 508 | real_data = input_handle.real_data 509 | embedding_ids = input_handle.embedding_ids 510 | no_target_data = input_handle.no_target_data 511 | no_target_ids = input_handle.no_target_ids 512 | 513 | # filter by one type of labels 514 | data_provider = TrainDataProvider(self.data_dir, filter_by=fine_tune) 515 | total_batches = data_provider.compute_total_batch_num(self.batch_size) 516 | val_batch_iter = data_provider.get_val_iter(self.batch_size) 517 | 518 | saver = tf.train.Saver(max_to_keep=3) 519 | summary_writer = tf.summary.FileWriter(self.log_dir, self.sess.graph) 520 | 521 | if resume: 522 | _, model_dir = self.get_model_id_and_dir() 523 | self.restore_model(saver, model_dir) 524 | 525 | current_lr = lr 526 | counter = 0 527 | start_time = time.time() 528 | 529 | for ei in range(epoch): 530 | train_batch_iter = data_provider.get_train_iter(self.batch_size) 531 | 532 | if (ei + 1) % schedule == 0: 533 | update_lr = current_lr / 2.0 534 | # minimum learning rate guarantee 535 | update_lr = max(update_lr, 0.0002) 536 | print("decay learning rate from %.5f to %.5f" % (current_lr, update_lr)) 537 | current_lr = update_lr 538 | 539 | for bid, batch in enumerate(train_batch_iter): 540 | counter += 1 541 | labels, batch_images = batch 542 | shuffled_ids = labels[:] 543 | if flip_labels: 544 | np.random.shuffle(shuffled_ids) 545 | # Optimize D 546 | _, batch_d_loss, d_summary = self.sess.run([d_optimizer, loss_handle.d_loss, 547 | summary_handle.d_merged], 548 | feed_dict={ 549 | real_data: batch_images, 550 | embedding_ids: labels, 551 | learning_rate: current_lr, 552 | no_target_data: batch_images, 553 | no_target_ids: shuffled_ids 554 | }) 555 | # Optimize G 556 | _, batch_g_loss = self.sess.run([g_optimizer, loss_handle.g_loss], 557 | feed_dict={ 558 | real_data: batch_images, 559 | embedding_ids: labels, 560 | learning_rate: current_lr, 561 | no_target_data: batch_images, 562 | no_target_ids: shuffled_ids 563 | }) 564 | # magic move to Optimize G again 565 | # according to https://github.com/carpedm20/DCGAN-tensorflow 566 | # collect all the losses along the way 567 | _, batch_g_loss, category_loss, cheat_loss, \ 568 | const_loss, l1_loss, tv_loss, g_summary = self.sess.run([g_optimizer, 569 | loss_handle.g_loss, 570 | loss_handle.category_loss, 571 | loss_handle.cheat_loss, 572 | loss_handle.const_loss, 573 | loss_handle.l1_loss, 574 | loss_handle.tv_loss, 575 | summary_handle.g_merged], 576 | feed_dict={ 577 | real_data: batch_images, 578 | embedding_ids: labels, 579 | learning_rate: current_lr, 580 | no_target_data: batch_images, 581 | no_target_ids: shuffled_ids 582 | }) 583 | passed = time.time() - start_time 584 | log_format = "Epoch: [%2d], [%4d/%4d] time: %4.4f, d_loss: %.5f, g_loss: %.5f, " + \ 585 | "category_loss: %.5f, cheat_loss: %.5f, const_loss: %.5f, l1_loss: %.5f, tv_loss: %.5f" 586 | print(log_format % (ei, bid, total_batches, passed, batch_d_loss, batch_g_loss, 587 | category_loss, cheat_loss, const_loss, l1_loss, tv_loss)) 588 | summary_writer.add_summary(d_summary, counter) 589 | summary_writer.add_summary(g_summary, counter) 590 | 591 | if counter % sample_steps == 0: 592 | # sample the current model states with val data 593 | self.validate_model(val_batch_iter, ei, counter) 594 | 595 | if counter % checkpoint_steps == 0: 596 | print("Checkpoint: save checkpoint step %d" % counter) 597 | self.checkpoint(saver, counter) 598 | # save the last checkpoint 599 | print("Checkpoint: last checkpoint step %d" % counter) 600 | self.checkpoint(saver, counter) 601 | -------------------------------------------------------------------------------- /model/utils.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import print_function 3 | from __future__ import absolute_import 4 | 5 | import os 6 | import glob 7 | 8 | import imageio 9 | import scipy.misc as misc 10 | import numpy as np 11 | from cStringIO import StringIO 12 | 13 | 14 | def pad_seq(seq, batch_size): 15 | # pad the sequence to be the multiples of batch_size 16 | seq_len = len(seq) 17 | if seq_len % batch_size == 0: 18 | return seq 19 | padded = batch_size - (seq_len % batch_size) 20 | seq.extend(seq[:padded]) 21 | return seq 22 | 23 | 24 | def bytes_to_file(bytes_img): 25 | return StringIO(bytes_img) 26 | 27 | 28 | def normalize_image(img): 29 | """ 30 | Make image zero centered and in between (-1, 1) 31 | """ 32 | normalized = (img / 127.5) - 1. 33 | return normalized 34 | 35 | 36 | def read_split_image(img): 37 | mat = misc.imread(img).astype(np.float) 38 | side = int(mat.shape[1] / 2) 39 | assert side * 2 == mat.shape[1] 40 | img_A = mat[:, :side] # target 41 | img_B = mat[:, side:] # source 42 | 43 | return img_A, img_B 44 | 45 | 46 | def shift_and_resize_image(img, shift_x, shift_y, nw, nh): 47 | w, h, _ = img.shape 48 | enlarged = misc.imresize(img, [nw, nh]) 49 | return enlarged[shift_x:shift_x + w, shift_y:shift_y + h] 50 | 51 | 52 | def scale_back(images): 53 | return (images + 1.) / 2. 54 | 55 | 56 | def merge(images, size): 57 | h, w = images.shape[1], images.shape[2] 58 | img = np.zeros((h * size[0], w * size[1], 3)) 59 | for idx, image in enumerate(images): 60 | i = idx % size[1] 61 | j = idx // size[1] 62 | img[j * h:j * h + h, i * w:i * w + w, :] = image 63 | 64 | return img 65 | 66 | 67 | def save_concat_images(imgs, img_path): 68 | concated = np.concatenate(imgs, axis=1) 69 | misc.imsave(img_path, concated) 70 | 71 | 72 | def compile_frames_to_gif(frame_dir, gif_file): 73 | frames = sorted(glob.glob(os.path.join(frame_dir, "*.png"))) 74 | print(frames) 75 | images = [misc.imresize(imageio.imread(f), interp='nearest', size=0.33) for f in frames] 76 | imageio.mimsave(gif_file, images, duration=0.1) 77 | return gif_file 78 | -------------------------------------------------------------------------------- /package.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import print_function 3 | from __future__ import absolute_import 4 | 5 | import argparse 6 | import glob 7 | import os 8 | import cPickle as pickle 9 | import random 10 | 11 | 12 | def pickle_examples(paths, train_path, val_path, train_val_split=0.1): 13 | """ 14 | Compile a list of examples into pickled format, so during 15 | the training, all io will happen in memory 16 | """ 17 | with open(train_path, 'wb') as ft: 18 | with open(val_path, 'wb') as fv: 19 | for p in paths: 20 | label = int(os.path.basename(p).split("_")[0]) 21 | with open(p, 'rb') as f: 22 | print("img %s" % p, label) 23 | img_bytes = f.read() 24 | r = random.random() 25 | example = (label, img_bytes) 26 | if r < train_val_split: 27 | pickle.dump(example, fv) 28 | else: 29 | pickle.dump(example, ft) 30 | 31 | 32 | parser = argparse.ArgumentParser(description='Compile list of images into a pickled object for training') 33 | parser.add_argument('--dir', dest='dir', required=True, help='path of examples') 34 | parser.add_argument('--save_dir', dest='save_dir', required=True, help='path to save pickled files') 35 | parser.add_argument('--split_ratio', type=float, default=0.1, dest='split_ratio', 36 | help='split ratio between train and val') 37 | args = parser.parse_args() 38 | 39 | if __name__ == "__main__": 40 | train_path = os.path.join(args.save_dir, "train.obj") 41 | val_path = os.path.join(args.save_dir, "val.obj") 42 | pickle_examples(sorted(glob.glob(os.path.join(args.dir, "*.jpg"))), train_path=train_path, val_path=val_path, 43 | train_val_split=args.split_ratio) 44 | -------------------------------------------------------------------------------- /train.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import print_function 3 | from __future__ import absolute_import 4 | 5 | import tensorflow as tf 6 | import argparse 7 | 8 | from model.unet import UNet 9 | 10 | parser = argparse.ArgumentParser(description='Train') 11 | parser.add_argument('--experiment_dir', dest='experiment_dir', required=True, 12 | help='experiment directory, data, samples,checkpoints,etc') 13 | parser.add_argument('--experiment_id', dest='experiment_id', type=int, default=0, 14 | help='sequence id for the experiments you prepare to run') 15 | parser.add_argument('--image_size', dest='image_size', type=int, default=256, 16 | help="size of your input and output image") 17 | parser.add_argument('--L1_penalty', dest='L1_penalty', type=int, default=100, help='weight for L1 loss') 18 | parser.add_argument('--Lconst_penalty', dest='Lconst_penalty', type=int, default=15, help='weight for const loss') 19 | parser.add_argument('--Ltv_penalty', dest='Ltv_penalty', type=float, default=0.0, help='weight for tv loss') 20 | parser.add_argument('--Lcategory_penalty', dest='Lcategory_penalty', type=float, default=1.0, 21 | help='weight for category loss') 22 | parser.add_argument('--embedding_num', dest='embedding_num', type=int, default=40, 23 | help="number for distinct embeddings") 24 | parser.add_argument('--embedding_dim', dest='embedding_dim', type=int, default=128, help="dimension for embedding") 25 | parser.add_argument('--epoch', dest='epoch', type=int, default=100, help='number of epoch') 26 | parser.add_argument('--batch_size', dest='batch_size', type=int, default=16, help='number of examples in batch') 27 | parser.add_argument('--lr', dest='lr', type=float, default=0.001, help='initial learning rate for adam') 28 | parser.add_argument('--schedule', dest='schedule', type=int, default=10, help='number of epochs to half learning rate') 29 | parser.add_argument('--resume', dest='resume', type=int, default=1, help='resume from previous training') 30 | parser.add_argument('--freeze_encoder', dest='freeze_encoder', type=int, default=0, 31 | help="freeze encoder weights during training") 32 | parser.add_argument('--fine_tune', dest='fine_tune', type=str, default=None, 33 | help='specific labels id to be fine tuned') 34 | parser.add_argument('--inst_norm', dest='inst_norm', type=int, default=0, 35 | help='use conditional instance normalization in your model') 36 | parser.add_argument('--sample_steps', dest='sample_steps', type=int, default=10, 37 | help='number of batches in between two samples are drawn from validation set') 38 | parser.add_argument('--checkpoint_steps', dest='checkpoint_steps', type=int, default=500, 39 | help='number of batches in between two checkpoints') 40 | parser.add_argument('--flip_labels', dest='flip_labels', type=int, default=None, 41 | help='whether flip training data labels or not, in fine tuning') 42 | args = parser.parse_args() 43 | 44 | 45 | def main(_): 46 | config = tf.ConfigProto() 47 | config.gpu_options.allow_growth = True 48 | 49 | with tf.Session(config=config) as sess: 50 | model = UNet(args.experiment_dir, batch_size=args.batch_size, experiment_id=args.experiment_id, 51 | input_width=args.image_size, output_width=args.image_size, embedding_num=args.embedding_num, 52 | embedding_dim=args.embedding_dim, L1_penalty=args.L1_penalty, Lconst_penalty=args.Lconst_penalty, 53 | Ltv_penalty=args.Ltv_penalty, Lcategory_penalty=args.Lcategory_penalty) 54 | model.register_session(sess) 55 | if args.flip_labels: 56 | model.build_model(is_training=True, inst_norm=args.inst_norm, no_target_source=True) 57 | else: 58 | model.build_model(is_training=True, inst_norm=args.inst_norm) 59 | fine_tune_list = None 60 | if args.fine_tune: 61 | ids = args.fine_tune.split(",") 62 | fine_tune_list = set([int(i) for i in ids]) 63 | model.train(lr=args.lr, epoch=args.epoch, resume=args.resume, 64 | schedule=args.schedule, freeze_encoder=args.freeze_encoder, fine_tune=fine_tune_list, 65 | sample_steps=args.sample_steps, checkpoint_steps=args.checkpoint_steps, 66 | flip_labels=args.flip_labels) 67 | 68 | 69 | if __name__ == '__main__': 70 | tf.app.run() 71 | --------------------------------------------------------------------------------