Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

birds_skip_thought_demo.py 8.7 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
  1. from __future__ import division
  2. from __future__ import print_function
  3. import prettytensor as pt
  4. import tensorflow as tf
  5. import numpy as np
  6. import scipy.misc
  7. import os
  8. import argparse
  9. from PIL import Image, ImageDraw, ImageFont
  10. from misc.config import cfg, cfg_from_file
  11. from misc.utils import mkdir_p
  12. from misc import skipthoughts
  13. from stageII.model import CondGAN
  14. def parse_args():
  15. parser = argparse.ArgumentParser(description='Train a GAN network')
  16. parser.add_argument('--cfg', dest='cfg_file',
  17. help='optional config file',
  18. default=None, type=str)
  19. parser.add_argument('--gpu', dest='gpu_id',
  20. help='GPU device id to use [0]',
  21. default=-1, type=int)
  22. parser.add_argument('--caption_path', type=str, default=None,
  23. help='Path to the file with text sentences')
  24. # if len(sys.argv) == 1:
  25. # parser.print_help()
  26. # sys.exit(1)
  27. args = parser.parse_args()
  28. return args
  29. def sample_encoded_context(embeddings, model, bAugmentation=True):
  30. '''Helper function for init_opt'''
  31. # Build conditioning augmentation structure for text embedding
  32. # under different variable_scope: 'g_net' and 'hr_g_net'
  33. c_mean_logsigma = model.generate_condition(embeddings)
  34. mean = c_mean_logsigma[0]
  35. if bAugmentation:
  36. # epsilon = tf.random_normal(tf.shape(mean))
  37. epsilon = tf.truncated_normal(tf.shape(mean))
  38. stddev = tf.exp(c_mean_logsigma[1])
  39. c = mean + stddev * epsilon
  40. else:
  41. c = mean
  42. return c
  43. def build_model(sess, embedding_dim, batch_size):
  44. model = CondGAN(
  45. lr_imsize=cfg.TEST.LR_IMSIZE,
  46. hr_lr_ratio=int(cfg.TEST.HR_IMSIZE/cfg.TEST.LR_IMSIZE))
  47. embeddings = tf.placeholder(
  48. tf.float32, [batch_size, embedding_dim],
  49. name='conditional_embeddings')
  50. with pt.defaults_scope(phase=pt.Phase.test):
  51. with tf.variable_scope("g_net"):
  52. c = sample_encoded_context(embeddings, model)
  53. z = tf.random_normal([batch_size, cfg.Z_DIM])
  54. fake_images = model.get_generator(tf.concat(1, [c, z]))
  55. with tf.variable_scope("hr_g_net"):
  56. hr_c = sample_encoded_context(embeddings, model)
  57. hr_fake_images = model.hr_get_generator(fake_images, hr_c)
  58. ckt_path = cfg.TEST.PRETRAINED_MODEL
  59. if ckt_path.find('.ckpt') != -1:
  60. print("Reading model parameters from %s" % ckt_path)
  61. saver = tf.train.Saver(tf.all_variables())
  62. saver.restore(sess, ckt_path)
  63. else:
  64. print("Input a valid model path.")
  65. return embeddings, fake_images, hr_fake_images
  66. def drawCaption(img, caption):
  67. img_txt = Image.fromarray(img)
  68. # get a font
  69. fnt = ImageFont.truetype('Pillow/Tests/fonts/FreeMono.ttf', 50)
  70. # get a drawing context
  71. d = ImageDraw.Draw(img_txt)
  72. # draw text, half opacity
  73. d.text((10, 256), 'Stage-I', font=fnt, fill=(255, 255, 255, 255))
  74. d.text((10, 512), 'Stage-II', font=fnt, fill=(255, 255, 255, 255))
  75. if img.shape[0] > 832:
  76. d.text((10, 832), 'Stage-I', font=fnt, fill=(255, 255, 255, 255))
  77. d.text((10, 1088), 'Stage-II', font=fnt, fill=(255, 255, 255, 255))
  78. idx = caption.find(' ', 60)
  79. if idx == -1:
  80. d.text((256, 10), caption, font=fnt, fill=(255, 255, 255, 255))
  81. else:
  82. cap1 = caption[:idx]
  83. cap2 = caption[idx+1:]
  84. d.text((256, 10), cap1, font=fnt, fill=(255, 255, 255, 255))
  85. d.text((256, 60), cap2, font=fnt, fill=(255, 255, 255, 255))
  86. return img_txt
  87. def save_super_images(sample_batchs, hr_sample_batchs,
  88. captions_batch, batch_size,
  89. startID, save_dir):
  90. if not os.path.isdir(save_dir):
  91. print('Make a new folder: ', save_dir)
  92. mkdir_p(save_dir)
  93. # Save up to 16 samples for each text embedding/sentence
  94. img_shape = hr_sample_batchs[0][0].shape
  95. for j in range(batch_size):
  96. padding = np.zeros(img_shape)
  97. row1 = [padding]
  98. row2 = [padding]
  99. # First row with up to 8 samples
  100. for i in range(np.minimum(8, len(sample_batchs))):
  101. lr_img = sample_batchs[i][j]
  102. hr_img = hr_sample_batchs[i][j]
  103. hr_img = (hr_img + 1.0) * 127.5
  104. re_sample = scipy.misc.imresize(lr_img, hr_img.shape[:2])
  105. row1.append(re_sample)
  106. row2.append(hr_img)
  107. row1 = np.concatenate(row1, axis=1)
  108. row2 = np.concatenate(row2, axis=1)
  109. superimage = np.concatenate([row1, row2], axis=0)
  110. # Second 8 samples with up to 8 samples
  111. if len(sample_batchs) > 8:
  112. row1 = [padding]
  113. row2 = [padding]
  114. for i in range(8, len(sample_batchs)):
  115. lr_img = sample_batchs[i][j]
  116. hr_img = hr_sample_batchs[i][j]
  117. hr_img = (hr_img + 1.0) * 127.5
  118. re_sample = scipy.misc.imresize(lr_img, hr_img.shape[:2])
  119. row1.append(re_sample)
  120. row2.append(hr_img)
  121. row1 = np.concatenate(row1, axis=1)
  122. row2 = np.concatenate(row2, axis=1)
  123. super_row = np.concatenate([row1, row2], axis=0)
  124. superimage2 = np.zeros_like(superimage)
  125. superimage2[:super_row.shape[0],
  126. :super_row.shape[1],
  127. :super_row.shape[2]] = super_row
  128. mid_padding = np.zeros((64, superimage.shape[1], 3))
  129. superimage =\
  130. np.concatenate([superimage, mid_padding, superimage2], axis=0)
  131. top_padding = np.zeros((128, superimage.shape[1], 3))
  132. superimage =\
  133. np.concatenate([top_padding, superimage], axis=0)
  134. fullpath = '%s/sentence%d.jpg' % (save_dir, startID + j)
  135. superimage = drawCaption(np.uint8(superimage), captions_batch[j])
  136. scipy.misc.imsave(fullpath, superimage)
  137. if __name__ == "__main__":
  138. args = parse_args()
  139. if args.cfg_file is not None:
  140. cfg_from_file(args.cfg_file)
  141. if args.gpu_id != -1:
  142. cfg.GPU_ID = args.gpu_id
  143. if args.caption_path is not None:
  144. cfg.TEST.CAPTION_PATH = args.caption_path
  145. cap_path = cfg.TEST.CAPTION_PATH
  146. with open(cap_path) as f:
  147. captions = f.read().split('\n')
  148. captions_list = [cap for cap in captions if len(cap) > 0]
  149. print('Successfully load sentences from: ', cap_path)
  150. print('Total number of sentences:', len(captions_list))
  151. # path to save generated samples
  152. save_dir = cap_path[:cap_path.find('.txt')] + '-skip-thought'
  153. if len(captions_list) > 0:
  154. # Load skipthoughts model and generate embeddings from text sentences
  155. print('Load skipthoughts as encoder:')
  156. model = skipthoughts.load_model()
  157. embeddings = skipthoughts.encode(model, captions_list, verbose=False)
  158. num_embeddings = len(embeddings)
  159. print('num_embeddings:', num_embeddings, embeddings.shape)
  160. batch_size = np.minimum(num_embeddings, cfg.TEST.BATCH_SIZE)
  161. # Build StackGAN and load the model
  162. config = tf.ConfigProto(allow_soft_placement=True)
  163. with tf.Session(config=config) as sess:
  164. with tf.device("/gpu:%d" % cfg.GPU_ID):
  165. embeddings_holder, fake_images_opt, hr_fake_images_opt =\
  166. build_model(sess, embeddings.shape[-1], batch_size)
  167. count = 0
  168. while count < num_embeddings:
  169. iend = count + batch_size
  170. if iend > num_embeddings:
  171. iend = num_embeddings
  172. count = num_embeddings - batch_size
  173. embeddings_batch = embeddings[count:iend]
  174. captions_batch = captions_list[count:iend]
  175. samples_batchs = []
  176. hr_samples_batchs = []
  177. # Generate up to 16 images for each sentence with
  178. # randomness from noise z and conditioning augmentation.
  179. for i in range(np.minimum(16, cfg.TEST.NUM_COPY)):
  180. hr_samples, samples =\
  181. sess.run([hr_fake_images_opt, fake_images_opt],
  182. {embeddings_holder: embeddings_batch})
  183. samples_batchs.append(samples)
  184. hr_samples_batchs.append(hr_samples)
  185. save_super_images(samples_batchs,
  186. hr_samples_batchs,
  187. captions_batch,
  188. batch_size,
  189. count, save_dir)
  190. count += batch_size
  191. print('Finish generating samples for %d sentences:' % num_embeddings)
  192. print('Example sentences:')
  193. for i in xrange(np.minimum(10, num_embeddings)):
  194. print('Sentence %d: %s' % (i, captions_list[i]))
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...