spatial_transformer.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ==============================================================================
  15. import tensorflow as tf
  16. def transformer(U, theta, out_size, name='SpatialTransformer', **kwargs):
  17. """Spatial Transformer Layer
  18. Implements a spatial transformer layer as described in [1]_.
  19. Based on [2]_ and edited by David Dao for Tensorflow.
  20. Parameters
  21. ----------
  22. U : float
  23. The output of a convolutional net should have the
  24. shape [num_batch, height, width, num_channels].
  25. theta: float
  26. The output of the
  27. localisation network should be [num_batch, 6].
  28. out_size: tuple of two ints
  29. The size of the output of the network (height, width)
  30. References
  31. ----------
  32. .. [1] Spatial Transformer Networks
  33. Max Jaderberg, Karen Simonyan, Andrew Zisserman, Koray Kavukcuoglu
  34. Submitted on 5 Jun 2015
  35. .. [2] https://github.com/skaae/transformer_network/blob/master/transformerlayer.py
  36. Notes
  37. -----
  38. To initialize the network to the identity transform init
  39. ``theta`` to :
  40. identity = np.array([[1., 0., 0.],
  41. [0., 1., 0.]])
  42. identity = identity.flatten()
  43. theta = tf.Variable(initial_value=identity)
  44. """
  45. def _repeat(x, n_repeats):
  46. with tf.variable_scope('_repeat'):
  47. rep = tf.transpose(
  48. tf.expand_dims(tf.ones(shape=tf.stack([n_repeats, ])), 1), [1, 0])
  49. rep = tf.cast(rep, 'int32')
  50. x = tf.matmul(tf.reshape(x, (-1, 1)), rep)
  51. return tf.reshape(x, [-1])
  52. def _interpolate(im, x, y, out_size):
  53. with tf.variable_scope('_interpolate'):
  54. # constants
  55. num_batch = tf.shape(im)[0]
  56. height = tf.shape(im)[1]
  57. width = tf.shape(im)[2]
  58. channels = tf.shape(im)[3]
  59. x = tf.cast(x, 'float32')
  60. y = tf.cast(y, 'float32')
  61. height_f = tf.cast(height, 'float32')
  62. width_f = tf.cast(width, 'float32')
  63. out_height = out_size[0]
  64. out_width = out_size[1]
  65. zero = tf.zeros([], dtype='int32')
  66. max_y = tf.cast(tf.shape(im)[1] - 1, 'int32')
  67. max_x = tf.cast(tf.shape(im)[2] - 1, 'int32')
  68. # scale indices from [-1, 1] to [0, width/height]
  69. x = (x + 1.0)*(width_f) / 2.0
  70. y = (y + 1.0)*(height_f) / 2.0
  71. # do sampling
  72. x0 = tf.cast(tf.floor(x), 'int32')
  73. x1 = x0 + 1
  74. y0 = tf.cast(tf.floor(y), 'int32')
  75. y1 = y0 + 1
  76. x0 = tf.clip_by_value(x0, zero, max_x)
  77. x1 = tf.clip_by_value(x1, zero, max_x)
  78. y0 = tf.clip_by_value(y0, zero, max_y)
  79. y1 = tf.clip_by_value(y1, zero, max_y)
  80. dim2 = width
  81. dim1 = width*height
  82. base = _repeat(tf.range(num_batch)*dim1, out_height*out_width)
  83. base_y0 = base + y0*dim2
  84. base_y1 = base + y1*dim2
  85. idx_a = base_y0 + x0
  86. idx_b = base_y1 + x0
  87. idx_c = base_y0 + x1
  88. idx_d = base_y1 + x1
  89. # use indices to lookup pixels in the flat image and restore
  90. # channels dim
  91. im_flat = tf.reshape(im, tf.stack([-1, channels]))
  92. im_flat = tf.cast(im_flat, 'float32')
  93. Ia = tf.gather(im_flat, idx_a)
  94. Ib = tf.gather(im_flat, idx_b)
  95. Ic = tf.gather(im_flat, idx_c)
  96. Id = tf.gather(im_flat, idx_d)
  97. # and finally calculate interpolated values
  98. x0_f = tf.cast(x0, 'float32')
  99. x1_f = tf.cast(x1, 'float32')
  100. y0_f = tf.cast(y0, 'float32')
  101. y1_f = tf.cast(y1, 'float32')
  102. wa = tf.expand_dims(((x1_f-x) * (y1_f-y)), 1)
  103. wb = tf.expand_dims(((x1_f-x) * (y-y0_f)), 1)
  104. wc = tf.expand_dims(((x-x0_f) * (y1_f-y)), 1)
  105. wd = tf.expand_dims(((x-x0_f) * (y-y0_f)), 1)
  106. output = tf.add_n([wa*Ia, wb*Ib, wc*Ic, wd*Id])
  107. return output
  108. def _meshgrid(height, width):
  109. with tf.variable_scope('_meshgrid'):
  110. # This should be equivalent to:
  111. # x_t, y_t = np.meshgrid(np.linspace(-1, 1, width),
  112. # np.linspace(-1, 1, height))
  113. # ones = np.ones(np.prod(x_t.shape))
  114. # grid = np.vstack([x_t.flatten(), y_t.flatten(), ones])
  115. x_t = tf.matmul(tf.ones(shape=tf.stack([height, 1])),
  116. tf.transpose(tf.expand_dims(tf.linspace(-1.0, 1.0, width), 1), [1, 0]))
  117. y_t = tf.matmul(tf.expand_dims(tf.linspace(-1.0, 1.0, height), 1),
  118. tf.ones(shape=tf.stack([1, width])))
  119. x_t_flat = tf.reshape(x_t, (1, -1))
  120. y_t_flat = tf.reshape(y_t, (1, -1))
  121. ones = tf.ones_like(x_t_flat)
  122. grid = tf.concat(axis=0, values=[x_t_flat, y_t_flat, ones])
  123. return grid
  124. def _transform(theta, input_dim, out_size):
  125. with tf.variable_scope('_transform'):
  126. num_batch = tf.shape(input_dim)[0]
  127. height = tf.shape(input_dim)[1]
  128. width = tf.shape(input_dim)[2]
  129. num_channels = tf.shape(input_dim)[3]
  130. theta = tf.reshape(theta, (-1, 2, 3))
  131. theta = tf.cast(theta, 'float32')
  132. # grid of (x_t, y_t, 1), eq (1) in ref [1]
  133. height_f = tf.cast(height, 'float32')
  134. width_f = tf.cast(width, 'float32')
  135. out_height = out_size[0]
  136. out_width = out_size[1]
  137. grid = _meshgrid(out_height, out_width)
  138. grid = tf.expand_dims(grid, 0)
  139. grid = tf.reshape(grid, [-1])
  140. grid = tf.tile(grid, tf.stack([num_batch]))
  141. grid = tf.reshape(grid, tf.stack([num_batch, 3, -1]))
  142. # Transform A x (x_t, y_t, 1)^T -> (x_s, y_s)
  143. T_g = tf.matmul(theta, grid)
  144. x_s = tf.slice(T_g, [0, 0, 0], [-1, 1, -1])
  145. y_s = tf.slice(T_g, [0, 1, 0], [-1, 1, -1])
  146. x_s_flat = tf.reshape(x_s, [-1])
  147. y_s_flat = tf.reshape(y_s, [-1])
  148. input_transformed = _interpolate(
  149. input_dim, x_s_flat, y_s_flat,
  150. out_size)
  151. output = tf.reshape(
  152. input_transformed, tf.stack([num_batch, out_height, out_width, num_channels]))
  153. return output
  154. with tf.variable_scope(name):
  155. output = _transform(theta, U, out_size)
  156. return output
  157. def batch_transformer(U, thetas, out_size, name='BatchSpatialTransformer'):
  158. """Batch Spatial Transformer Layer
  159. Parameters
  160. ----------
  161. U : float
  162. tensor of inputs [num_batch,height,width,num_channels]
  163. thetas : float
  164. a set of transformations for each input [num_batch,num_transforms,6]
  165. out_size : int
  166. the size of the output [out_height,out_width]
  167. Returns: float
  168. Tensor of size [num_batch*num_transforms,out_height,out_width,num_channels]
  169. """
  170. with tf.variable_scope(name):
  171. num_batch, num_transforms = map(int, thetas.get_shape().as_list()[:2])
  172. indices = [[i]*num_transforms for i in xrange(num_batch)]
  173. input_repeated = tf.gather(U, tf.reshape(indices, [-1]))
  174. return transformer(input_repeated, thetas, out_size)