model.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. from __future__ import print_function
  2. import os
  3. import time
  4. import random
  5. from PIL import Image
  6. import tensorflow as tf
  7. import numpy as np
  8. from utils import *
  9. def concat(layers):
  10. return tf.concat(layers, axis=3)
  11. def DecomNet(input_im, layer_num, channel=64, kernel_size=3):
  12. input_max = tf.reduce_max(input_im, axis=3, keepdims=True)
  13. input_im = concat([input_max, input_im])
  14. with tf.variable_scope('DecomNet', reuse=tf.AUTO_REUSE):
  15. conv = tf.layers.conv2d(input_im, channel, kernel_size * 3, padding='same', activation=None, name="shallow_feature_extraction")
  16. for idx in range(layer_num):
  17. conv = tf.layers.conv2d(conv, channel, kernel_size, padding='same', activation=tf.nn.relu, name='activated_layer_%d' % idx)
  18. conv = tf.layers.conv2d(conv, 4, kernel_size, padding='same', activation=None, name='recon_layer')
  19. R = tf.sigmoid(conv[:,:,:,0:3])
  20. L = tf.sigmoid(conv[:,:,:,3:4])
  21. return R, L
  22. def RelightNet(input_L, input_R, channel=64, kernel_size=3):
  23. input_im = concat([input_R, input_L])
  24. with tf.variable_scope('RelightNet'):
  25. conv0 = tf.layers.conv2d(input_im, channel, kernel_size, padding='same', activation=None)
  26. conv1 = tf.layers.conv2d(conv0, channel, kernel_size, strides=2, padding='same', activation=tf.nn.relu)
  27. conv2 = tf.layers.conv2d(conv1, channel, kernel_size, strides=2, padding='same', activation=tf.nn.relu)
  28. conv3 = tf.layers.conv2d(conv2, channel, kernel_size, strides=2, padding='same', activation=tf.nn.relu)
  29. up1 = tf.image.resize_nearest_neighbor(conv3, (tf.shape(conv2)[1], tf.shape(conv2)[2]))
  30. deconv1 = tf.layers.conv2d(up1, channel, kernel_size, padding='same', activation=tf.nn.relu) + conv2
  31. up2 = tf.image.resize_nearest_neighbor(deconv1, (tf.shape(conv1)[1], tf.shape(conv1)[2]))
  32. deconv2= tf.layers.conv2d(up2, channel, kernel_size, padding='same', activation=tf.nn.relu) + conv1
  33. up3 = tf.image.resize_nearest_neighbor(deconv2, (tf.shape(conv0)[1], tf.shape(conv0)[2]))
  34. deconv3 = tf.layers.conv2d(up3, channel, kernel_size, padding='same', activation=tf.nn.relu) + conv0
  35. deconv1_resize = tf.image.resize_nearest_neighbor(deconv1, (tf.shape(deconv3)[1], tf.shape(deconv3)[2]))
  36. deconv2_resize = tf.image.resize_nearest_neighbor(deconv2, (tf.shape(deconv3)[1], tf.shape(deconv3)[2]))
  37. feature_gather = concat([deconv1_resize, deconv2_resize, deconv3])
  38. feature_fusion = tf.layers.conv2d(feature_gather, channel, 1, padding='same', activation=None)
  39. output = tf.layers.conv2d(feature_fusion, 1, 3, padding='same', activation=None)
  40. return output
  41. class lowlight_enhance(object):
  42. def __init__(self, sess):
  43. self.sess = sess
  44. self.DecomNet_layer_num = 5
  45. # build the model
  46. self.input_low = tf.placeholder(tf.float32, [None, None, None, 3], name='input_low')
  47. self.input_high = tf.placeholder(tf.float32, [None, None, None, 3], name='input_high')
  48. [R_low, I_low] = DecomNet(self.input_low, layer_num=self.DecomNet_layer_num)
  49. [R_high, I_high] = DecomNet(self.input_high, layer_num=self.DecomNet_layer_num)
  50. I_delta = RelightNet(I_low, R_low)
  51. I_low_3 = concat([I_low, I_low, I_low])
  52. I_high_3 = concat([I_high, I_high, I_high])
  53. I_delta_3 = concat([I_delta, I_delta, I_delta])
  54. self.output_R_low = R_low
  55. self.output_I_low = I_low_3
  56. self.output_I_delta = I_delta_3
  57. self.output_S = R_low * I_delta_3
  58. # loss
  59. self.recon_loss_low = tf.reduce_mean(tf.abs(R_low * I_low_3 - self.input_low))
  60. self.recon_loss_high = tf.reduce_mean(tf.abs(R_high * I_high_3 - self.input_high))
  61. self.recon_loss_mutal_low = tf.reduce_mean(tf.abs(R_high * I_low_3 - self.input_low))
  62. self.recon_loss_mutal_high = tf.reduce_mean(tf.abs(R_low * I_high_3 - self.input_high))
  63. self.equal_R_loss = tf.reduce_mean(tf.abs(R_low - R_high))
  64. self.relight_loss = tf.reduce_mean(tf.abs(R_low * I_delta_3 - self.input_high))
  65. self.Ismooth_loss_low = self.smooth(I_low, R_low)
  66. self.Ismooth_loss_high = self.smooth(I_high, R_high)
  67. self.Ismooth_loss_delta = self.smooth(I_delta, R_low)
  68. self.loss_Decom = self.recon_loss_low + self.recon_loss_high + 0.001 * self.recon_loss_mutal_low + 0.001 * self.recon_loss_mutal_high + 0.1 * self.Ismooth_loss_low + 0.1 * self.Ismooth_loss_high + 0.01 * self.equal_R_loss
  69. self.loss_Relight = self.relight_loss + 3 * self.Ismooth_loss_delta
  70. self.lr = tf.placeholder(tf.float32, name='learning_rate')
  71. optimizer = tf.train.AdamOptimizer(self.lr, name='AdamOptimizer')
  72. self.var_Decom = [var for var in tf.trainable_variables() if 'DecomNet' in var.name]
  73. self.var_Relight = [var for var in tf.trainable_variables() if 'RelightNet' in var.name]
  74. self.train_op_Decom = optimizer.minimize(self.loss_Decom, var_list = self.var_Decom)
  75. self.train_op_Relight = optimizer.minimize(self.loss_Relight, var_list = self.var_Relight)
  76. self.sess.run(tf.global_variables_initializer())
  77. self.saver_Decom = tf.train.Saver(var_list = self.var_Decom)
  78. self.saver_Relight = tf.train.Saver(var_list = self.var_Relight)
  79. print("[*] Initialize model successfully...")
  80. def gradient(self, input_tensor, direction):
  81. self.smooth_kernel_x = tf.reshape(tf.constant([[0, 0], [-1, 1]], tf.float32), [2, 2, 1, 1])
  82. self.smooth_kernel_y = tf.transpose(self.smooth_kernel_x, [1, 0, 2, 3])
  83. if direction == "x":
  84. kernel = self.smooth_kernel_x
  85. elif direction == "y":
  86. kernel = self.smooth_kernel_y
  87. return tf.abs(tf.nn.conv2d(input_tensor, kernel, strides=[1, 1, 1, 1], padding='SAME'))
  88. def ave_gradient(self, input_tensor, direction):
  89. return tf.layers.average_pooling2d(self.gradient(input_tensor, direction), pool_size=3, strides=1, padding='SAME')
  90. def smooth(self, input_I, input_R):
  91. input_R = tf.image.rgb_to_grayscale(input_R)
  92. return tf.reduce_mean(self.gradient(input_I, "x") * tf.exp(-10 * self.ave_gradient(input_R, "x")) + self.gradient(input_I, "y") * tf.exp(-10 * self.ave_gradient(input_R, "y")))
  93. def evaluate(self, epoch_num, eval_low_data, sample_dir, train_phase):
  94. print("[*] Evaluating for phase %s / epoch %d..." % (train_phase, epoch_num))
  95. for idx in range(len(eval_low_data)):
  96. input_low_eval = np.expand_dims(eval_low_data[idx], axis=0)
  97. if train_phase == "Decom":
  98. result_1, result_2 = self.sess.run([self.output_R_low, self.output_I_low], feed_dict={self.input_low: input_low_eval})
  99. if train_phase == "Relight":
  100. result_1, result_2 = self.sess.run([self.output_S, self.output_I_delta], feed_dict={self.input_low: input_low_eval})
  101. save_images(os.path.join(sample_dir, 'eval_%s_%d_%d.png' % (train_phase, idx + 1, epoch_num)), result_1, result_2)
  102. def train(self, train_low_data, train_high_data, eval_low_data, batch_size, patch_size, epoch, lr, sample_dir, ckpt_dir, eval_every_epoch, train_phase):
  103. assert len(train_low_data) == len(train_high_data)
  104. numBatch = len(train_low_data) // int(batch_size)
  105. # load pretrained model
  106. if train_phase == "Decom":
  107. train_op = self.train_op_Decom
  108. train_loss = self.loss_Decom
  109. saver = self.saver_Decom
  110. elif train_phase == "Relight":
  111. train_op = self.train_op_Relight
  112. train_loss = self.loss_Relight
  113. saver = self.saver_Relight
  114. load_model_status, global_step = self.load(saver, ckpt_dir)
  115. if load_model_status:
  116. iter_num = global_step
  117. start_epoch = global_step // numBatch
  118. start_step = global_step % numBatch
  119. print("[*] Model restore success!")
  120. else:
  121. iter_num = 0
  122. start_epoch = 0
  123. start_step = 0
  124. print("[*] Not find pretrained model!")
  125. print("[*] Start training for phase %s, with start epoch %d start iter %d : " % (train_phase, start_epoch, iter_num))
  126. start_time = time.time()
  127. image_id = 0
  128. for epoch in range(start_epoch, epoch):
  129. for batch_id in range(start_step, numBatch):
  130. # generate data for a batch
  131. batch_input_low = np.zeros((batch_size, patch_size, patch_size, 3), dtype="float32")
  132. batch_input_high = np.zeros((batch_size, patch_size, patch_size, 3), dtype="float32")
  133. for patch_id in range(batch_size):
  134. h, w, _ = train_low_data[image_id].shape
  135. x = random.randint(0, h - patch_size)
  136. y = random.randint(0, w - patch_size)
  137. rand_mode = random.randint(0, 7)
  138. batch_input_low[patch_id, :, :, :] = data_augmentation(train_low_data[image_id][x : x+patch_size, y : y+patch_size, :], rand_mode)
  139. batch_input_high[patch_id, :, :, :] = data_augmentation(train_high_data[image_id][x : x+patch_size, y : y+patch_size, :], rand_mode)
  140. image_id = (image_id + 1) % len(train_low_data)
  141. if image_id == 0:
  142. tmp = list(zip(train_low_data, train_high_data))
  143. random.shuffle(list(tmp))
  144. train_low_data, train_high_data = zip(*tmp)
  145. # train
  146. _, loss = self.sess.run([train_op, train_loss], feed_dict={self.input_low: batch_input_low, \
  147. self.input_high: batch_input_high, \
  148. self.lr: lr[epoch]})
  149. print("%s Epoch: [%2d] [%4d/%4d] time: %4.4f, loss: %.6f" \
  150. % (train_phase, epoch + 1, batch_id + 1, numBatch, time.time() - start_time, loss))
  151. iter_num += 1
  152. # evalutate the model and save a checkpoint file for it
  153. if (epoch + 1) % eval_every_epoch == 0:
  154. self.evaluate(epoch + 1, eval_low_data, sample_dir=sample_dir, train_phase=train_phase)
  155. self.save(saver, iter_num, ckpt_dir, "RetinexNet-%s" % train_phase)
  156. print("[*] Finish training for phase %s." % train_phase)
  157. def save(self, saver, iter_num, ckpt_dir, model_name):
  158. if not os.path.exists(ckpt_dir):
  159. os.makedirs(ckpt_dir)
  160. print("[*] Saving model %s" % model_name)
  161. saver.save(self.sess, \
  162. os.path.join(ckpt_dir, model_name), \
  163. global_step=iter_num)
  164. def load(self, saver, ckpt_dir):
  165. ckpt = tf.train.get_checkpoint_state(ckpt_dir)
  166. if ckpt and ckpt.model_checkpoint_path:
  167. full_path = tf.train.latest_checkpoint(ckpt_dir)
  168. try:
  169. global_step = int(full_path.split('/')[-1].split('-')[-1])
  170. except ValueError:
  171. global_step = None
  172. saver.restore(self.sess, full_path)
  173. return True, global_step
  174. else:
  175. print("[*] Failed to load model from %s" % ckpt_dir)
  176. return False, 0
  177. def test(self, test_low_data, test_high_data, test_low_data_names, save_dir, decom_flag):
  178. tf.global_variables_initializer().run()
  179. print("[*] Reading checkpoint...")
  180. load_model_status_Decom, _ = self.load(self.saver_Decom, './model/Decom')
  181. load_model_status_Relight, _ = self.load(self.saver_Relight, './model/Relight')
  182. if load_model_status_Decom and load_model_status_Relight:
  183. print("[*] Load weights successfully...")
  184. print("[*] Testing...")
  185. for idx in range(len(test_low_data)):
  186. print(test_low_data_names[idx])
  187. [_, name] = os.path.split(test_low_data_names[idx])
  188. suffix = name[name.find('.') + 1:]
  189. name = name[:name.find('.')]
  190. input_low_test = np.expand_dims(test_low_data[idx], axis=0)
  191. [R_low, I_low, I_delta, S] = self.sess.run([self.output_R_low, self.output_I_low, self.output_I_delta, self.output_S], feed_dict = {self.input_low: input_low_test})
  192. if decom_flag == 1:
  193. save_images(os.path.join(save_dir, name + "_R_low." + suffix), R_low)
  194. save_images(os.path.join(save_dir, name + "_I_low." + suffix), I_low)
  195. save_images(os.path.join(save_dir, name + "_I_delta." + suffix), I_delta)
  196. save_images(os.path.join(save_dir, name + "_S." + suffix), S)