spatial_transformer.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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, downsample_factor=1, 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. downsample_factor : float
  29. A value of 1 will keep the original size of the image
  30. Values larger than 1 will downsample the image.
  31. Values below 1 will upsample the image
  32. example image: height = 100, width = 200
  33. downsample_factor = 2
  34. output image will then be 50, 100
  35. References
  36. ----------
  37. .. [1] Spatial Transformer Networks
  38. Max Jaderberg, Karen Simonyan, Andrew Zisserman, Koray Kavukcuoglu
  39. Submitted on 5 Jun 2015
  40. .. [2] https://github.com/skaae/transformer_network/blob/master/transformerlayer.py
  41. Notes
  42. -----
  43. To initialize the network to the identity transform init
  44. ``theta`` to :
  45. identity = np.array([[1., 0., 0.],
  46. [0., 1., 0.]])
  47. identity = identity.flatten()
  48. theta = tf.Variable(initial_value=identity)
  49. """
  50. def _repeat(x, n_repeats):
  51. with tf.variable_scope('_repeat'):
  52. rep = tf.transpose(tf.expand_dims(tf.ones(shape=tf.pack([n_repeats,])),1),[1,0])
  53. rep = tf.cast(rep, 'int32')
  54. x = tf.matmul(tf.reshape(x,(-1, 1)), rep)
  55. return tf.reshape(x,[-1])
  56. def _interpolate(im, x, y, downsample_factor):
  57. with tf.variable_scope('_interpolate'):
  58. # constants
  59. num_batch = tf.shape(im)[0]
  60. height = tf.shape(im)[1]
  61. width = tf.shape(im)[2]
  62. channels = tf.shape(im)[3]
  63. x = tf.cast(x, 'float32')
  64. y = tf.cast(y, 'float32')
  65. height_f = tf.cast(height, 'float32')
  66. width_f = tf.cast(width, 'float32')
  67. out_height = tf.cast(height_f // downsample_factor, 'int32')
  68. out_width = tf.cast(width_f // downsample_factor, 'int32')
  69. zero = tf.zeros([], dtype='int32')
  70. max_y = tf.cast(tf.shape(im)[1] - 1, 'int32')
  71. max_x = tf.cast(tf.shape(im)[2] - 1, 'int32')
  72. # scale indices from [-1, 1] to [0, width/height]
  73. x = (x + 1.0)*(width_f) / 2.0
  74. y = (y + 1.0)*(height_f) / 2.0
  75. # do sampling
  76. x0 = tf.cast(tf.floor(x), 'int32')
  77. x1 = x0 + 1
  78. y0 = tf.cast(tf.floor(y), 'int32')
  79. y1 = y0 + 1
  80. x0 = tf.clip_by_value(x0, zero, max_x)
  81. x1 = tf.clip_by_value(x1, zero, max_x)
  82. y0 = tf.clip_by_value(y0, zero, max_y)
  83. y1 = tf.clip_by_value(y1, zero, max_y)
  84. dim2 = width
  85. dim1 = width*height
  86. base = _repeat(tf.range(num_batch)*dim1, out_height*out_width)
  87. base_y0 = base + y0*dim2
  88. base_y1 = base + y1*dim2
  89. idx_a = base_y0 + x0
  90. idx_b = base_y1 + x0
  91. idx_c = base_y0 + x1
  92. idx_d = base_y1 + x1
  93. # use indices to lookup pixels in the flat image and restore channels dim
  94. im_flat = tf.reshape(im,tf.pack([-1, channels]))
  95. im_flat = tf.cast(im_flat, 'float32')
  96. Ia = tf.gather(im_flat, idx_a)
  97. Ib = tf.gather(im_flat, idx_b)
  98. Ic = tf.gather(im_flat, idx_c)
  99. Id = tf.gather(im_flat, idx_d)
  100. # and finally calculate interpolated values
  101. x0_f = tf.cast(x0, 'float32')
  102. x1_f = tf.cast(x1, 'float32')
  103. y0_f = tf.cast(y0, 'float32')
  104. y1_f = tf.cast(y1, 'float32')
  105. wa = tf.expand_dims(((x1_f-x) * (y1_f-y)),1)
  106. wb = tf.expand_dims(((x1_f-x) * (y-y0_f)),1)
  107. wc = tf.expand_dims(((x-x0_f) * (y1_f-y)),1)
  108. wd = tf.expand_dims(((x-x0_f) * (y-y0_f)),1)
  109. output = tf.add_n([wa*Ia, wb*Ib, wc*Ic, wd*Id])
  110. return output
  111. def _meshgrid(height, width):
  112. with tf.variable_scope('_meshgrid'):
  113. # This should be equivalent to:
  114. # x_t, y_t = np.meshgrid(np.linspace(-1, 1, width),
  115. # np.linspace(-1, 1, height))
  116. # ones = np.ones(np.prod(x_t.shape))
  117. # grid = np.vstack([x_t.flatten(), y_t.flatten(), ones])
  118. x_t = tf.matmul(tf.ones(shape=tf.pack([height, 1])),
  119. tf.transpose(tf.expand_dims(tf.linspace(-1.0, 1.0, width),1),[1,0]))
  120. y_t = tf.matmul(tf.expand_dims(tf.linspace(-1.0, 1.0, height),1),
  121. tf.ones(shape=tf.pack([1, width])))
  122. x_t_flat = tf.reshape(x_t,(1, -1))
  123. y_t_flat = tf.reshape(y_t,(1, -1))
  124. ones = tf.ones_like(x_t_flat)
  125. grid = tf.concat(0, [x_t_flat, y_t_flat, ones])
  126. return grid
  127. def _transform(theta, input_dim, downsample_factor):
  128. with tf.variable_scope('_transform'):
  129. num_batch = tf.shape(input_dim)[0]
  130. height = tf.shape(input_dim)[1]
  131. width = tf.shape(input_dim)[2]
  132. num_channels = tf.shape(input_dim)[3]
  133. theta = tf.reshape(theta, (-1, 2, 3))
  134. theta = tf.cast(theta, 'float32')
  135. # grid of (x_t, y_t, 1), eq (1) in ref [1]
  136. height_f = tf.cast(height, 'float32')
  137. width_f = tf.cast(width, 'float32')
  138. out_height = tf.cast(height_f // downsample_factor, 'int32')
  139. out_width = tf.cast(width_f // downsample_factor, 'int32')
  140. grid = _meshgrid(out_height, out_width)
  141. grid = tf.expand_dims(grid,0)
  142. grid = tf.reshape(grid,[-1])
  143. grid = tf.tile(grid,tf.pack([num_batch]))
  144. grid = tf.reshape(grid,tf.pack([num_batch, 3, -1]))
  145. # Transform A x (x_t, y_t, 1)^T -> (x_s, y_s)
  146. T_g = tf.batch_matmul(theta, grid)
  147. x_s = tf.slice(T_g, [0,0,0], [-1,1,-1])
  148. y_s = tf.slice(T_g, [0,1,0], [-1,1,-1])
  149. x_s_flat = tf.reshape(x_s,[-1])
  150. y_s_flat = tf.reshape(y_s,[-1])
  151. input_transformed = _interpolate(
  152. input_dim, x_s_flat, y_s_flat,
  153. downsample_factor)
  154. output = tf.reshape(input_transformed, tf.pack([num_batch, out_height, out_width, num_channels]))
  155. return output
  156. with tf.variable_scope(name):
  157. output = _transform(theta, U, downsample_factor)
  158. return output