TensorFlow如何用边值填充张量

时间:2018-05-04 12:27:35

标签: python tensorflow padding

如何使用边值填充张量(尺寸为WxHxC)?

例如:

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

变为:

[1, 1, 2, 3, 3]
[1, 1, 2, 3, 3]
[4, 4, 5, 6, 6]
[7, 7, 8, 9, 9]
[7, 7, 8, 9, 9]

2 个答案:

答案 0 :(得分:1)

使用tf.pad()和模式" SYMMETRIC" - 它将反映边缘上的值,但如果只进行1次深度填充,则相当于重复边缘值。如果你需要更多的填充,你必须重复操作,但你可以指数地(1先,然后2,然后4等)。此代码(已测试):

import tensorflow as tf

a = tf.reshape( tf.constant( range( 1, 10 ) ), ( 3, 3 ) )
b = tf.pad( a, [ [ 1, 1 ], [ 1, 1 ] ], "SYMMETRIC" )

with tf.Session() as sess:
    print( sess.run( b ) )

输出:

  

[[1 1 2 3 3]
   [1 1 2 3 3]
   [4 4 5 6 6]
   [7 7 8 9 9]
   [7 7 8 9 9]]

根据需要。

答案 1 :(得分:0)

作为补充,如果要使用像opencv这样的复制模式填充图像,则可以执行以下操作,dst_image是要填充的图像。 pad_h_up,pad_h_down,pad_w_left,pad_w_right是四个参数:

def pad_replica(image_pad, up,down, left, right):
    paddings_up = tf.constant([[1, 0],[0,0],[0,0]])
    paddings_down = tf.constant([[0, 1],[0,0],[0,0]])
    paddings_left = tf.constant([[0, 0],[1,0],[0,0]])
    paddings_right = tf.constant([[0, 0],[0, 1],[0 ,0]])
    i = tf.constant(0)
    c = lambda i,pad_len,pad_mode, image: tf.less(i, pad_len)
    def body(i,pad_len,pad_mode,image):
        i = i+1
        image = tf.pad(image, pad_mode,"SYMMETRIC")
        return [i, pad_len,pad_mode, image]
    [_, _, _, image_pad_up] = tf.while_loop(c, body, \
                                          [i, up, paddings_up, image_pad])
    i = tf.constant(0)
    [_, _, _, image_pad_down] = tf.while_loop(c, body, [i, down,paddings_down, image_pad_up])
    i = tf.constant(0)
    [_, _, _, image_pad_left] = tf.while_loop(c, body, [i, left, paddings_left, image_pad_down])
    i = tf.constant(0)
    [_, _, _, image_pad_right] = tf.while_loop(c, body, [i, right,paddings_right, image_pad_left])
    i = tf.constant(0)
    return image_pad_right
dst_image.set_shape([None, None, None])
dst_image = pad_replica(dst_image,\
             tf.cast(pad_h_up, tf.int32),\
            tf.cast(pad_h_down,tf.int32),\
            tf.cast(pad_w_left, tf.int32),\
            tf.cast(pad_w_right,tf.int32)
            )