这是 tensorflow 中周期性填充的实现,适用于一批二维图像。它使用切片和 tf.concat:
def periodic_padding(x, padding=1):
'''
x: shape (batch_size, d1, d2)
return x padded with periodic boundaries. i.e. torus or donut
'''
d1 = x.shape[1] # dimension 1: height
d2 = x.shape[2] # dimension 2: width
p = padding
# assemble padded x from slices
# tl,tc,tr
# padded_x = ml,mc,mr
# bl,bc,br
top_left = x[:, -p:, -p:] # top left
top_center = x[:, -p:, :] # top center
top_right = x[:, -p:, :p] # top right
middle_left = x[:, :, -p:] # middle left
middle_center = x # middle center
middle_right = x[:, :, :p] # middle right
bottom_left = x[:, :p, -p:] # bottom left
bottom_center = x[:, :p, :] # bottom center
bottom_right = x[:, :p, :p] # bottom right
top = tf.concat([top_left, top_center, top_right], axis=2)
middle = tf.concat([middle_left, middle_center, middle_right], axis=2)
bottom = tf.concat([bottom_left, bottom_center, bottom_right], axis=2)
padded_x = tf.concat([top, middle, bottom], axis=1)
return padded_x
import tensorflow as tf
a = tf.constant([
[[1,2,3],[4,5,6],[7,8,9]],
[[11,12,13],[14,15,16],[17,18,19]],
])
result = periodic_padding(a, padding=1)
sess = tf.InteractiveSession()
print('a:')
print(a.eval())
print('padded a:')
print(result.eval())
sess.close()
例子的输出是:
a:
[[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]]
[[11 12 13]
[14 15 16]
[17 18 19]]]
padded a:
[[[ 9 7 8 9 7]
[ 3 1 2 3 1]
[ 6 4 5 6 4]
[ 9 7 8 9 7]
[ 3 1 2 3 1]]
[[19 17 18 19 17]
[13 11 12 13 11]
[16 14 15 16 14]
[19 17 18 19 17]
[13 11 12 13 11]]]